Stop window unload

I have written the following code to confirm if user wants to leave the chat. I want to stop the unload if user clicks Cancel. How to?

function exit() {
var c = confirm(‘You are about to leave the Chat Room.
Please click OK to continue.’);
//Code to run if user clicks OK.
//Code to be written to stop the window event


By the time the onunload event fires, it’s too late to cancel it.

You would need to use the onbeforeunload event instead.

Be warned though, you can not filter the types of actions that are performed that cause the unload event to fire.

It could be someone clicking a link to somewhere else on your website.
It could be someone submitting a form on your page
It could be someone going to a different website
It could be someone closing the tab/window that the webpage is in
It could be someone closing the entire web browser

It is not possible to determine which one of these causes the unload event to occur.

I used onbeforeunload, but it causes an issue in IE - Clicking on any dummy link i.e. <a href=“javascript:void(0);”>Test</a>, also fire this event.


Also onbeforeunload is a proprietary event and so only a couple of browsers recognise it at all.