Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.onbeforeunload not displaying the alert box

I just want to show a message before leaving the page, but my code doesn't works:

window.onload=function(){
    alert("Page with a digital clock");
    setInterval(clock,1000);
}

window.onbeforeunload=function(){
    alert("Are you sure to leave this page?");
}

The "onload alert" works fine, but the second is not working..

like image 255
Alex Avatar asked Nov 19 '13 09:11

Alex


People also ask

Why is Onbeforeunload not working?

1) It refuses to call all blocking native functions (alert, prompt, confirm). It is obvious from User perspective. 3) It is fired only if there was ANY interaction of the user with the site. Without ANY interaction (even one click anywhere) event onbeforeunload won't be fired.

What triggers Onbeforeunload?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.

How do I stop Windows unloading?

Since jQuery 1.4, you can bind the 'beforeunload' event to $(windows) object to stop a page from exit , unload or navigating away. $(window). bind('beforeunload', function(){ return ''; });


1 Answers

You can't put an alert inside onbeforeunload. Most browsers will do this for you so you don't need to handle it, you need to return the confirm message to the method instead:

window.onbeforeunload=function(){
    return "Are you sure to leave this page?";
}

Here are the docs for the method on MDN.

When this event returns a non-void value, the user is prompted to confirm the page unload. In most browsers, the return value of the event is displayed in this dialog

like image 196
CodingIntrigue Avatar answered Sep 17 '22 13:09

CodingIntrigue