Solved

How to detect browser close in ASP.NET

Posted on 2010-11-13
7
1,239 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
  • 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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
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 500 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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
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…

929 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now