/ Published in: JavaScript
I needed a method to confirm unload of the site, but still allow the user to click around the site this was my method of doing so.
Expand |
Embed | Plain Text
window.onload = function(){ var allowUnload = true; window.onbeforeunload = function(e){ //allowUnload will allow us to see if user recently clicked something if so we wont allow the beforeunload. if(allowUnload){ //message to be returned to the popup box. var message = 'Are you sure you want to leave this page message', e = e||window.event; if(e) e.returnValue=message; // IE return message; // Safari } }; // We need this to allow us to see if user has clicked anywhere if user has clicked we wont allow beforeunload to run. document.getElementsByTagName('body')[0].onclick = function(){ allowUnload = false; //setTimeout so we can reset allowUnload incase user didn't leave the page but randomly clicked. setTimeout(function(){ allowUnload = true; },100); }; };
Comments
Subscribe to comments
You need to login to post a comment.

With using this event 'onbeforeunload' , can we prevent alert message when we click on browser back button.
I have used this event and if I click on browser back button, this event should not fire and stop the alert message.
Please help me out if any one know about it.
Regards, Tejas Savaliya