Confirm leaving your site onbeforeunload


/ Published in: JavaScript
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. window.onload = function(){
  2.  
  3. var allowUnload = true;
  4.  
  5. window.onbeforeunload = function(e){
  6. //allowUnload will allow us to see if user recently clicked something if so we wont allow the beforeunload.
  7. if(allowUnload){
  8. //message to be returned to the popup box.
  9. var message = 'Are you sure you want to leave this page message',
  10. e = e||window.event;
  11. if(e)
  12. e.returnValue=message; // IE
  13. return message; // Safari
  14. }
  15. };
  16. // We need this to allow us to see if user has clicked anywhere if user has clicked we wont allow beforeunload to run.
  17. document.getElementsByTagName('body')[0].onclick = function(){
  18. allowUnload = false;
  19. //setTimeout so we can reset allowUnload incase user didn't leave the page but randomly clicked.
  20. setTimeout(function(){ allowUnload = true; },100);
  21. };
  22. };

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.