9

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

Alex
  • 750
  • 5
  • 15
  • 33

2 Answers2

17

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

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
0

In addition to the previous answer - you cannot handle when the user reloaded the page or canceled the page leave, so I made a simple package that does this - https://www.npmjs.com/package/@garage-panda/use-before-unload

Also keep in mind that you cannot execute a function when the user leave the page.

Vladimir Vladimirov
  • 269
  • 1
  • 2
  • 14