?
Solved

How to detect browser close in ASP.NET

Posted on 2010-11-13
7
Medium Priority
?
1,262 Views
Last Modified: 2012-05-10
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
0
Comment
Question by:countrymeister
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
7 Comments
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 34127350
You can't detect that specifically, but what you can use is the "unload" event.

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

Open in new window

0
 
LVL 1

Author Comment

by:countrymeister
ID: 34127360
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
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 34127364
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
Fill in the form and get your FREE NFR key NOW!

Veeam® is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

 
LVL 1

Author Comment

by:countrymeister
ID: 34130790
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
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 2000 total points
ID: 34130878
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
 
LVL 1

Author Closing Comment

by:countrymeister
ID: 34130894
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
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 34130901
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

Featured Post

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
In this blog, we’ll look at how improvements to Percona XtraDB Cluster improved IST performance.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

649 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question