Solved

How to detect browser close in ASP.NET

Posted on 2010-11-13
7
1,234 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
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
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…

708 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

16 Experts available now in Live!

Get 1:1 Help Now