Blog

  • Capture Browser Close Jquery Javascript

    Previously I had a task where I had to hit an ajax call to server on browser close event.

    onbeforeunload is an javascript event which occurs on window close but there is a problem with it.

    It is bind to all events that occur on window unload like click on a hyperlink , page redirect or page refresh.

    Following is the JS code for handling these situations.You need to test this on different browsers before applying.

    var validNavigation = false; 
    
    
    function wireUpWindowUnloadEvents() {
     /*
     * List of events which are triggered onbeforeunload on IE
     * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
     */
    
     // Attach the event keypress to exclude the F5 refresh
     $(document).on('keypress', function(e) {
       if (e.keyCode == 116){
         validNavigation = true;
       }
     });
    
     // Attach the event click for all links in the page
     $(document).on("click", "a" , function() {
       validNavigation = true;
     });
    
     // Attach the event submit for all forms in the page
     $(document).on("submit", "form" , function() {
       validNavigation = true;
     });
    
     // Attach the event click for all inputs in the page
     $(document).bind("click", "input[type=submit]" , function() {
       validNavigation = true;
     });
     
     $(document).bind("click", "button[type=submit]" , function() {
       validNavigation = true;
     });
      
    }
    
    
    
    function windowCloseEvent()
           {
            window.onbeforeunload = function() {
             if (!validNavigation){
              callServerForBrowserCloseEvent();
             }
            }
           }
    
    
    
    function callServerForBrowserCloseEvent()
    {
     //…...Do you operation here
    }
    

     

    For more information you can follow this link .

     

    Thanks

Tags: grails , ajax