Blog Archive

jQuery STOP user from page exit - window beforeunload event

How to warn a user from exiting a HTML page?

If you want to stop and warn a user before they move away from a page then you can use the $(window).bind('beforeunload', callback) to achieve that. This is very useful when user clicks on the back button, hit refresh or try to close the browser window. You can alert the user about saving their changes and they can choose to either stay on the page or leave, similar to the javaScript confirm().

Now this issue with binding the window object to the beforeunload event is that it will trigger even for legit actions such as when the user clicks on a button to save the changes or clicks on a hyperlink to navigate to a new page. The avoid that we have created a global variable and set that the value to true or false when they hover over the actual page elements such as buttons, hyperlinks, etc. In this example we have added the hover() function to all page elements but you can customize that based on selectors.


jquery stop page exit unload
jquery stop page exit unload


<html>
<head>
<title>jQuery Stop user from page exit</title>

<link
 href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
 rel="stylesheet" type="text/css" />

<script
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"
 type="text/javascript"></script>
<script
 src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
 type="text/javascript"></script>
<script type="text/javascript">
        $(document).ready(function() {
         
         var displayMessage = true;
         
         $(window).bind('beforeunload', function(){
          //the custom message for page unload doesn't work on Firefox
          if(displayMessage){
           var message =  '-- You specify a custom message here ---' + 
           '\n Thanks for visiting my site!';
           return message;
          } 
         });
         
         $('*').hover(
          function(){displayMessage = false;},
          function(){displayMessage = true;} 
            );  
           
            $('#myButton').click(function() {
             window.location.href = "http://demo.mysamplecode.com";
            })
            
            $('a[href^="javascript:"]').click(function(event) {
             event.preventDefault();
             window.location.href = "http://demo.mysamplecode.com";
            });
        });     
    </script>

</head>
<body>
 <p>If you try to hit browser back button or Reload the page it
  should stop and alert the user, whereas if you click on the button or
  the link below it should just let you move forward.</p>
 <input id="myButton" type="button" value="Go to MySampleCode.com" />
 <a href="javascript:void(0);">Go to MySampleCode.com</a>
</body>
</html>