?
Solved

How to detect browser close in ASP.NET

Posted on 2010-11-13
7
Medium Priority
?
1,256 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
Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

 
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

Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

Question has a verified solution.

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

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
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

770 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