jQuery & Javascript – Capture the Browser or Tab Closed Event

I was working on a WordPress project which i need to clear the PHP session when the browser or browser tab is closed. Although Javascript provides the window.onbeforeunload event but it will be triggered even whenever you leave the website. Finally i got a simple solution from Daniel Melo in StackOverflow. The following code required jQuery and i have included the Google one in the HTML.

In your web root, create the js/check_browser_close.js.

/**
 * This javascript file checks for the brower/browser tab action.
 * It is based on the file menstioned by Daniel Melo.
 * Reference: http://stackoverflow.com/questions/1921941/close-kill-the-session-when-the-browser-or-tab-is-closed
 */
var validNavigation = false;

function endSession() {
  // Browser or broswer tab is closed
  // Do sth here ...
  alert("bye");
}

function wireUpEvents() {
  /*
  * For a list of events that triggers onbeforeunload on IE
  * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
  */
  window.onbeforeunload = function() {
      if (!validNavigation) {
         endSession();
      }
  }

  // Attach the event keypress to exclude the F5 refresh
  $(document).bind('keypress', function(e) {
    if (e.keyCode == 116){
      validNavigation = true;
    }
  });

  // Attach the event click for all links in the page
  $("a").bind("click", function() {
    validNavigation = true;
  });

  // Attach the event submit for all forms in the page
  $("form").bind("submit", function() {
    validNavigation = true;
  });

  // Attach the event click for all inputs in the page
  $("input[type=submit]").bind("click", function() {
    validNavigation = true;
  });
  
}

// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
  wireUpEvents();  
});

 

Also create the following .html in your web root to test the above Javascript file.

<html>
  <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    <script type="text/javascript" src="js/check_browser_close.js"></script>
  </head>
  <body>
    <h1>Eureka!</h1>
      <a href="http://www.google.com">Google</a>
      <a href="http://www.yahoo.com">Yahoo</a>
      <a href="http://ykyuen.wordpress.com">Eureka!</a>
  </body>
</html>

 

A alert box will be shown when you closed the browser or the browser tab.

Done =)

Reference:

Update @ 2012-02-19: In Chrome, window.onbeforeunload is required to return a string. please try the following check_browser_close.js.

/**
 * This javascript file checks for the brower/browser tab action.
 * It is based on the file menstioned by Daniel Melo.
 * Reference: http://stackoverflow.com/questions/1921941/close-kill-the-session-when-the-browser-or-tab-is-closed
 */
var validNavigation = false;

function wireUpEvents() {
  /**
   * For a list of events that triggers onbeforeunload on IE
   * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
   *
   * onbeforeunload for IE and chrome
   * check http://stackoverflow.com/questions/1802930/setting-onbeforeunload-on-body-element-in-chrome-and-ie-using-jquery
   */
  var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the user to be able to leave withou confirmation
  var leave_message = 'You sure you want to leave?'
  function goodbye(e) {
    if (!validNavigation) {
      if (dont_confirm_leave!==1) {
        if(!e) e = window.event;
        //e.cancelBubble is supported by IE - this will kill the bubbling process.
        e.cancelBubble = true;
        e.returnValue = leave_message;
        //e.stopPropagation works in Firefox.
        if (e.stopPropagation) {
          e.stopPropagation();
          e.preventDefault();
        }
        //return works for Chrome and Safari
        return leave_message;
      }
    }
  }
  window.onbeforeunload=goodbye;

  // Attach the event keypress to exclude the F5 refresh
  $(document).bind('keypress', function(e) {
    if (e.keyCode == 116){
      validNavigation = true;
    }
  });

  // Attach the event click for all links in the page
  $("a").bind("click", function() {
    validNavigation = true;
  });

  // Attach the event submit for all forms in the page
  $("form").bind("submit", function() {
    validNavigation = true;
  });

  // Attach the event click for all inputs in the page
  $("input[type=submit]").bind("click", function() {
    validNavigation = true;
  });

}

// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
  wireUpEvents();
});

 

Update @ 2012-06-15: If there is any link which implements ajax feature, you can refer to this approach. Thanks Immo. =)

Reference: StackOverflow – Setting onbeforeunload on body element in Chrome and IE using jQuery

About these ads

238 thoughts on “jQuery & Javascript – Capture the Browser or Tab Closed Event”

    1. I have included the F5 press exception in check_browser_close.js

      ...
        // Attach the event keypress to exclude the F5 refresh
        $('html').bind('keypress', function(e) {
          if (e.keyCode == 116){
            validNavigation = true;
          }
        });
      ...
      

      But this only works for user who press the F5 button, if the user click the refresh button using the mouse, the endSession() will be stilled fired.

      hope this help. =)

      Like

    2. yes u can use this code:

      window.onload = function () {
        document.onkeydown = function (e) {  
          return (e.which || e.keyCode) != 116;
        };
      

      Like

      1. Hi, I works for me, I’m closing the session on tab/ browser close. If user clicks “stay on page” option i don’t want to do any action.
        Is there any way?

        Like

  1. This was a real help….Am a pretty newbie,…I just had requirement….

    I want to update a my SQL database and set the status of an online user to ‘0’ from ‘1’ from the function endsession()….i am stuck here…I tried using an AJAX code here to run a update query but its not working…

    Here is what i’ve done…

    var validNavigation = false;
    
    function endSession() 
    {
      // Browser or broswer tab is closed
      // Do sth here ...
    	alert("You are about to close your page and session");
      
    	var xmlhttp;
    
    	URL = 'localhost/close.php?id=3';
    
    	if (window.XMLHttpRequest)
    	{
    	// code for IE7+, Firefox, Chrome, Opera, Safari
    	xmlhttp=new XMLHttpRequest();
    	}
    	else
    	{
    	// code for IE6, IE5
      	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    	}
    	
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 &amp;&amp; xmlhttp.status==200)
        {
        document.getElementById("PC").innerHTML=xmlhttp.responseText;
    	
        }
      }
    xmlhttp.open("GET",URL,false);
    xmlhttp.send();
    
      
    }
    
    function wireUpEvents()
    {
      /*
      * For a list of events that triggers onbeforeunload on IE
      * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
      */
      window.onbeforeunload = function()
      {
          if (!validNavigation)
    	  {
             endSession();
          }
      }
    
      // Attach the event keypress to exclude the F5 refresh
      $('html').bind('keypress', function(e) {
        if (e.keyCode == 116){
          validNavigation = true;
        }
      });
    
      // Attach the event click for all links in the page
      $("a").bind("click", function() {
        validNavigation = true;
      });
    
      // Attach the event submit for all forms in the page
      $("form").bind("submit", function() {
        validNavigation = true;
      });
    
      // Attach the event click for all inputs in the page
      $("input[type=submit]").bind("click", function() {
        validNavigation = true;
      });
    
    }
    
    // Wire up the events as soon as the DOM tree is ready
    $(document).ready(function() {
      wireUpEvents();
    });
    

    Like

  2. I have master page and i save data in content page and then do alt+F4 i want to refresh parent page. But it will not calling method endSession() but when i do postback and then do alt+F4 it will call endSession() and my parent page get refereshed.

    function endSession() {
    parent.window.opener.RefreshRiskGrid(); window.close();
    }

    Please give me suggestion.

    Thanks in advance.

    Like

      1. I have form with image button, link button and Dropdown list, its working fine when click on link or any button, but when select dropdown, this event is called and application signout.

        Like

      2. In that case you have to add an extra checking when user select the dropdown

          ...
          // Attach the event click for all inputs in the page
          $("input[type=submit]").bind("click", function() {
            validNavigation = true;
          });
        
          // Attach the event when the dropdown option is changed
          $("select#select-id").bind("change", function() {
            validNavigation = true;
          });
          ...
        

        Like

  3. HI

    I was wondering , how I can use ur code and disable when someone click on the refresh button in ALL the browsers?

    Is there a solution for that

    Thanks

    Like

  4. Hi ykyuen,
    Thanks for this great script! I’m using it to load a survey of why the user is leaving the page without completing a form. It works great for this, but I’m having one problem. If the user tries to submit the form and fails because the form was incomplete, then closes the window, the alert no longer comes up. Please see here:

    http://request4.info/grantham-survey-if-test.html

    Close the page, an alert comes up. Then open the link again. Click Request Information (without filling anything in), and then close the page. Now the alert doesn’t come up. What do I need to do? I’m not changing the value of dont_confirm_leave anywhere… A big thanks in advance for your help!
    –Kyle

    Like

    1. When the user clicks the Request Information button, the validNavigation is set to TRUE even the form validation is not passed. That’s y the alert box didn’t come out when you close the page.

      How do u implement the form validation?

      One way to resolve ur problem is that whenever the validation is prompted, reset the validNavigation to FALSE.

      Like

      1. Thanks, that did it! I had to do a settimeout for changing the validNavigation to false though – otherwise the validation function would return false and immediately reset validNavigation to true! Thanks again!

        Also, could you possibly remove my last name from the original post? I’m not sure what I was thinking – I don’t like to use my full name :) Thanks,
        –Kyle

        Like

  5. nice solution, but i have a problem to open exit survey after closing page. How can it implemented in chrome as it just return message after closing window. KIndly help on it.

    Like

    1. I wonder if the following could solve the problem
      1. Change

      $('html').bind('keypress', function(e) {
        if (e.keyCode == 116){
          validNavigation = true;
        }
      });
      

      To

      $('document').bind('keydown', function(e) {
        if (e.keyCode == 116){
          validNavigation = true;
        }
      });
      

      OR

      2. Adding this to the wireUpEvents().

      document.onkeydown = function disableKeys() {
        if( typeof event != 'undefined' ) {
          if(event.keyCode == 116) {
            validNavigation = true;
            event.keyCode = 0;
            //return false; //return false if u want to disable refresh
          }
        }
      };
      

       

      Reference:

      Like

      1. Thank u very much ykyuen, both solutions worked.
        I’m facing with another silly problem hope you can give some idea about it.
        My website is having some certificate problem, when I log’s in IE gives Information bar giving message “cannot display contents due to certicate errors” when I right click and choose option of “Display blocked content” it refreshes whole page. How can I capture the automatic page refresh of browser in the above javascriptcode?

        Thanks,
        KD

        Like

      2. It seems that there is no way in Javascript to capture the “Display blocked content refresh”. It should be treated as normal refresh. Maybe you could try to solve the certificate problem.

        Like

  6. Hi ykyuen,

    Have you found solution for browser back link, refresh button and enter on url ? I have added all conditions but could not find any solution for these 3 conditions ?
    Any help is much appreciate.

    Like

    1. Maybe you could try the cookie method in this comment.

      About the enter on url, it should be handled by the following part.

      // Attach the event click for all links in the page
      $("a").bind("click", function() {
        validNavigation = true;
      });
      

      Like

  7. where to use prompt box and ajax call ?

    function goodbye(e) {
      if (!validNavigation) {
        if (dont_confirm_leave!==1) {
          if(!e) e = window.event;
          //e.cancelBubble is supported by IE - this will kill the bubbling process.
          e.cancelBubble = true;
          e.returnValue = leave_message;
          //e.stopPropagation works in Firefox.
          if (e.stopPropagation) {
            e.stopPropagation();
            e.preventDefault();
          }
          //return works for Chrome and Safari
          return leave_message;
        }
      }
    }
    

    Like

      1. I have used the code in this way,it works fine in mozilla,but in chrome it doesnt works , if call endSession() inside function goodbye(e).
        below is my code(i have commented goodbye(e) function here) ,can you help me out in this

        /**
         * This javascript file checks for the brower/browser tab action.
         * It is based on the file menstioned by Daniel Melo.
         * Reference: http://stackoverflow.com/questions/1921941/close-kill-the-session-when-the-browser-or-tab-is-closed
         */
        var validNavigation = false;
        function isValidEmailAddress(emailAddress) {
        	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
        	return pattern.test(emailAddress);
        }
        
        function endSession() {
          // Browser or broswer tab is closed
          // Do sth here ...
          
          var email=prompt("Enter you email address");
          
          if(isValidEmailAddress(email)){
            //ajax call
            url = '/ecommerce/cart/fetch-email?emailid='+email;
            alert(url);
            $.ajax({
              url: url,
              type: 'GET',
              async:false,
              disableCaching: true,
              success: function(data) {
                return true;
              },
              error: function(){
                alert('An error occurred, please check before continue...');
              }
            });  
             
          
          } else {
            alert("Incorrect email");
        	 
            return false; 
          }
          
        }
        
        function wireUpEvents() {
          /*
          * For a list of events that triggers onbeforeunload on IE
          * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
          */
          window.onbeforeunload = function(e) {
        	  
            if (!validNavigation) {
              endSession();
            }
            var t = Date.now() + 300;
            while(Date.now() < t) {};
            return 'any string'; 
          }
          
          /*
          var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the user to be able to leave withou confirmation
          var leave_message = 'You sure you want to leave?'
          function goodbye(e) {
            if (!validNavigation) {
              if (dont_confirm_leave!==1) {
            	
                if(!e) e = window.event;
                //e.cancelBubble is supported by IE - this will kill the bubbling process.
                e.cancelBubble = true;
                e.returnValue = leave_message;
                
                //e.stopPropagation works in Firefox.
                if (e.stopPropagation) {
                  e.stopPropagation();
                  e.preventDefault();
                  
                }
                
                //return works for Chrome and Safari
                return leave_message;
              }
            }
          }
          window.onbeforeunload=goodbye;*/
        
          
          // Attach the event keypress to exclude the F5 refresh
          $('document').bind('keypress', function(e) {
            if (e.keyCode == 116){
              validNavigation = true;
            }
          });
          
          // Attach the event click for all links in the page
          $("a").bind("click", function() {
            validNavigation = false;
          });
          
          $("#link-next-page").bind("click", function() {
            validNavigation = true;
          });
        
          // Attach the event submit for all forms in the page
          $("form").bind("submit", function() {
            validNavigation = true;
          });
        
          // Attach the event click for all inputs in the page
          $("input[type=submit]").bind("click", function() {
            validNavigation = true;
          });
          
        }
        
        // Wire up the events as soon as the DOM tree is ready
        $(document).ready(function() {
          wireUpEvents();
        });
        

        Like

  8. Hi,
    This post really helped me a lot. Thanks.

    Similar to 116 keycode for F5, is there keycode for the Next and previous buttons in iphone’s virtual keypad

    Like

  9. Hi,

    thanks for the code works well. I had to add one thing to handle navigation triggered by ajax requests. You don’t want to set validNavigation on all clicks on input elements as you might have a few of them which just cause a change in the page but not a navigation away from it. And if every click on a ‘ajax’ button or link sets validNavigation to true you wouldn’t be able to catch the back button anymore.

    So what I did for ajax pages is to have validNavigation set to true on the start of an ajaxRequest (in the function ajaxReqStarted()) and back to false at the end (in the function ajaxReqFinished().

    E.g. if you use RichFaces you can simply use the queue for a page (e.g. a global queue).

    <a:queue
      name="org.richfaces.queue.global"
      requestDelay="500"
      onsubmit="pageSubmitted();"
      oncomplete="ajaxReqFinished();"
    >
    

    *fixed the syntax highlight by ykyuen

    Regards
    Immo

    Like

    1. Mmh the code got deleted. Here it is again without the brackets

      <a:queue
        name="org.richfaces.queue.global"
        requestDelay="500"
        onsubmit="pageSubmitted();"
        oncomplete="ajaxReqFinished();"
      >
      

      *fixed the syntax highlight by ykyuen

      Like

  10. Bravo!. Great great geat solution. I was trying to implement this since 2 weeks, but everytime small problem killed my work. Now one more thing I need is to pop up on tab change. Can you help me plz. and thanx for your great work.

    Like

    1. i guess u want to exclude the checking when user clicks the tab. Assume the tab is a <a> element, you can exclude it by sth like

      $("#tab-id").bind("click", function() {
        validNavigation = true;
      });
      

      where tab-id is the id of the <a> element. i.e.

      <a href="#" id="tab-id">tab title</a>

      Like

  11. Hi ykyuen,
    This script is working great but i want to display alert only when i choose to close the browser tab or browser. Please help…

    Like

    1. Unfortunately the window.onbeforeunload in Chrome needs a returned string and seems that it must display a 2 options alert box (Stay or Leave).

      Like

  12. Hi! Thanks for this script. It really helped me a lot. Btw, is their a way that we could detect if the user clicks on the browser back, forward and reload button?

    Like

      1. Thank you for your comment!

        Unfortunately I got a problem.

        It doesn’t work in Samsung GalaxyTab and GalaxyS.

        In this case, how can i solve this problem?

        Like

      2. i found 2 posts about the window.onbeforeunload in iOS safari.

        Please note that there is no a generic way to handle it for all OSs and browsers. If you really need to make it work for all of them, probably you need to spend a lot of effort to handle difference scenarios.

        Like

  13. Hi,
    Great Solution!!! It works for me almost in all case except having a very small issue:

    I have used this code on my ASP.Net Master Page and its working for all types of navigation and click events but when i open a new window from any hyperlink it doesn’t work.

    Here is what I am trying to do:

    MasterPage.master code:
    Your updated piece of code placed in this.

    Content Page Code having above master page.
    /// a onclick=’ShowDocument(“/trial/Docs.aspx”)’

    function ShowDocument(url) {
    …..
    …..
    window.open(url, \”docwindow1\”, \”status=yes,toolbar=no,resizable=yes,menubar=no,scrollbars =yes,top=0,left=0\”);
    }

    So, when i close the new window and tries to close my main window it does not popup the message for confirmation.

    Like

      1. i think u need to reset the validNavigation to false after the new window is opened. maybe add it at the end of ShowDocument.

        function ShowDocument(url) {
          ...
          validNavigation = false;
        }
        

        does it solve the problem?

        Like

      2. This works perfectly.

        function ShowDocument(url) { 
           ...
             var mywindow = window.open(url, \”docwindow1\”, \”menubar=no,scrollbars =yes,top=0,left=0\”);
             mywindow.onunload = function(e) { validNavigation = false;}; 
        }
        

        Like

  14. TT I hava a problerm

    
    	$(window).bind('beforeunload', goodbye);
    	// Attach the event keypress to exclude the F5 refresh
    	$('document').bind('keypress', function(e) {
    		if (e.keyCode == 116) {
    			validNavigation = true;
    			alert("f5");
    		}
    	});
    
    	// Attach the event click for all links in the page
    	$("a").bind("click", function() {
    		validNavigation = true;
    		alert("a");
    	});
    
    	// Attach the event submit for all forms in the page
    	$("form").bind("submit", function() {
    		validNavigation = true;
    		alert("form");
    	});
    
    	// Attach the event click for all inputs in the page
    	$("input[type=submit]").bind("click", function() {
    		validNavigation = true;
    		alert("submit");
    	});
    

    only i can use this -> $(“a”).bind(“click”, function() .
    f5, form, submit cant use TT

    how can i solve?

    Like

  15. i want to update signout time in database when browser or window is closed..but problem is that when i click on back or forward button the signout time update in database even i am currently login..
    so any solution for that..?

    Like

      1. thanks for your reply but i don’t want to change url on clicking of back or forward button. i just only want to update signout time in database. for that i have try onbeforeunload event but that also call for the back and forward button.

        Like

      2. is the update signout time implemented by your own code?

        maybe you could use session to store if the user login status and then you check it before you update the database.

        Like

      3. thanks for your reply..but i don’t want to change url on click of back or forward button..i just only want to update time in database and for that i have try onbeforeunload event but that call on click of back/forward button..so any solution regarding this..?

        Like

      4. yes it’s my own code to update time in database..
        but i want to implement such a thing that “user is log in but if he/she directly close browser or window then signout time update in database”…

        Like

      5. sorry that i couldn’t help. there is no simple way to detect the browser back or forward button.

        i would still suggest your to use session to check user login status.

        Like

      1. If you want to exclude the form submission thru javascript. just set

        validNavigation = true;
        

        inside that submission function.

        I am not very sure what is a meta refresh event. could u paste your code here? Please follow the Syntax Highlight to paste the code.

        Like

  16. Thanks for reply it worked :)…below is code I was referring in my previous comment for refresing the page at a specific interval:

    <meta http-equiv="REFRESH" content="300" /> 
     

    Like

  17. Can i use custom message? rather than – Are you sure you want to leave this page?
    N i want to give link in custom alert box. any idea for this?

    Like

    1. You can customize it by editing this string.

      var leave_message = 'You sure you want to leave?'
      

      But for some browsers, the leaving dialogue is a default msg which cannot be modified.

      Like

  18. Lo utilizo en PHP. Si el usuario abandona la página carga otra donde actualiza una base de datos. Luego de actulizar los datos cierra la página.
    I use whit PHP.
    If user leave the page it load another where it update database, then close itself.

    /**
     * This javascript file checks for the brower/browser tab action.
     * It is based on the file menstioned by Daniel Melo.
     * Reference: http://stackoverflow.com/questions/1921941/close-kill-the-session-when-the-browser-or-tab-is-closed
     */
    var validNavigation = false;
    
    function wireUpEvents() {
      /**
       * For a list of events that triggers onbeforeunload on IE
       * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
       *
       * onbeforeunload for IE and chrome
       * check http://stackoverflow.com/questions/1802930/setting-onbeforeunload-on-body-element-in-chrome-and-ie-using-jquery
       */
      var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the user to be able to leave withou confirmation
      var leave_message = 'Seguro que quiere salir?'
      function goodbye(e) {
        if (!validNavigation) {
          if (dont_confirm_leave!==1) {
            if(!e) e = window.event;
            //e.cancelBubble is supported by IE - this will kill the bubbling process.
            e.cancelBubble = true;
            e.returnValue = leave_message;
            //e.stopPropagation works in Firefox.
            if (e.stopPropagation) {
              e.stopPropagation();
              e.preventDefault();
            }
            //return works for Chrome and Safari
             window.open('DelLogged.php?Id=');
            return leave_message;
          }
        }
      }
      window.onbeforeunload=goodbye;
    
      // Attach the event keypress to exclude the F5 refresh
      $('document').bind('keypress', function(e) {
        if (e.keyCode == 116){
          validNavigation = true;
        }
      });
      // Attach the event click for all links in the page
      $("a").bind("click", function() {
        validNavigation = true;
      });
      // Attach the event submit for all forms in the page
      $("form").bind("submit", function() {
        validNavigation = true;
      });
      // Attach the event click for all inputs in the page
      $("input[type=submit]").bind("click", function() {
        validNavigation = true;
      });
    }
    
    // Wire up the events as soon as the DOM tree is ready
    $(document).ready(function() {
      wireUpEvents();
    });
    

    (DelLogged.php)

    Saliendo…

    Funciona en chrome y firefox.
    It’s works under chrome and firefox
    Gracias
    Thanks

    Like

  19. I wish to display a form in order to update the database only if the user confirms that he wants to close the window. However, I am unable to track the event on confirmation of the close message in spite of implementing all the above possibilities.

    Please help, since I am unable to proceed.

    Like

    1. I think that will be quite complicated. Here is my suggestion.

      When the user close the message, you have to send a ajax request to the server in order to update the database, probably you will need some authentication here other wise it will be spammed.

      Like

  20. This is a really nice solution. This can be used for some kind of one time password scenarios for example i log in with my one time password and if i close browser that one time password must be refreshed and overwritten with a new one. Thank you ;)

    Like

  21. hi ykyuen this is a really nice solution and the best I have seen. Can you give me a suggestion on whether it is possible to track user click “Yes” and call some function (i.e update logout time upon confirmation)?

    Like

    1. you can use the window.onunload. for example, add the following line in the .js.

      window.onunload = function(){ window.open('http://eureka.ykyuen.info'); };
      

      If you click Yes, the window.onunload will be triggered. The above code will open a new window showing this blog.

      Hope this help. =)

      Like

      1. hi thanks for your quick response. I have attached your js file to one of my projects. It is an asp.net project. In the home page it has dynamically loaded menus and a dashboard which consists of grids. When I click menu item or hyperlink within the grid (these are created dynamically) ‘You sure you want to leave’ message is displayed.Can you suggest me how to bind the proper event in js file to avoid this message?

        Like

      2. Hi Samitha,

        how do you load the menu and dashboard dynamically? is it done by js?

        If yes, try loading the check_browser_close.js at the end. i.e.

        <head>
          <script type="text/javascript" src="js/your_js.js"></script>
          <script type="text/javascript" src="js/check_browser_close.js"></script>
        </head>
        

        Does it solve the problem?

        Like

  22. Hi I am not loading the menu from a js. It’s done the code behind. Anyway I moved the ,js reference just after the closing html tag and it seems working fine. I have read at some other place that window.unload event doesn’t fire on IE. Somehow the way you have suggested working fine and satisfies my requirement. Thanks for your prompt reply and keep up the good work :)

    Like

  23. Hello! great script but I have a problem with firefox.
    If i push the refresh button or when i klik on a menulink the function window.onunload = function(){ window.open(‘http://www.google.nl’); }; is always happening.
    It looks like I can’t disable the script for refresh and links.
    You know what I should do?

    Like

    1. Hello again,
      This solved the isseu.
      function ShowDocument(url) {
      var mywindow = window.open(“http://www.google.nl”);
      mywindow.onunload = function(e) { validNavigation = false;};
      }

      Like

      1. There is no simple way to detect the browser refresh button. please refer to this comment.

        For menu link click, i think u need to detect it by js and then set the validNavigation to true.

        Hope this help. =)

        Like

  24. Hello Ykyuen,
    Thanks for your answer helps allot.
    Can I ask you for a fafor I realy do not want my e-mail adress displayed public and also not my website could you please remove it from the public acces?
    I did not see that it would come publicly avalible.
    I found great use for your plugin and i am very glad with your solution thanks.

    Like

      1. Thanks for that,
        I don’t have any time to work on your script for a while but I did do some work on it and thought lets share.
        I found a way to tell people what to do if the use the refresch button or any other browser navigation buttons also I found a way to make the menu links not respond on your scipt and a way to redirect to a sertain page it now only works in IE and Firefox.
        For Opera Safari and Chorme I still got to make it work but as I said I Need to do some other stuff first. But I will post it here for anyone who needs it.
        I dont know How to put code on here so I try but dont know if it go’s oke. Here it comes.
        ———————————————————————————-

        /**
         * This javascript file checks for the brower/browser tab action.
         * It is based on the file menstioned by Daniel Melo.
         * Reference: http://stackoverflow.com/questions/1921941/close-kill-the-session-when-the-browser-or-tab-is-closed
         */
        var validNavigation = false;
        
        function wireUpEvents() {
          /**
           * For a list of events that triggers onbeforeunload on IE
           * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
           *
           * onbeforeunload for IE and chrome
           * check http://stackoverflow.com/questions/1802930/setting-onbeforeunload-on-body-element-in-chrome-and-ie-using-jquery
           */
           
            
          var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the user to be able to leave withou confirmation
          var leave_message = 'Please click: (stay on this page)\nand close page again\nand follow the instructions'
          var leave_message2 = 'Chrome  Please click: (stay on this page)\nand close page again\nand follow the instructions'
          
          function goodbye2(e) {
            if (!validNavigation) {
              if (dont_confirm_leave!==1) {
                if(!e) e = window.event;
        		return leave_message2;
        	
              }
            }
          }
          
          
          
          
          function goodbye(e) {
            if (!validNavigation) {
              if (dont_confirm_leave!==1) {
                if(!e) e = window.event;
                //e.cancelBubble is supported by IE - this will kill the bubbling process.
                e.cancelBubble = true;
                e.returnValue = false;
                //e.stopPropagation works in Firefox.
                if (e.stopPropagation) {
                  e.stopPropagation();
                  e.preventDefault();
        		  e.returnValue = false;
                }
                //return works for Chrome and Safari
        		
        
                return leave_message;
              }
            }
          }
        var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') &gt; -1;
        if (is_chrome) {
        /*alert('hallo1');*/
        
        window.onbeforeunload =goodbye2
        
         } else {
          window.onbeforeunload= (readCookie('welkom9278') !== 'gegroet9278')
        {
        window.onbeforeunload = function(){  var x=window.confirm("Oops.. het lijkt erop dat er een pop-up blocker aan staat.\n\nAls je op het (kruisje) X de Close-Knop hebt gedrukt.\nKies dan OK\nKies (stay on this page)!\nKies dan in de pop-up blokker (always allow popups for this site)\nKies nogmaals OK\n\n De pop-up pagina sluit vanzelf binnen 5 seconden\n\nVoor de pagina die dan nog niet is afgesloten.\nSluit dan de pagina nogmaals. en kies dan Annuleren\n\nAls u op een andere browser navigation knop hebt gedrukt.\nKies dan direct; Annuleren. ")
        if (x) {
        	var browserName=navigator.appName;
        	if (browserName=="Microsoft Internet Explorer")
         {
          window.open("http://www.yourwebpage.nl/session_end.html");
        window.onbeforeunload=goodbye
        window.onbeforeunload= x
        window.event= null; 
        return false;
         }
         else
          {
            window.open("http://www.yourwebpage.nl/session_end.html");
        window.event= null; 
        return false;
           }
        }
        else {
        
        }}
        
        }
        createCookie('welkom9268','gegroet9268',0)
        setInterval(function eraseCookie(welkom9268) {
        createCookie('welkom9268',"",-1);
        },200);
        
         }
         
        
        	
        createCookie('rescookie','restcookie',0)
        function createCookie(name,value,days) {
        if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
        }
        
        function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i  -1;
        if (is_fire) {
        window.onbeforeunload = function(){  var x=window.confirm("Oops.. het lijkt erop dat er een pop-up blocker aan staat.\n\nAls je op het (kruisje) X de Close-Knop hebt gedrukt.\nKies dan OK\nKies (stay on this page)!\nKies dan in de pop-up blokker (always allow popups for this site)\nKies nogmaals OK\n\n De pop-up pagina sluit vanzelf binnen 5 seconden\n\nVoor de pagina die dan nog niet is afgesloten.\nSluit dan de pagina nogmaals. en kies dan Annuleren\n\nAls u op een andere browser navigation knop hebt gedrukt.\nKies dan direct; Annuleren. ")
        if (x) {
        window.open("http://www.yourwebpage.nl/session_end.html");
        window.event= null; 
        return false;
        }
        else {
        
        }}
        
        }}
        createCookie('welkom9278','gegroet9278',0)
        setInterval(function eraseCookie(welkom9278) {
        createCookie('welkom9278',"",-1);
        },200);
        
        
        
           //Attach the event keypress to exclude the F5 refresh
         
          
          $('a').click(function(){
            window.onunload = null;
        	window.onbeforeunload= null;
        });
          
          
          document.onkeydown = function disableKeys() {
          if( typeof event != 'undefined' ) {
            if(event.keyCode == 116) {
              validNavigation = true;
              event.keyCode = 0;
        	  
              return false; //return false if u want to disable refresh
            }
          }
        };
        
          
        
          // Attach the event click for all links in the page
          $("a").bind("click", function() {
            validNavigation = true;
          });
        
          // Attach the event submit for all forms in the page
          $("form").bind("submit", function() {
            validNavigation = true;
          });
        
          // Attach the event click for all inputs in the page
          $("input[type=submit]").bind("click", function() {
            validNavigation = true;
          });
        
        }
        
        // Wire up the events as soon as the DOM tree is ready
        $(document).ready(function() {
          wireUpEvents();
        });
        

        Like

  25. Hello Ykyuen,
    Dreamweaver does not see the missing bracket on line 110 so the have to look into this when the use this code any way it seems also to work without that bracket and i am sorry but i am not able to take a futer look at this right now. But i will post it again and use the syntax highlighting you told my about. If you like you can remove the code without the syntax higlighting. Thanks again for your great code. here it comes
    ———————————————————————————————–

    
    
    /**
     * This javascript file checks for the brower/browser tab action.
     * It is based on the file menstioned by Daniel Melo.
     * Reference: http://stackoverflow.com/questions/1921941/close-kill-the-session-when-the-browser-or-tab-is-closed
     */
    var validNavigation = false;
    
    function wireUpEvents() {
      /**
       * For a list of events that triggers onbeforeunload on IE
       * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
       *
       * onbeforeunload for IE and chrome
       * check http://stackoverflow.com/questions/1802930/setting-onbeforeunload-on-body-element-in-chrome-and-ie-using-jquery
       */
       
        
      var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the user to be able to leave withou confirmation
      var leave_message = 'Please click: (stay on this page)\nand close page again\nand follow the instructions'
      var leave_message2 = 'Chrome  Please click: (stay on this page)\nand close page again\nand follow the instructions'
      
      function goodbye2(e) {
        if (!validNavigation) {
          if (dont_confirm_leave!==1) {
            if(!e) e = window.event;
    		return leave_message2;
    	      }
        }
      }
      
      
      
      
      function goodbye(e) {
        if (!validNavigation) {
          if (dont_confirm_leave!==1) {
            if(!e) e = window.event;
            //e.cancelBubble is supported by IE - this will kill the bubbling process.
            e.cancelBubble = true;
            e.returnValue = false;
            //e.stopPropagation works in Firefox.
            if (e.stopPropagation) {
              e.stopPropagation();
              e.preventDefault();
    		  e.returnValue = false;
            }
            //return works for Chrome and Safari
    		
    
            return leave_message;
          }
        }
      }
    var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    if (is_chrome) {
    /*alert('hallo1');*/
    
    window.onbeforeunload =goodbye2
    
     } else {
      window.onbeforeunload= (readCookie(‘welkom9268′) !== ‘gegroet9268′)
    {
    window.onbeforeunload = function(){  var x=window.confirm("Oops.. it seems a pop-up blokker is on.\n\nIf you pushed the (cross) X de Close-button.\nChoose: OK.\nChoose (stay on this page)!\nThan choose in the pop-up blokker (always allow popups for this site)\nChoose OK again\n\nThe pop-up page closes automaticly in 5 seconds\n\nChoose leave this page for the page that you stayed on.\n\nIf you pushed a other browser navigation button.\nYou need to choose Cancel this will execute the browser navigation button function. ")
    if (x) {
    	var browserName=navigator.appName;
    	if (browserName=="Microsoft Internet Explorer")
     {
      window.open("http://www.yourwebpage.nl/session_end.html");
    window.onbeforeunload=goodbye
    window.onbeforeunload= x
    window.event= null; 
    return false;
     }
     else
      {
        window.open("http://www.yourwebpage.nl/session_end.html");
    window.event= null; 
    return false;
       }
    }
    else {
    
    }}
    
    }
    createCookie('welkom9268','gegroet9268',0)
    setInterval(function eraseCookie(welkom9268) {
    createCookie('welkom9268',"",-1);
    },200);
    
     }
     
    
    	
    createCookie('rescookie','restcookie',0)
    function createCookie(name,value,days) {
    if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
    }
    
    function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
    }
    if (readCookie('welkom9278') !== 'gegroet9278')
    {
    	var is_fire = navigator.userAgent.toLowerCase().indexOf('Firefox') > -1;
    if (is_fire) {
    window.onbeforeunload = function(){  var x=window.confirm("Oops.. it seems a pop-up blokker is on.\n\nIf you pushed the (cross) X de Close-button.\nChoose: OK.\nChoose (stay on this page)!\nThan choose in the pop-up blokker (always allow popups for this site)\nChoose OK again\n\nThe pop-up page closes automaticly in 5 seconds\n\nChoose leave this page for the page that you stayed on.\n\nIf you pushed a other browser navigation button.\nYou need to choose Cancel this will execute the browser navigation button function. ")
    if (x) {
    window.open("http://www.yourwebpage.nl/session_end.html");
    window.event= null; 
    return false;
    }
    else {
    
    }}
    
    }}
    createCookie('welkom9278','gegroet9278',0)
    setInterval(function eraseCookie(welkom9278) {
    createCookie('welkom9278',"",-1);
    },200);
    
    
    
       //Attach the event keypress to exclude the F5 refresh
     
      
      $('a').click(function(){
        window.onunload = null;
    	window.onbeforeunload= null;
    });
      
      
      document.onkeydown = function disableKeys() {
      if( typeof event != 'undefined' ) {
        if(event.keyCode == 116) {
          validNavigation = true;
          event.keyCode = 0;
    	  
          return false; //return false if u want to disable refresh
        }
      }
    };
    
      
    
      // Attach the event click for all links in the page
      $("a").bind("click", function() {
        validNavigation = true;
      });
    
      // Attach the event submit for all forms in the page
      $("form").bind("submit", function() {
        validNavigation = true;
      });
    
      // Attach the event click for all inputs in the page
      $("input[type=submit]").bind("click", function() {
        validNavigation = true;
      });
    
    }
    
    // Wire up the events as soon as the DOM tree is ready
    $(document).ready(function() {
      wireUpEvents();
    });
    
    
    
    

    Like

  26. Hello Ykyuen,
    I had a litle bit of time and could do some more work on your code. Can you please remove my tree previous posts I mean the ones with The code.I Have cleared some unnecessary junk lines. I also found a way to make it work in Google Chrome and safari. So now it is working in Google Chrome, IE9, Safari en Firefox. Next time I will look at Opera. Here is the new code: Works like a charme
    ————————————————————————

    var validNavigation = false;
    function wireUpEvents() {
    
    var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    
    
    var is_safari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
    
    if (is_chrome) {
    var test = 1;
    window.onbeforeunload = function(){
        setTimeout(function(){
            test = 2;
    		setInterval(function(){
        if (test = 2) {
            var x = confirm("\nIf you pushed the (cross) X the Close-button.\nChoose OK\n\nIf you pushed a other browser navigation button\nChoose: Cancel.")
     if ( x == true)
       {
    	 window.location = "/session_end.html";
    	 window.onunload = document.location = ("http://www.terraverdedesign.nl/session_end.html");
       }
     else
       {
       }
       }
        },0);
        },50);
    	return "If you pushed the (cross) X the Close-button..\nChoose (Stay on this page)\nChoose (OK)\nChoose (Leave this page)\nChoose (OK)\n\nAIf you pushed a other browser navigation button\nChoose: (Leave this page)";
     }
     
    }
    createCookie('rescookie','restcookie',0)
    function createCookie(name,value,days) {
    if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
    }
    
    function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
    }
    if (readCookie('welkom9278') !== 'gegroet9278')
    {
    	var is_fire = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
    if (is_fire) {
    	/*alert('oops..seems like a pop-up blocker is enabled. Please disable');*/	
    window.onbeforeunload = function(){  var x=window.confirm("Oops.. it seems a pop-up blokker is on.\n\nIf you pushed the (cross) X de Close-button.\nChoose: OK.\nChoose (stay on this page)!\nThan choose in the pop-up blokker (always allow popups for this site)\nChoose OK again\n\nThe pop-up page closes automaticly in 5 seconds\n\nChoose leave this page for the page that you stayed on.\n\nIf you pushed a other browser navigation button.\nYou need to choose Cancel this will execute the browser navigation button function. ")
    if (x) {
    window.open("http://www.terraverdedesign.nl/session_end.html");
    return false;
    }
    else {
    
    }
    }
    
    }
    
    createCookie('welkom9278','gegroet9278',0)
    setInterval(function eraseCookie(welkom9278) {
    createCookie('welkom9278',"",-1);
    },200);
    }
    
    if (readCookie('welkom9268') !== 'gegroet9268')
    {
    	var is_msie = navigator.userAgent.toLowerCase().indexOf('msie') > -1;
    	if (is_msie) {
    	/*alert('oops..seems like a pop-up blocker is enabled. Please disable');*/
    window.onbeforeunload = function(){  var x=window.confirm("Oops.. it seems a pop-up blokker is on.\n\nIf you pushed the (cross) X de Close-button.\nChoose: OK.\nChoose (stay on this page)!\nThan choose in the pop-up blokker (always allow popups for this site)\nChoose OK again\n\nThe pop-up page closes automaticly in 5 seconds\n\nChoose leave this page for the page that you stayed on.\n\nIf you pushed a other browser navigation button.\nYou need to choose Cancel this will execute the browser navigation button function. ")
    if (x) {
    window.open("http://www.terraverdedesign.nl/session_end.html");
    window.onbeforeunload= x
    return false;
     }
     else
      {
     return false;
       }
    }
    
    } 
    
    
    createCookie('welkom9268','gegroet9268',0)
    setInterval(function eraseCookie(welkom9268) {
    createCookie('welkom9268',"",-1);
    },200);
    }
    
    
    
    if (is_safari) {
    
    var tesx = 3;
    
    window.onbeforeunload = function(){
        setTimeout(function(){
            tesx = 4;
    		setInterval(function(){
        if (tesx = 4) {
           var x = confirm("\nIf you pushed the (cross) X the Close-button.\nChoose OK\n\nIf you pushed a other browser navigation button\nChoose: Cancel.")
     if ( x == true)
       {
    	 window.location = "/session_end.html";
    	 window.onunload = document.location = ("http://www.terraverdedesign.nl/session_end.html");
       }
     else
       {
       }
       }
        },0);
        },50);
    	return "If you pushed the (cross) X the Close-button..\nChoose (Stay on this page)\nChoose (OK)\nChoose (Leave this page)\nChoose (OK)\n\nAIf you pushed a other browser navigation button\nChoose: (Leave this page)";
     }}
    	
    
    
    
    
        $("a").bind("click", function() {
        validNavigation = true;
    	window.onbeforeunload= null;
    	   window.onunload= null;
    
      });
     
     	 $('a').click(function(){
    	  validNavigation = true;
    	  window.onbeforeunload= null;
    	   window.onunload= null;
    
    });
     
     
    $(window).bind('click', function(event) {
           if(event.target.href) $(window).unbind('beforeunload');
    	   validNavigation = true;
    	   window.onbeforeunload = null;
    	   window.onunload = null;
    
    });
      
      
      document.onkeydown = function disableKeys() {
      if( typeof event != 'undefined' ) {
        if(event.keyCode == 116) {
          validNavigation = true;
          event.keyCode = 0;
    	  
          return false; 
        }
      }
    };
    
       $("form").bind("submit", function() {
        validNavigation = true;
      });
    
        $("input[type=submit]").bind("click", function() {
        validNavigation = true;
      });
    
    }
    
    $(document).ready(function() {
      wireUpEvents();
    });
    

    Like

      1. Hey D,
        I will spear you the summerize part and post once the code is finalized. Thanks this blog is realy helpfull.

        Like

  27. Hi Ykyuen, very nice script, congratulations!
    But I have 2 problems…
    1 – The script is not working in Opera.
    2 – I wish to call a function “logout” when the user confirms the closing of the window.
    Can you help me?

    Like

    1. Hi AGoes,

      1 – The script is not working in Opera.
      Currently Jeroen is working on a better solution and he is still working for Opera. I am sorry that i am not going to dig deeper to the solution since looking for 100% compatibility on this requirement is a bit too far for me. especially when different browsers have different responses on the input.

      2 – I wish to call a function “logout” when the user confirms the closing of the window.
      There is no way to do that. we couldn’t know whether the user pressed stay or leave. you can refer to this comment.

      Like

      1. Hello AGoes,
        You can call the function I believe if you put it between the if (X) or if ( x == true) parts where the url’s are. Opera may be a problem it does not know a onbeforeunload event it does how ever know the onunlaod event so I will take a look at that when i have time.
        Use the code just above this text than you can call a function or url.

        Like

      2. Hello there, I did take a look at opera but it does not like to detect the close tab event. So I made up a different way to detect a close tab. just ask. This code opens a seccond window when you close the second window a allert box ask you if you want to end the session. then you get redirected to the end session page. here is this code.

        //-----------------------------------------------------------------------------------------
        
        var is_opera = navigator.userAgent.toLowerCase().indexOf('opera') > -1;	
        
        if (is_opera) {
        	awt = window.setTimeout(function eraseCookie(welkom9968) 
        	{createCookie('welkom9968','gegroet9968',0)
        	},1000);	
        	
        // Add Event function
        
        
        xwin = new Object();
          if (readCookie('welkom9988') !== 'gegroet9988') 
        {		
        var xwin = window.open('/bloemenspeciaalzaak-terraverdedesign.html', 'SessionStart')
        , int = window.setTimeout(function () {
        if (xwin.closed !== true) { 
        	alert('\nPlease Klik on(OK) and then on (Allow Pop-up) Below in the right corner of your display.\n\nOpera needs a extra tab to see if you leave this site.\n\nClose both tabs when you leave this website, bedankt.\n\nThanks for your visit.');
                }
            },50);
        }
           createCookie('welkom9988','gegroet9988',0)
        
        kk = window.setInterval(function () {
        if (window.name !== 'SessionStart')
        {
        	window.location.reload();
        	if (typeof xwin.closed == 'undefined')	{
        	alert('\nPlease klik (OK)/n/nThe the session will be ending.')
        	
        	var xwun = window.location.href = '/session_end.html';
        	}
        }},2000);
           
            
        	if ( $("input[type=submit]").bind("click", function(event) {
            if(event.target.href) {
                	//alert ('link2');
        
        	//To not popup the warning message
        	} else {
                	// alert ('somthing else like a button2');
        			int = window.setTimeout(function eraseCookie(welkom9968) {
        			createCookie('welkom9968',"",-1);
        			},0);
        
        	}}));
        	  
        	 
        	 if (   $(window).bind('click', function(event) {
              	   if(event.target.href){
                	//alert ('link'); //To not popup the warning message
        			int = window.setTimeout(function eraseCookie(welkom9968) {
        			createCookie('welkom9968',"",-1);
        			},0);	//To not popup the warning message
        		} else {
                    
        	}}));
        	  
        }
        //------------------------------------------------------------------------------------------------------------------------------------------------------
        
        // /session_end.html
        //------------------------------------------------------------------------------------------------------------------------------------------------------
        
        //Your cookie session is ending.
        //Page closes automaticly.
        //
        //<?php
        //if(isset($_SERVER['HTTP_COOKIE'])){
        //
        //$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
        //    foreach($cookies as $cookie){
        //        $parts = explode('=', $cookie);
        //        $name = trim($parts[0]);
        //        setcookie($name,'', time()-1000);
        //        setcookie($name,'', time()-1000,'/');
        //    }
        //}
        //session_unset();    
        //session_destroy();
        //?>
        //
        //<form name="redirect" class="serb">
        //<p class="clountdown">Deze webpagina wordt gesloten in:</p>
        //<form>
        //<input name="redirect2" type="text" class="countdown">
        //<p class="clountdown">Seconden</p> 
        //</form>
        //
        //
        //<script language="javascript" type="text/javascript">
        //var countdownfrom=3
        //var currentsecond=document.redirect.redirect2.value=countdownfrom+1
        //function countredirect(){
        //if (currentsecond!=1){
        //currentsecond-=1
        //document.redirect.redirect2.value=currentsecond
        //}
        //else{
        //var objWindow = window.open(location.href, "_self"); objWindow.close();
        //window.name = 'SessionEnd'
        //window.open('/session_end.html','SessionEnd','');
        //SessionEnd.close();
        //self.close();
        //window.open('','_self','');
        //window.close();
        //win.close();
        //return
        //}
        //setTimeout("countredirect()",1000)
        //}
        //
        //countredirect()
        //<//script> 
        //
        

        Like

  28. Thanks for the script and it is working for IE, firefox and chrome. I have lot of pages in my web application. Can I have any option to define close browser and close tab in one place for all the pages?

    Like

  29. Hello ykyuen

    I’m Momin Ansari from Mumbai,India

    I have a Problem regarding Browser Closing…….

    See I have a Master Page and inside that have so many Pages which contains many user controls….Now I want a piece of code eg yours if I put on the Master Page and while Navigation it won’t display the Message Box na….Suppose If I Navigate “A.aspx” and close the Browser then it will display the Message…and if I Navigate to “B.aspx” then it won’t Display the Message…I hope so that you will understand my problem……..Waiting for your reply…..

    Like

    1. Hello,

      If the browser crashes (or) killed explicitly by the user, I would need to have control for this to send to the server.
      Is there a way of doing this?

      Thanks
      Praveen

      Like

      1. Hi Praveen,

        I tried to close the page by terminating the browser in task manager and the alert dialogue was prompted. so i think you can still make use of it and send a request to the server thru ajax.

        Like

    2. As u read in the code, it tries to disable the message box for specific action by setting validNavigation to true. e.x.

      // Attach the event click for all links in the page
      $("a").bind("click", function() {
        validNavigation = true;
      });
      

       

      So i suggest you could set a specific class to the elements in the .aspx.
      For example, if you want to disable the message box for all hyperlinks in B.aspx. then you can add a class to it, say

      <a href="http://eureka.ykyuen.info" class="no-message-box">Eureka!</a>
      

       

      Then in the .js, add the following piece of code.

      // Attach the event click for all links with class "no-message-box"
      $(".no-message-box").bind("click", function() {
        validNavigation = true;
      });
      

       

      So any hyperlink with class “no-message-box” will not trigger the message box.

      Like

      1. Sir what about Menu Controls like I have a Parent Menu and inside that I have many Child menus so when I navigate to menus it sholudn’t display the Message and when i close the Page then it should fire a Page methods/AjAX Request…..plz let me know….Waiting for your reply……

        Like

      2. But Sir,,,

        The Menu Items are coming from the SiteMap….i.e in Web.SiteMap we had specified the URL like

        so how to Manage……Plz Sir Help me out I’m stuck in this for the last 2-3 days

        Like

      3. If you couldn’t add the class to the menu item. maybe you could use jQuery to add the class and then bind the click function to set the validNavigation to true.

        If still doesn’t work, then I think you need to use a proper jQuery selection to select the menu item.

        Like

  30. and one more thing I’m using the following code
    window.onbeforeunload = function() { myUnloadEvent(); }
    function myUnloadEvent() {

    PageMethods.TestMethod();
    }

    where TestMethod() is the WebService called when the Browser is closed….N
    Now my problem is When I navigate to TreeViewNode and click on some Link it doesn’t get Fired…….Plz Sir guide me in this

    Like

  31. window.onbeforeunload = function (evt) { 
      var message = 'Are you sure you want to leave?'; 
      if (typeof evt == 'undefined') { 
        evt = window.event; 
      } 
      if (evt) { 
        evt.returnValue = message; 
      } 
      return message; 
    } 
    

    Like

  32. hi,i want to open popup box with one form at same window when i close tab,and in that popup user able to fill a form.pls help me..Thanks in advance.

    Like

  33. thanks for your work but it is still not working in Opera
    I tried the code of Jeroen but it’s not working

    I hope you can help me

    Like

    1. Hello, Did you try this code here? Jeroen on December 1, 2012 at 03:50 said: Opera doesnot support windowunload event or window close so this is the only way I could think of. here is the code:

      var is_opera = navigator.userAgent.toLowerCase().indexOf('opera') > -1;	
      
      if (is_opera) {
      	awt = window.setTimeout(function eraseCookie(welkom9968) 
      	{createCookie('welkom9968','gegroet9968',0)
      	},1000);	
      	
      // Add Event function
      
      
      xwin = new Object();
        if (readCookie('welkom9988') !== 'gegroet9988') 
      {		
      var xwin = window.open('/bloemenspeciaalzaak-terraverdedesign.html', 'SessionStart') // url the start page off your sie:
      , int = window.setTimeout(function () {
      if (xwin.closed !== true) { 
      	alert('\nPlease Klik on(OK) and then on (Allow Pop-up) Below in the right corner of your display.\n\nOpera needs a extra tab to see if you leave this site.\n\nClose both tabs when you leave this website, bedankt.\n\nThanks for your visit.');
              }
          },50);
      }
         createCookie('welkom9988','gegroet9988',0)
      
      kk = window.setInterval(function () {
      if (window.name !== 'SessionStart')
      {
      	window.location.reload();
      	if (typeof xwin.closed == 'undefined')	{
      	alert('\nPlease klik (OK)/n/nThe the session will be ending.')
      	
      	var xwun = window.location.href = '/session_end.html'; // URL you end your session add. or some function
      	}
      }},2000);
         
          
      	if ( $("input[type=submit]").bind("click", function(event) {
          if(event.target.href) {
              	//alert ('link2');
      
      	//To not popup the warning message
      	} else {
              	// alert ('somthing else like a button2');
      			int = window.setTimeout(function eraseCookie(welkom9968) {
      			createCookie('welkom9968',"",-1);
      			},0);
      
      	}}));
      	  
      	 
      	 if (   $(window).bind('click', function(event) {
            	   if(event.target.href){
              	//alert ('link'); //To not popup the warning message
      			int = window.setTimeout(function eraseCookie(welkom9968) {
      			createCookie('welkom9968',"",-1);
      			},0);	//To not popup the warning message
      		} else {
                  
      	}}));
      	  
      }
       
      

      Like

  34. Hi, I tried to use this script to detect if browser close button is clicked.
    In my application there are submit buttons, links and other controls.
    As I see, sometimes onbeforeunload function runs before controlling “validNavigation”.
    Do you have any idea how to resolve it?

    Like

    1. Thit u use this?

      function okEvent(){
           validNavigation = true;
        }
      
      $(':button').click(okEvent);
      $("form").bind("submit", okEvent );
      
      
      
      
          $("a").bind("click", function() {
          validNavigation = true;
      	window.onbeforeunload= null;
      	   window.onunload= null;
      	   
        });
       
       	 $('a').click(function(){
      	  validNavigation = true;
      	  window.onbeforeunload= null;
      	   window.onunload= null;
      	   
      
      });
       
       
      $(window).bind('click', function(event) {
             if(event.target.href) $(window).unbind('beforeunload');
      	   validNavigation = true;
      	   window.onbeforeunload = null;
      	   window.onunload = null;
      	   
      });
      
      
      
        
      
        
        document.onkeydown = function disableKeys() {
        if( typeof event != 'undefined' ) {
          if(event.keyCode == 116) {
            validNavigation = true;
            event.keyCode = 0;
      	  
            //return false; 
          }
        }
      };
      
         $("form").bind("submit", function() {
          validNavigation = true;
        });
      
          $("input[type=submit]").bind("click", function() {
          validNavigation = true;
        });
      

      Like

      1. I will open a new browser if user closes the browser. I use almost same code as yours to handle browser close event. But sometimes, it opens a new window even if I click a button or link in my application. I debug in firefox and see that, it doesn’t always assing true to validNavigation parameter.
        I hope you can help me.

        var validNavigation = false;
        
        function wireUpEvents() {
        
            //set dont_confirm_leave to 1 when you want the user to be able to leave without confirmation
            var dont_confirm_leave = 0;
        
            function closeInChrome(e) {
                if (!validNavigation) {
                    if (dont_confirm_leave != 1) {
                        window.open('http://www.google.com', 'google','width=800,height=600,status=0,toolbar=0');
                        return null;
                    }
                }
            }
        
            var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') &gt; -1;
        
            if (is_chrome) {
                window.onbeforeunload = closeInChrome
            }
            else{
                window.onbeforeunload =  function () {
        
                    if (!validNavigation) {
                        validNavigation = false;
        
                        window.open('http://www.google.com', 'google','width=800,height=600,status=0,toolbar=0');
                    }
                }
            }
        
            $('a').click(function () {
                window.onunload = null;
                window.onbeforeunload = null;
            });
        
            document.onkeydown = function disableKeys() {
                if (typeof event != 'undefined') {
                    if ( event.keyCode == 112 || event.keyCode == 116) {
                        validNavigation = true;
                        event.keyCode = 0;
        
                        return false; //return false if u want to disable refresh
                    }
                }
            };
              /*
             // Attach the event keypress to exclude the F5 refresh
            $('html').bind('keypress', function (e) {
                if (e.keyCode == 116) {
                    validNavigation = true;
                }
            });
            */
            // Attach the event click for all links in the page
            $("a").bind("click", function () {
                validNavigation = true;
            });
        
            // Attach the event submit for all forms in the page
            $("form").bind("submit", function () {
                validNavigation = true;
            });
        
            // Attach the event click for all inputs in the page
            $("input[type=submit]").bind("click", function () {
                validNavigation = true;
            });
        
            $("input[type=button]").bind("click", function () {
                validNavigation = true;
            });
        
            $(".active-menu").bind("click", function() {
                validNavigation = true;
            });
        }
        
        // Wire up the events as soon as the DOM tree is ready
        $(document).ready(function () {
            wireUpEvents();
        });
        

        Like

    1. (JEROEN says) Hello I use this code:

      
      var validNavigation = false;
      function wireUpEvents() {
      
      var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
      var is_opera = navigator.userAgent.toLowerCase().indexOf('opera') > -1; 
      var is_safari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
      
      if (is_chrome) {
      var test = 1;
      window.onbeforeunload = function(){
          setTimeout(function(){
              test = 2;
      		setInterval(function(){
          if (test = 2) {
              var x = confirm("\nAls je op het (kruisje) X de Close-Knop hebt gedrukt.\nKies dan OK\n\nAls u op een andere browser navigation knop hebt gedrukt.\nKies dan direct: annuleren.")
       if ( x == true)
         {
      	 window.location = "/session_end.html";
      	 window.onunload = document.location = ("http://www.terraverdedesign.nl/session_end.html");
         }
       else
         {
         }
         }
          },0);
          },50);
      	return "Als je op het (kruisje) X de Close-Knop hebt gedrukt.\nKies dan (Op deze pagina blijven)\nKies dan (OK)\nKies dan (Deze pagina verlaten)\nKies dan (OK)\n\nAls u op een andere browser navigation knop hebt gedrukt.\nKies dan direct: (Deze pagina verlaten)";
       }
       
      }
      createCookie('rescookie','restcookie',0)
      function createCookie(name,value,days) {
      if (days) {
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      var expires = "; expires="+date.toGMTString();
      }
      else var expires = "";
      document.cookie = name+"="+value+expires+"; path=/";
      }
      
      function readCookie(name) {
      var nameEQ = name + "=";
      var ca = document.cookie.split(';');
      for(var i=0;i < ca.length;i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
      }
      return null;
      }
      if (readCookie('welkom9278') !== 'gegroet9278')
      {
      	var is_fire = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
      if (is_fire) {
      		
      window.onbeforeunload = function(){  var x=window.confirm("Oeps.. het lijkt erop dat er een pop-up blocker aan staat.\n\nAls je op het (kruisje) X de Close-Knop hebt gedrukt.\nKies dan OK\nKies (stay on this page)!\nKies dan in de pop-up blokker (always allow popups for this site)\nKies nogmaals OK\n\n De pop-up pagina sluit vanzelf binnen 5 seconden\n\nVoor de pagina die dan nog niet is afgesloten.\nSluit dan de pagina nogmaals. en kies dan Annuleren\n\nAls u op een andere browser navigation knop hebt gedrukt.\nKies dan direct; Annuleren. ")
      if (x) {
      window.open("http://www.terraverdedesign.nl/session_end.html");
      return false;
      }
      else {
      
      }
      }
      
      }
      
      createCookie('welkom9278','gegroet9278',0)
      setInterval(function eraseCookie(welkom9278) {
      createCookie('welkom9278',"",-1);
      },200);
      }
      
      if (readCookie('welkom9268') !== 'gegroet9268')
      {
      	var is_msie = navigator.userAgent.toLowerCase().indexOf('msie') > -1;
      	if (is_msie) {
      	
      window.onbeforeunload = function(){  var x=window.confirm("Oeps.. het lijkt erop dat er een pop-up blocker aan staat.\n\nAls je op het (kruisje) X de Close-Knop hebt gedrukt.\nKies dan OK\nKies (stay on this page)!\nKies dan in de pop-up blokker (always allow popups for this site)\nKies nogmaals OK\n\n De pop-up pagina sluit vanzelf binnen 5 seconden\n\nVoor de pagina die dan nog niet is afgesloten.\nSluit dan de pagina nogmaals. en kies dan Annuleren\n\nAls u op een andere browser navigation knop hebt gedrukt.\nKies dan direct; Annuleren. ")
      if (x) {
      window.open("http://www.terraverdedesign.nl/session_end.html");
      window.onbeforeunload= x
      return false;
       }
       else
        {
       return false;
         }
      }
      
      } 
      
      
      createCookie('welkom9268','gegroet9268',0)
      setInterval(function eraseCookie(welkom9268) {
      createCookie('welkom9268',"",-1);
      },200);
      }
      
      
      
      if (is_safari) {
      
      var tesx = 3;
      
      window.onbeforeunload = function(){
          setTimeout(function(){
              tesx = 4;
      		setInterval(function(){
          if (tesx = 4) {
              var x = confirm("\nAls je op het (kruisje) X de Close-Knop hebt gedrukt.\nKies dan OK\n\nAls u op een andere browser navigation knop hebt gedrukt.\nKies dan direct: annuleren.")
       if ( x == true)
         {
      	 window.location = "/session_end.html";
      	 window.onunload = document.location = ("http://www.terraverdedesign.nl/session_end.html");
         }
       else
         {
         }
         }
          },0);
          },50);
      	return "Als je op het (kruisje) X de Close-Knop hebt gedrukt.\nKies dan (Op deze pagina blijven)\nKies dan (OK)\nKies dan (Deze pagina verlaten)\nKies dan (OK)\n\nAls u op een andere browser navigation knop hebt gedrukt.\nKies dan direct: (Deze pagina verlaten)";
       }}
      	
      	
      
      if (is_opera) {
      	awt = window.setTimeout(function eraseCookie(welkom9968) 
      	{createCookie('welkom9968','gegroet9968',0)
      	},1000);	
      	
      xwin = new Object();
        if (readCookie('welkom9988') !== 'gegroet9988') 
      {		
      var xwin = window.open('/bloemenspeciaalzaak-terraverdedesign.html', 'SessionStart')
      , int = window.setTimeout(function () {
      if (xwin.closed !== true) { 
      	  
      	alert('\nKlikt u A.U.B op (OK) en daarna op (Pop-up toestaan) rechtsonder in de hoek van uw scherm.\n\nOpera heeft een extra tabblad nodig om te kunnen zien wanneer u de website verlaat.\n\nSluit beide tabbladen pas bij het verlaten van deze website, bedankt.\n\nBedankt voor uw bezoek.');
              }
          },50);
      }
         createCookie('welkom9988','gegroet9988',0)
      
      kk = window.setInterval(function () {
      if (window.name !== 'SessionStart')
      {
      	window.location.reload();
      	if (typeof xwin.closed == 'undefined')	{
      	alert('\nKlikt u A.U.B op (OK)/n/nDan wordt de session beeindigd bedankt.')
      	
      	var xwun = window.location.href = '/session_end.html';
      	}
      }},2000);
         
      
      	if ( $("input[type=submit]").bind("click", function(event) {
          if(event.target.href) {
              	
      
      	
      	} else {
              	
      			int = window.setTimeout(function eraseCookie(welkom9968) {
      			createCookie('welkom9968',"",-1);
      			},0);
      
      	}}));
      	  
      	 
      	 if (   $(window).bind('click', function(event) {
            	   if(event.target.href){
              	
      			int = window.setTimeout(function eraseCookie(welkom9968) {
      			createCookie('welkom9968',"",-1);
      			},0);	
      		} else {
                  
      	}}));
      	
      }
      	
      
      
      	
      	
      function okEvent(){
           validNavigation = true;
        }
      
      $(':button').click(okEvent);
      $("form").bind("submit", okEvent );
      
      
      
          $("a").bind("click", function() {
          validNavigation = true;
      	window.onbeforeunload= null;
      	   window.onunload= null;
      	   
        });
       
       	 $('a').click(function(){
      	  validNavigation = true;
      	  window.onbeforeunload= null;
      	   window.onunload= null;
      	   
      
      });
       
       
      $(window).bind('click', function(event) {
             if(event.target.href) $(window).unbind('beforeunload');
      	   validNavigation = true;
      	   window.onbeforeunload = null;
      	   window.onunload = null;
      	   
      });
      
      
      
        
      
        
        document.onkeydown = function disableKeys() {
        if( typeof event != 'undefined' ) {
          if(event.keyCode == 116) {
            validNavigation = true;
            event.keyCode = 0;
          }
        }
      };
      
         $("form").bind("submit", function() {
          validNavigation = true;
        });
      
          $("input[type=submit]").bind("click", function() {
          validNavigation = true;
        });
      
      }
      
      $(document).ready(function() {
        wireUpEvents();
      });
      
      

      Like

      1. Opps i see i posted the dutch version here is the english version!”

        
        var validNavigation = false;
        function wireUpEvents() {
        
        var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
        var is_opera = navigator.userAgent.toLowerCase().indexOf('opera') > -1; 
        var is_safari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
        
        if (is_chrome) {
        var test = 1;
        window.onbeforeunload = function(){
            setTimeout(function(){
                test = 2;
        		setInterval(function(){
            if (test = 2) {
                var x = confirm("\nIf you pushed the (cross) X the Close-button.\nChoose OK\n\nIf you pushed a other browser navigation button\nChoose: Cancel.")
         if ( x == true)
           {
        	 window.location = "/session_end.html";
        	 window.onunload = document.location = ("http://www.terraverdedesign.nl/session_end.html");
           }
         else
           {
           }
           }
            },0);
            },50);
        	return "If you pushed the (cross) X the Close-button..\nChoose (Stay on this page)\nChoose (OK)\nChoose (Leave this page)\nChoose (OK)\n\nAIf you pushed a other browser navigation button\nChoose: (Leave this page)";
         }
         
        }
        createCookie('rescookie','restcookie',0)
        function createCookie(name,value,days) {
        if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
        }
        
        function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
        }
        if (readCookie('welkom9278') !== 'gegroet9278')
        {
        	var is_fire = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
        if (is_fire) {
        		
        window.onbeforeunload = function(){  var x=window.confirm("Oops.. it seems a pop-up blokker is on.\n\nIf you pushed the (cross) X de Close-button.\nChoose: OK.\nChoose (stay on this page)!\nThan choose in the pop-up blokker (always allow popups for this site)\nChoose OK again\n\nThe pop-up page closes automaticly in 5 seconds\n\nChoose leave this page for the page that you stayed on.\n\nIf you pushed a other browser navigation button.\nYou need to choose Cancel this will execute the browser navigation button function. ")
        if (x) {
        window.open("http://www.terraverdedesign.nl/session_end.html");
        return false;
        }
        else {
        
        }
        }
        
        }
        
        createCookie('welkom9278','gegroet9278',0)
        setInterval(function eraseCookie(welkom9278) {
        createCookie('welkom9278',"",-1);
        },200);
        }
        
        if (readCookie('welkom9268') !== 'gegroet9268')
        {
        	var is_msie = navigator.userAgent.toLowerCase().indexOf('msie') > -1;
        	if (is_msie) {
        	
        window.onbeforeunload = function(){  var x=window.confirm("Oops.. it seems a pop-up blokker is on.\n\nIf you pushed the (cross) X de Close-button.\nChoose: OK.\nChoose (stay on this page)!\nThan choose in the pop-up blokker (always allow popups for this site)\nChoose OK again\n\nThe pop-up page closes automaticly in 5 seconds\n\nChoose leave this page for the page that you stayed on.\n\nIf you pushed a other browser navigation button.\nYou need to choose Cancel this will execute the browser navigation button function. ")
        if (x) {
        window.open("http://www.terraverdedesign.nl/session_end.html");
        window.onbeforeunload= x
        return false;
         }
         else
          {
         return false;
           }
        }
        
        } 
        
        
        createCookie('welkom9268','gegroet9268',0)
        setInterval(function eraseCookie(welkom9268) {
        createCookie('welkom9268',"",-1);
        },200);
        }
        
        
        
        if (is_safari) {
        
        var tesx = 3;
        
        window.onbeforeunload = function(){
            setTimeout(function(){
                tesx = 4;
        		setInterval(function(){
            if (tesx = 4) {
                var x = confirm("\nIf you pushed the (cross) X the Close-button.\nChoose OK\n\nIf you pushed a other browser navigation button\nChoose: Cancel.")
         if ( x == true)
           {
        	 window.location = "/session_end.html";
        	 window.onunload = document.location = ("http://www.terraverdedesign.nl/session_end.html");
           }
         else
           {
           }
           }
            },0);
            },50);
        	return "If you pushed the (cross) X the Close-button..\nChoose (Stay on this page)\nChoose (OK)\nChoose (Leave this page)\nChoose (OK)\n\nAIf you pushed a other browser navigation button\nChoose: (Leave this page)";
         }}
        	
        	
        
        if (is_opera) {
        	awt = window.setTimeout(function eraseCookie(welkom9968) 
        	{createCookie('welkom9968','gegroet9968',0)
        	},1000);	
        	
        xwin = new Object();
          if (readCookie('welkom9988') !== 'gegroet9988') 
        {		
        var xwin = window.open('/bloemenspeciaalzaak-terraverdedesign.html', 'SessionStart')
        , int = window.setTimeout(function () {
        if (xwin.closed !== true) { 
        		 alert('\nPlease Klik on(OK) and then on (Allow Pop-up) Below in the right corner of your display.\n\nOpera needs a extra tab to see if you leave this site.\n\nClose both tabs when you leave this website, Thanks.\n\nThanks for your visit.');
                }
            },50);
        }
           createCookie('welkom9988','gegroet9988',0)
        
        kk = window.setInterval(function () {
        if (window.name !== 'SessionStart')
        {
        	window.location.reload();
        	if (typeof xwin.closed == 'undefined')	{
        	alert('\nPlease klik (OK)/n/nThe the session will be ending.')
        	
        	var xwun = window.location.href = '/session_end.html';
        	}
        }},2000);
           
        
        	if ( $("input[type=submit]").bind("click", function(event) {
            if(event.target.href) {
        
        	} else {
                	int = window.setTimeout(function eraseCookie(welkom9968) {
        			createCookie('welkom9968',"",-1);
        			},0);
        
        	}}));
        	  
        	 
        	 if (   $(window).bind('click', function(event) {
              	   if(event.target.href){
                	
        			int = window.setTimeout(function eraseCookie(welkom9968) {
        			createCookie('welkom9968',"",-1);
        			},0);	
        		} else {
                    
        	}}));
        	
        }
        	
        
        
        //------------------------------------------------------------------------------------------------------------------------------------------------------
        	
        	
        function okEvent(){
             validNavigation = true;
          }
        
        $(':button').click(okEvent);
        $("form").bind("submit", okEvent );
        
        
        
        
        
            $("a").bind("click", function() {
            validNavigation = true;
        	window.onbeforeunload= null;
        	   window.onunload= null;
        	   
          });
         
         	 $('a').click(function(){
        	  validNavigation = true;
        	  window.onbeforeunload= null;
        	   window.onunload= null;
        	   
        
        });
         
         
        $(window).bind('click', function(event) {
               if(event.target.href) $(window).unbind('beforeunload');
        	   validNavigation = true;
        	   window.onbeforeunload = null;
        	   window.onunload = null;
        	   
        });
        
        
        
          
        
          
          document.onkeydown = function disableKeys() {
          if( typeof event != 'undefined' ) {
            if(event.keyCode == 116) {
              validNavigation = true;
              event.keyCode = 0;
        
            }
          }
        };
        
           $("form").bind("submit", function() {
            validNavigation = true;
          });
        
            $("input[type=submit]").bind("click", function() {
            validNavigation = true;
          });
        
        }
        
        $(document).ready(function() {
          wireUpEvents();
        });
        
        

        Like

  35. Hi Jeroen,
    Is it possible to get rid of confirm messages in chrome browser. I think it is confused and not comfortable for end user. Is there any way to end session through onbeforeunload method for Chrome browser like Firefox/IE.
    I user following code for firefox and IE:

    function goodbye(e) {
    	  if (!validNavigation) {
    	  	var e = e || window.event;
    	       // For IE and Firefox
    	      if (e) {			
    	        e.returnValue = '';
    		location.href = "logout.php";
    		return e.returnValue;
    	     }
    	  }
    }
    window.onbeforeunload=goodbye;
    

    here section is expired in IE and FF.
    Please suggest me how can get this in chrome browser.

    Like

    1. I guess the confirm messages of chrome browser is the return messages. how about doing a redirect before the return?

      function goodbye(e) {
        if (!validNavigation) {
          if (dont_confirm_leave!==1) {
          if(!e) e = window.event;
            //e.cancelBubble is supported by IE - this will kill the bubbling process.
            e.cancelBubble = true;
            e.returnValue = leave_message;
            //e.stopPropagation works in Firefox.
            if (e.stopPropagation) {
              e.stopPropagation();
              e.preventDefault();
            }
            //return works for Chrome and Safari
            location.href = "logout.php";
            // return leave_message;
          }
        }
      }
      

      Like

  36. I need to use this script only if user spend < 60 seconds on my site, if this user is our regular customer i dont want to worry him with this message . I'm trying to make js all day, but i cant. May be someone can help me?

    Like

  37. can anyone reply,what to do when i want to delete a file on window/tab close? i am using ajax for this

    $.ajax({
      type: "POST",
      data:"file="+ ,
      url:"delete_csv.php";
      dataType:"json",
      success: function(response)
      {
        alert("Delete");
      }
    });
    

    where to put my ajax code in this case?

    Like

    1. In the example of this post, you can try

      /**
       * This javascript file checks for the brower/browser tab action.
       * It is based on the file menstioned by Daniel Melo.
       * Reference: http://stackoverflow.com/questions/1921941/close-kill-the-session-when-the-browser-or-tab-is-closed
       */
      var validNavigation = false;
      
      function wireUpEvents() {
        /**
         * For a list of events that triggers onbeforeunload on IE
         * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
         *
         * onbeforeunload for IE and chrome
         * check http://stackoverflow.com/questions/1802930/setting-onbeforeunload-on-body-element-in-chrome-and-ie-using-jquery
         */
        var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the user to be able to leave withou confirmation
        var leave_message = 'You sure you want to leave?'
        function goodbye(e) {
          if (!validNavigation) {
            if (dont_confirm_leave!==1) {
            
              // *********************
              $.ajax({
                type: "POST",
                data:"file="+ ,
                url:"delete_csv.php";
                dataType:"json",
                success: function(response)
                {
                  alert("Delete");
                }
              });
              // *********************
            
              if(!e) e = window.event;
              //e.cancelBubble is supported by IE - this will kill the bubbling process.
              e.cancelBubble = true;
              e.returnValue = leave_message;
              //e.stopPropagation works in Firefox.
              if (e.stopPropagation) {
                e.stopPropagation();
                e.preventDefault();
              }
              //return works for Chrome and Safari
              return leave_message;
            }
          }
        }
        window.onbeforeunload=goodbye;
      
        // Attach the event keypress to exclude the F5 refresh
        $('document').bind('keypress', function(e) {
          if (e.keyCode == 116){
            validNavigation = true;
          }
        });
      
        // Attach the event click for all links in the page
        $("a").bind("click", function() {
          validNavigation = true;
        });
      
        // Attach the event submit for all forms in the page
        $("form").bind("submit", function() {
          validNavigation = true;
        });
      
        // Attach the event click for all inputs in the page
        $("input[type=submit]").bind("click", function() {
          validNavigation = true;
        });
      
      }
      
      // Wire up the events as soon as the DOM tree is ready
      $(document).ready(function() {
        wireUpEvents();
      });
      
      

       

      But your POST request will send to server anyway no matter the user click stay or leave.

      Like

  38. Hi ykyuen,

    Great Script !!! but is there a way to use this script, just on Browser close only and not every page refresh, right now “You sure you want to leave?” alert is coming on very page refresh as well as on Browser close event…..i just want to use this on Browser close and not on refrsh event.

    Like

  39. Hi Friend..
    Good Script..
    I am Using below code…
    ————————————————————————–

    var validNavigation = false;
     
    function endSession() {
      // Browser or broswer tab is closed
      // Do sth here ...
      alert("bye");
    }
     
    function wireUpEvents() {
       window.onbeforeunload = function() {
          if (!validNavigation) {
             endSession();
          }
      }
     
      // Attach the event keypress to exclude the F5 refresh
      $('document').bind('keypress', function(e) {
        if (e.keyCode == 116){
          validNavigation = true;
        }
      });
     
      // Attach the event click for all links in the page
      $("a").bind("click", function() {
        validNavigation = true;
      });
     
      // Attach the event submit for all forms in the page
      $("form").bind("submit", function() {
        validNavigation = true;
      });
     
      // Attach the event click for all inputs in the page
      $("input[type=submit]").bind("click", function() {
        validNavigation = true;
      });
       
    }
     
    // Wire up the events as soon as the DOM tree is ready
    $(document).ready(function() {
      wireUpEvents(); 
    });
    

    ——————————————————————————

    its work great..problem is when i press input type button its giving a endsession method alert message…its should not come..
    when i press input button i am redirecting to another page (using onclick method & redirecting using document.forms[0].submit)

    Please give a solution asap..
    Thank u

    Like

    1. is your input type = “button”? if yes, you could bypass it by adding

      $("input[type=button]").bind("click", function() {
        validNavigation = true;
      });
      

      Like

  40. One thing needs to be corrected though concerning the F5 keypress. Some browsers *cough* IE *cough* will not react on keypress but will react on keydown so that would be a better choice. Also the quotation marks around document stop it from working. it sould be
    $(document) not $(‘document’)

    Like

  41. Thanks for posting this – is the code you provided up to date with all the fixes and suggestions posted via comments over the years? If not, could you provide a js file that is updated available for download?

    Like

  42. I’m using Ajax in some pages…and when I click in some ajax request the code dont work because  validNavigation is set to true.
    Can you help me with that?

    Like

    1. you can add an id on those anchor and exclude them by

      // Attach the event click for all links in the page
        $("a#your-id").bind("click", function() {
          validNavigation = false;
        });
      

      Does it work?

      Like

    1. Hi Prashant,

      You can refer to this comment for the code snippet provided by Jeroen. I haven’t tried to run the code before and i think the code is specifically for Jeroen own use so i think you could just edit it such that it works for you.

      Maybe i will create a github repo for this example later.

      Thanks for your comment. =)

      Kit

      Like

  43. Hello

    I am using the version (Update @ 2012-02-19) script. Implemented simple ajax call to a page that just destroys the session.

    Everything works properly, when closing tabs, etc. …

    But I’m having problems with the F5 (Refresh), even as the script by default ignores the F5, whenever I press this button, activates the alert message and closes my session because he understands that it was like a close tab action.

    Any solution?
    It happens in all browsers.

    Like

    1. The f5 key is handled by this checking

      // Attach the event keypress to exclude the F5 refresh
        $(document).bind('keypress', function(e) {
          if (e.keyCode == 116){
            validNavigation = true;
          }
        });
      

      But if you are using a mac machine the keycode maybe different. you can try adding alert(e.keyCode) and see the keycode value. you may also need to check the e.metaKey. For more info, you can refer to the following post.
      StackOverflow – How does one capture a Mac’s command key via Javascript?

      Like

  44. I cannot get this test included in the wireupevents script, I’ve tried $(‘tr’).on(‘click’ – $(“.rows”) – and a few others. Any ideas?

    Like

      1. try adding

        // Attach the event click for tr
        $("tr").bind("click", function() {
          validNavigation = true;
        });
        

        inside the wireUpEvents().

        And you could add alert() inside the click event so you can confirm if the event is fired or not.

        Like

      2. Sorry – my previous explanation a bit confusing.
        My problem is , I tried this and it does not fire.

        Like

  45. this code works for me but the problem arises when there is a reload page function as when page is reloaded with value it got disconnected

    Like

  46. Hello! This is my first visit to your blog!
    We are a team of volunteers and starting a new initiative in a community in the same niche.
    Your blog provided us beneficial information to work
    on. You have done a outstanding job!

    Like

  47. Hi,

    Thanks for this. I have a question though, I can’t seem to prevent the onbeforeunload event message when I post via iframe target.

    I have this form to submit a file and is posting on an iframe target. I keep getting the alert message of leaving or staying in Chrome. If I stay the form doesn’t get submitted. I wanted to prevent the message and keep on the form submission.

    Would you know if there’s a way? Thank you so much.

    Like

  48. Hi all

    Below code is working for latest chrome(Version 35.0.1916.114 m), firefox(28.0) and also works in IE(11.0.96…….)

    window.addEventListener("beforeunload", function (e) {
      var confirmationMessage = "\o/";
    
      (e || window.event).returnValue = confirmationMessage; //Gecko + IE
      return confirmationMessage;                            //Webkit, Safari, Chrome
    });
    

    Like

  49. Hi,

    My scenario is as follows. I have a registration form and only when the user try to close the browser / tab and navigate to other domains it should show the navigation conformation box.

    In this registration form I have modal popup which has an <a> link and when I click on that it asks for the page navigation confirmation which don’t need as it will redirect to some other page.

    I have added the below bindings to the js file.

    $("a").bind("click", function () {
      validNavigation = true;
    });
    

    Thanks in advance.

    Arul

    Like

    1. if the modal popup is created after you load the js files, the event handler could not be binded. you can make use of the jquery .on() and bind the event handler to the any parent html element which exists before you load the js files. Ex.

      $("#modal-container").on("click", "a", function(){
        validNavigation = true;
      });
      

      Like

  50. Hi All,
    Problem on browser reload,refresh from mouse the logout actions is being called.
    Testing on latest chrome(Version 35.0.1916.114 m), firefox(28.0) and in IE(11.0.96…….)

    How to restrict browser reload on chrome and refresh on IE etc.

    can anyone help?

    Please give suggestions if anyone faces this type of problem.

    Like

  51. how we detect browser close , tab close and back and forward button event in javascript when event is performed on mouse click event?

    Like

  52. HI Thanks,

    The script you all mentioned above is working but onbeforeunload event is being fired on browser close as well as on page refresh. Is there any way to fire this event only on browser close not on page refresh. For F4 and CTRL+F4 we can trace key code and prevent them but what to do in case of browser refresh button click or if someonel click in address bar and press enter. In these cases your script is not working. I would appreciate any help in it. Looking forward to hear you you.

    var validNavigation = false;
    var test = false;
    
    function wireUpEvents() {
    
      var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the user to be able to leave withou confirmation
      var leave_message = ‘You sure you want to leave ? ’
        function goodbye(e) {
          if (!validNavigation) {
            if (dont_confirm_leave !== 1) {
              if (!e) e = window.event;
              //e.cancelBubble is supported by IE – this will kill the bubbling process.
              e.cancelBubble = true;
              e.returnValue = leave_message;
              //e.stopPropagation works in Firefox.
              if (e.stopPropagation) {
                e.stopPropagation();
                e.preventDefault();
              }
              //return works for Chrome and Safari
              return leave_message;
            }
          }
        }
    
      window.onbeforeunload = (function(event) {
    
          if (!validNavigation) {
            return goodbye(event);
          }
        })
        // Attach the event keypress to exclude the F5 refresh
      $(document).bind(‘keydown’, function(e) {
        getKeyCode(e);
    
        if (keyCd == 116) {
          validNavigation = true;
        }
    
        if (altKy &&
          (keyCd == 18 || keyCd == 115)) {
          validNavigation = true;
        }
        if (keyCd == 13) {
          validNavigation = true;
        }
      });
    
      // Attach the event click for all links in the page
      $(“a”).bind(“click”, function() {
        validNavigation = true;
      });
    
      // Attach the event submit for all forms in the page
      $(“form”).bind(“submit”, function() {
        validNavigation = true;
      });
    
      // Attach the event click for all inputs in the page
      $(“input[type = submit]“).bind(“click”, function() {
        validNavigation = true;
      });
    
    }
    
    function getMouseButton(event) {
      if (IE == true) {
        mouseBtn = event.button;
      }
      if (Netscape == true) {
        if (event.which == null)
          mouseBtn = event.button;
        else
          mouseBtn = event.which;
    
      }
    }
    
    function getKeyCode(event) {
        if (IE == true) {
          keyCd = event.keyCode;
          altKy = event.altKey;
          ctlKy = event.ctlKey;
          shiftKy = event.shiftKey;
        }
        if (Netscape == true) {
          if (event.which == null)
            keyCd = event.keyCode;
          else
            keyCd = event.which;
    
          altKy = event.altKey;
          ctlKy = event.ctrlKey;
          shiftKy = event.shiftKey;
        }
    
      }
      // Wire up the events as soon as the DOM tree is ready
    $(document).ready(function() {
      var keyCd, altKy, mouseBtn, ctlKy, shiftKy;
      Browser = navigator.appName
      Net = Browser.indexOf(“Netscape”)
      Micro = Browser.indexOf(“Microsoft”)
      Netscape = false
      IE = false
      if (Net >= 0) {
        window.captureEvents(Event.MOUSEDOWN)
    
        Netscape = true
      }
      if (Micro >= 0) {
        IE = true
      }
      wireUpEvents();
    
    });
    

    Like

  53. Can we detect back & foward button and then we will not display message. The message only display when user click on close button of the browser? It can be?

    Like

  54. Hi all,
    I’ve make like that, but I cannot handle event (back, foward, reload ) in browser bar.
    could anyone help me about it.
    thank in advance.

    Like

  55. i want record time duration from Once play video in web by clicking play button(built-in or player screen)
    i don’t know which event should i take???

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s