How to detect browser close in ASP.NET

I have an asp.net application where I need to track user login logoff acitivity. The app has a login page where everytime a user logs in I want to record tthe login time and when he/she signs off we record the logoff time. This all works well.

But I need to know how can I detect if the user closed the browser (the red x)
So that I can throw a message stating" do you want to close your session, if yes then record the logout time.
I need this to work in IE and also in other browsers, any code samples will be great
LVL 1
countrymeisterAsked:
Who is Participating?
 
Carl TawnConnect With a Mentor Systems and Integration DeveloperCommented:
It fires when the Session terminates on the server, 20 minutes after the users last activity by default, although you can configure the timeout period.

The browser closing is a purely client-side event, the server isn't notified of it.
0
 
Carl TawnSystems and Integration DeveloperCommented:
You can't detect that specifically, but what you can use is the "unload" event.

  <body onunload="doSomething();">
      ...
  </body>

Open in new window

0
 
countrymeisterAuthor Commented:
carl_tawn:

I have quite a few aspx pages, do I have to add this javascript code in each of my aspx pages.

Also while looking for a solution I came upon the following link
http://forums.asp.net/p/1153888/1891072.aspx

What are your thoughts on that
//////////////////////////////////////////////////////////////////////////
// Page1.aspx
//////////////////////////////////////////////////////////////////////////

<script type="text/javascript">
<!--
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;
}
// -->
</script>

<script type="text/javascript">
<!--
var g_isPostBack = false;

window.onbeforeunload = function ()
{
 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 = 'LogoffPage.aspx';
 var queryString = '?LogoffDatabase=Y&UserID=' + '<%= Session["UserID"] %>';
 var returnCode = callAjax(webUrl, queryString);
 //alert(returnCode);
}
// -->
</script>

//////////////////////////////////////////////////////////////////////////
// Page1.aspx.cs
//////////////////////////////////////////////////////////////////////////

private void Page_Load(object sender, System.EventArgs e)
{
 if ( this.IsPostBack )
 {
  this.Session["UserID"] = "12345";
 }

 this.RegisterOnSubmitStatement("OnSubmitScript", "g_isPostBack = true;");
}

//////////////////////////////////////////////////////////////////////////
// LogoffPage.aspx.cs
//////////////////////////////////////////////////////////////////////////

protected string LogoffUser(string userId)
{
 string returnValue = "OK";

 // Call the database, logging the user off here...

 return returnValue;
}

private void Page_Load(object sender, System.EventArgs e)
{
 string logoffDatabase = (this.Request["LogoffDatabase"] == null) ? string.Empty : this.Request["LogoffDatabase"];
 string returnValue = string.Empty;

 if ( logoffDatabase == "Y" )
 {
  if ( returnValue.Length > 0 )
   returnValue += ", ";

  returnValue += this.LogoffUser(this.Session["UserID"].ToString());
 }

 this.Response.ClearHeaders();            
 this.Response.Clear();
 this.Response.Write(returnValue);
 this.Response.End();
}

Open in new window

0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
Carl TawnSystems and Integration DeveloperCommented:
You only need to call a method from the unload. If you are using a master page then you only need to change it in one place.

The downside to using onbeforeunload is that it will only work with IE. You other option of course is to use the Session_End event on Global.asax to record the log out rather than specifically trying to catch when the user closes the browser.
0
 
countrymeisterAuthor Commented:
carl_tawn:
If I use the Session_End event will that cause the logout to occur only when the session timeout expires, or will it trigger when the user has closed the browser.
I am not clear on this.
0
 
countrymeisterAuthor Commented:
Thanks again, I guess besides all these checks to handle the closing of the browser I iwll not be able to handle situations when they close the browser from task manager
0
 
Carl TawnSystems and Integration DeveloperCommented:
True. Client-side options are available, but none of them are 100% reliable, and you simply can't detect every possible manner of the browser closing. Server-side events will be more reliable, but there will be a time-delay before it fires.
0
All Courses

From novice to tech pro — start learning today.