/ 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
Copy this code and paste it in your HTML
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); }; };