window.onbeforeunload not displaying the alert box

Alex picture Alex · Nov 19, 2013 · Viewed 15.2k times · Source

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..

Answer

CodingIntrigue picture CodingIntrigue · Nov 19, 2013

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