Posted By

MichaelM on 12/24/10



Versions (?)

Confirm leaving your site onbeforeunload

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

  1. window.onload = function(){
  3. var allowUnload = true;
  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  


RSS Icon Subscribe to comments
Posted By: tejas14883 on December 13, 2012

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

You need to login to post a comment.