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..
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.
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.
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 ''; });
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With