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.’);
if(c){
//Code to run if user clicks OK.
}
else{
//Code to be written to stop the window event
}
}
window.onunload=exit;
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.