title: Catching A Browser Close Event
body: <p>Hello Seniors (As I am new to Web Based Applications),
  I was keen to implement or catching browser closing event.
  Yes! I did it and successfully implemented it by using javascript{see code below}
  but I have implemented it in a web page without MasterPage.
  Now, as I am trying to implement it in a webpage with MASTERPAGE but in each post back...the event window.onunload is caught, which is giving me problems...
  Is there any technique or logic to detect whether I can differentiate between a Close browser button and  a page's post back event.</p>
  
  <p>Please guide me...as I have to implement in a project as soon as possible....
  thank you.</p>
  
  <p>Ankit Srivastava</p>
  
  <pre><code> &lt;script type="text/javascript"&gt;
  
          function callAjax(webUrl, queryString)
          {
              var xmlHttpObject = null;
  
                  try
                  {
                          // Firefox, Opera 8.0+, Safari...
  
                          xmlHttpObject = new XMLHttpRequest();
                      }
                 catch(ex)
                  {
                         // Internet Explorer...
  
                  try
                      {
                          xmlHttpObject = new ActiveXObject('Msxml2.XMLHTTP');
                      }
                  catch(ex)
                  {
                      xmlHttpObject = new ActiveXObject('Microsoft.XMLHTTP');
                  }
               }
  
              if ( xmlHttpObject == null )
                  {
                  window.alert('AJAX is not available in this browser');
                  return;
                   }
  
          xmlHttpObject.open("GET", webUrl + queryString, false);
          xmlHttpObject.send();
  
          return xmlText;
  }
  
  &lt;/script&gt;
  
  &lt;script type="text/javascript"&gt;
  
  var g_isPostBack = false;
  
  window.onbeforeunload = check ()
  function check()
  {
   if ( g_isPostBack == true )
    return;
  
   var closeMessage =
    'You are exiting this page.\n' +
    'If you have made changes without saving, your changes will be lost.\n' +
    'Are you sure that you want to exit?';
  
   if ( window.event )
   {
    // IE only...
  
    window.event.returnValue = closeMessage;
   }
   else
   {
    // Other browsers...
  
    return closeMessage;
   }
  
   g_isPostBack = false;
  }
  window.onunload = function ()
  {
   if ( g_isPostBack == true )
    return;
  
   var webUrl = 'LogOff.aspx';
   var queryString = '?LogoffDatabase=Y&amp;UserID=' + '&lt;%# Session["loginId"] %&gt;';
   var returnCode = callAjax(webUrl, queryString);
  
  }
  
  &lt;/script&gt;
  </code></pre>