Ousman Ahmad
Ousman Ahmad

Reputation: 399

JavaScript: trying to exit onbeforeunload function in an if statement

I have the following JavaScript code at the head section of the page:

window.onbeforeunload =  function()
{var r=confirm("Really leave?");
if (r==true)
{
self.close;
}
else
{
break;
}} 

After 'else,' I want code that will cancel the onbeforeunload so that when the user clicks 'cancel,' the webpage should not exit. Can this be done?

Upvotes: 2

Views: 998

Answers (1)

Martin Buberl
Martin Buberl

Reputation: 47144

You can't modify the behavior of the browser's default onbeforeunload dialogue because of security reasons.

Let the dialogue handle the 'Really leave?' logic for you (it will generate the button logic).

The only thing you can modify is the message itself (in some browsers only partial) and a logic if the window should appear at all (e.g. only if the user made changes):

window.onbeforeunload = function() {
   return 'Your custom message why the user should not leave';
}

Hope that helps.

Upvotes: 1

Related Questions