title: How to detect Browser / Tab is closed
body: <p>i want to alert box when browser is closed or browser tab is closed. I had some code but in this 1 extra message is coming.. I want to know from where it is coming in alert box. if any other code you have then send me or tell me what should i do.. actually i want to avoid second user login (For this i create 1 session id and save in DB after that every time when user login it check session id is in DB or not if then user can login, when user log out session id is also deleted but browser or tab is closed then session id is not deleted. for this i want to detect that one after that i want to send the control to ajax controller ) that's why i want to know from where 1 extra message is coming. please solve my problem ..   </p>
  
  <pre><code>&lt;script type="text/javascript" &gt;
  var validNavigation = 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=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();
  }); 
  &lt;/script&gt;
  </code></pre>