Get Help:Ask a Question in our Forums|Report a Bug|More Help Resources
Last post Apr 05, 2010 01:46 PM by A1ien51
Sep 03, 2007 07:11 AM|LINK
Hey can any one please brief me on how to detect the browser close event in ASP.Net (C#)
Sep 03, 2007 10:44 AM|LINK
You have the onUnload event of the body.
!!!!!!! ---> The problem with this event is that you can't cancel the unloading of the page in this event. The event says it itself. onUnload, which means the page is already unloading.
In InternetExplorer, you have the OnBeforeUnload event of the body. This is a good one to check the unloading of a webapp. And you should check google for equal events like onbeforeunload but then for firefox. (for example: google 'onbeforeunload firefox')
There is one this you should keep in mind!!! ---> You can never catch the browser close event for the full 100%.
For example, what if the user kills the browser process. Then the onUnload, or even the onBeforeUnload isn't called.
if((window.event.clientX<0) || (window.event.clientY<0))
event.returnValue = "If you have made any changes to the fields without clicking the Save button, your changes will be lost.";
You can for example run this script everytime a mouse button is clicked (well, maybe that's some overhead.) But then again, what if a user closes his browser with the key combination ALT + F4?
I hope this info has been usefull.
If you have questions/remarks please do so!
Sep 04, 2007 07:13 AM|LINK
Hi Wim Thanks for your comments. Its absolutely answer my question.
Its really a worthy answer.
Actually i have a requirement like for example I have a login page and i have logged in,
now while clicking logout button i have to do some database updation and suddenly without clicking the logout button if the user
closes the window no updation will take place. More over i also need to check if some one try to login with the details which is already logged in.
Can you please comment on this
Sep 04, 2007 11:06 AM|LINK
Hi Nicsam, sorry but I can't give you specific code (because I don't have it), just my considerations ...
now while clicking logout button i have to do some database updation and suddenly
Is it a website/application for an intranet or for the internet? For example when it's for an intranet, you probably know your group of end-users and they can get a training in how to log-out, so that the way of loggin out is consistent. When you have an
internet site you can't do this.
What kind of authentication do you have?
When you press a logout button, then in the click event of that button you will probably do some of these things:
- session.abandon() ----> abandon the user's session
- formsAuthentication.SignOut() ---> if you use forms auth. / this makes the authentication Ticket expire (I guess)
- here you can do your database updates.
!!!!!! BUT as I already said ... what if the user presses ALT + F4 to close the window ....
In the global.asax file you have a Session_End event. Whenever a session expires for a certain user, this event is called. Maybe you can do the database updates here? But there can be a delay on this event. You have to keep that in mind. For example if a
user log's out (the wrong way), and you have set a session timout of 15 minutes, then it can take up to 15 minutes until the event gets called.
one) Maybe this is something you can do!, but setting it with a timeout of 1 minute will be too small I guess and may cause overhead for the application.
More over i also need to check if some one try to login with the details which is already logged in.
I searched google on 'asp.net restrict logins' .... and then a few threads on this forum came up, and also some other links ....
In general what they talked about was the following:
- Everytime a user logs in, you should create an Application wide session variable which stores the userName. Then when a user tries to start another session, for example by logging in again from another browser, you can check your app. wide session variable
to see if it exists already. You have to watch out with this approach!!!!!! WHY: This can be a bottleneck for your application depending on where you store your Session information. If it is stored in memory of the WebServer, then it can get overloaded and
your website will hang/crash. Another thing: If the user logs out the wrong way, then the session isn't killed instantly (remember the session timeout). This will cause a lockout for a userAccount for a maximum time equal to the session-timeout.
- You could use a database table where you set flags (boolean) when a user is logged-in. Here you have the same problem as in the above example. You should set the flag back to false again when the user log's out. But because you can't catch the logging-out
of the user with a 100% certainty (well you can with the session_end event I guess), there will be some delay on the database changes and therefore a user can be locked-out for a certain amount of time.
Again sorry that there aren't any specific examples, only considerations.
If you do have questions etc ... let me know!
Sep 06, 2007 11:29 AM|LINK
Hi Wim Thanks for your comments.
Its really answers my doubts, still i need to consider the points you mentioned like the case of (AltF4) and consider all these cases.Definitely I will let you know any doubts with this.
Mar 08, 2008 04:02 PM|LINK
Here is solution for ALT+F4,
Remember, still as Deblendewim explained. its still not 100%.(eg. user can kill the browser with task manager, or may be can close window from bottom task bar etc..)
Thanks to deblendewim! you explained situation very well.I just have one doubt. does really session_End will execute after perticular session timeout for the user who closed his window? I never tested it, but I just doubt it. lets say in
my Session_End , I am doing something like below.
will user session who closed his window ever come across this line to execute? I mean User.Identity.Name.ToString() will still available for that user??
Dec 24, 2009 04:21 PM|LINK
I am running into the same issue, I got to know after searching it on goggle for more then 2 hours, that there is no specific way that you can detect the browser closing event, Like Niscam I am having an web app where I need to see if user is ideal for say
30 min or closes browser without log out then I need to update the database values, I am not sure if It is possible but I had seen it live on a web site where it alerts every tieme we try to close browser eben on ALT + F4 and closing the tab from file menu.
Its really shocking for me as I tried the onbeforeunload method which produces alerts every time page is reload or even if i try to navigate away from the page. That takes to search if at the time "onbeforeunload" is called the event is browser close and not
else. I got to knoe the windo.clientX and window.clientY but it only works in IE and not in FF and others.
Please do reply if any ideas...
Dec 24, 2009 04:36 PM|LINK
Here is a sample of calling a server-side method when a window is closed. The server-side functionality is written in C#, but is easily converted to VB by using
It entails creating a separate page (in this sample, LogoffPage.aspx) to house the function (the page will never display), but multiple functions to call could be placed there and accessed via the QueryString. This is basically the same as creating a Web
Service, which would be a better solution, but more difficult to post here.
function callAjax(webUrl, queryString)
var xmlHttpObject = null;
// Firefox, Opera 8.0+, Safari...
xmlHttpObject = new XMLHttpRequest();
// Internet Explorer...
xmlHttpObject = new ActiveXObject('Msxml2.XMLHTTP');
xmlHttpObject = new ActiveXObject('Microsoft.XMLHTTP');
if ( xmlHttpObject == null )
window.alert('AJAX is not available in this browser');
xmlHttpObject.open("GET", webUrl + queryString, false);
var g_isPostBack = false;
window.onbeforeunload = function ()
if ( g_isPostBack == true )
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;
// Other browsers...
g_isPostBack = false;
window.onunload = function ()
if ( g_isPostBack == true )
var webUrl = 'LogoffPage.aspx';
var queryString = '?LogoffDatabase=Y&UserID=' + '<%= Session["UserID"] %>';
var returnCode = callAjax(webUrl, queryString);
private void Page_Load(object sender, System.EventArgs e)
if ( this.IsPostBack )
this.Session["UserID"] = "12345";
this.RegisterOnSubmitStatement("OnSubmitScript", "g_isPostBack = true;");
protected string LogoffUser(string userId)
string returnValue = "OK";
// Call the database, logging the user off here...
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());
Dec 26, 2009 12:13 PM|LINK
It really worked for me, I ma feeling like getting a toy from the santa, I had tried this in a test project and its workign fine, I will be implementing this to in my application next week. Thanks Thanks a bunches to you. And yes a, Merry Christmas to
you as well.
Apr 05, 2010 05:55 AM|LINK
I needed a similar solution and I tried implementing this method in my c# asp.net application. Its not working.
I need to change a value in database , if the user closes the browser without logging off. Please let me know why its not working.