CodeSnip: Handle Browser Close Event on the Server-Side
page 1 of 4
Published: 07 Jun 2007
In this article Bilal Haidar demonstrates how to handle the close event of the browser on the client side and execute a server side method on the server code.
by Bilal Haidar
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 118607/ 91


During the last couples of years, we have already seen so many questions, on website, asking how to fire some code on the server side when the user closes the browser.  The answer was always, the browser will only fire a client side event and the server side cannot be notified when the page is closed.

This is true and valid until AJAX came into life! Using AJAX we can do anything we want on the server side of the page whenever the user closes the browser.

One possible thing we might want to do is when the user closes the browser, kill the session on the server side immediately without having to wait until the session times out! This means, we will fire the Session_End event on the spot when the session is killed and this way we make sure the Session_End will fire for sure! Believe me, this is very helpful.

View Entire Article

User Comments

Title: I have a question   
Name: sATs
Date: 2013-02-02 8:57:51 AM
how we can update database using this ....
Title: Thank YOu   
Name: Keshab Pandey
Date: 2013-01-24 5:41:19 AM
Thank you so much.
This article really helped me.
Once again thanks alot.
Title: as   
Name: sa
Date: 2012-12-24 3:36:38 AM
Title: asdf   
Name: asdf
Date: 2012-09-02 2:15:27 AM
Title: Limited solution   
Name: Sreenivas
Date: 2012-08-01 8:48:24 AM
1. This will work only when u have one page and no links from the page
2. It work if you maintain a flag like 'validnavigation' (hidden in master)which will set to true when you hit any navigation button or link on the pages. then u manage if the flag is true the navigate to the other page or confirm and kill session
Title: 12   
Name: 12
Date: 2012-07-25 8:39:02 AM
Title: it does not work at all   
Name: PK
Date: 2012-06-26 1:09:59 PM
Pagemethods undefined error
what kind of framework does this solution work.
Title: Also work on refresh   
Name: Akshay
Date: 2012-03-17 3:08:41 AM
This code also works on page refresh!any idea about the code that works only on close event
Title: session kill   
Name: nuthan
Date: 2012-02-28 4:19:41 AM
if my page is child of master page then how can i do this for current page.
please provide sample code for that
Title: Code for master page   
Name: Mishtha.........
Date: 2011-11-30 7:14:16 AM
This works fine with normal aspx page bt i want code for master page as all of child aspx pages are in content place holder.....
Title: Very Good   
Name: MohamedSlam
Date: 2011-09-17 10:34:40 AM
Very Smart Somone
Title: Page Refresh   
Name: Sami
Date: 2011-05-21 10:17:41 PM

Body unload event will also triggered When the user refresh the page.I don't think so this method is right way.
Title: how to use this code when moving another pages   
Name: vino
Date: 2011-04-25 8:04:05 AM
the above coding is applicable for single page, if im moving from one page to another page using link, the AbandonSession() is firing so i coundnt open another page, plz help
Title: Master Page   
Name: Marlon
Date: 2011-04-07 1:27:20 PM

This solution does not work on MasterPages, there is allways an error (PageMethods is undefined)
Title: it helped me a lot , great thanks   
Name: Hdev
Date: 2011-02-14 4:36:53 AM
Thank you very much
Title: Mr   
Name: gangeshvar
Date: 2011-01-12 4:52:45 AM
Hi, i added the Listing 1 to 3 in Aspx file and Listing 4 in .Cs file, I'm able to get alert message but not the .Cs file event? I gave break point to check it didnt, i even wrote a code to insert some values in DB in the Listing4 so to check if it got fired, No luck.... appreciate if you could suggest!!!!!
Title: How can i restrict a user to navigate back to a secure a rea once he has left it by pressing the browser back button.   
Name: Patrick
Date: 2010-11-15 5:56:35 AM
How can i restrict a user to navigate back to a secure area once he has left it without logging off.
Title: How Can I Fire unload event in FireFox   
Name: Liza Rajesh
Date: 2010-10-12 5:15:47 AM
How Can I Fire unload event in FireFox
Title: Mr   
Name: Ralph Daudi
Date: 2010-07-28 10:41:08 AM
Hello. Am having problems on implementing the method on a Master-Child page application coz it unloads and reloads the master page with each navigation and on most control clicks.
Title: Mr.   
Name: Ganesh Patil
Date: 2010-07-09 2:49:44 AM
Hi, i added the Listing 1 to 3 in Aspx file and Listing 4 in .Cs file, I'm able to get alert message but not the .Cs file event? I gave break point to check it didnt, i even wrote a code to insert some values in DB in the Listing4 so to check if it got fired, No luck.... appreciate if you could suggest!!!!!!
Title: Sr. Developer   
Name: Kumar
Date: 2010-06-14 1:06:22 AM
"window.event.clientY" won't work on firefox 6.3.6 version
Title: Imp Comment   
Name: NA
Date: 2010-05-25 2:46:51 PM
This codes does not work...
A page can have only one server-side Form tag.
Title: onunload   
Name: Shawpnendu
Date: 2010-04-22 8:50:30 AM
onunload has some implication specially when you navigate from one page to another page using linkbutton. onunload also fired at that time.
Title: System Analyst   
Name: Umesh Kapadi
Date: 2010-04-09 7:16:25 PM
Do you think this will work as this HandleClose event will fire even when u move to a different state.
Title: OnUnload   
Name: Malik
Date: 2010-04-06 6:20:01 PM
/*if(window.event.clientY < 0 && window.event.clientY < -80)*/

this line not work on firefox!!
Title: OnUnload   
Name: Malik
Date: 2010-04-06 6:16:32 PM
Hi, OnUnload event fires on page refresh!
what is this solution?
Title: Handle Browser Close Event on the Server-Side   
Name: pinko
Date: 2010-03-19 3:53:28 AM
what if JavaScript is Disable in browser?
Title: Fantastic   
Name: Sabyasachi Banerjee
Date: 2010-03-19 3:25:12 AM
Excelent post.
This saved my day
Title: This is completely wrong Bilal   
Name: Harish
Date: 2010-02-25 8:26:56 AM
Bilal, Unload event fired for every post back man not only window close.
Title: Wow Man   
Name: Sayem
Date: 2010-02-08 8:31:25 AM
Wow man, this snippet helped me a lot. Thank you very much...
Title: this code is not run   
Name: this code is not run
Date: 2010-01-25 2:16:35 AM
this code is not running
this is not possible also in ajax
Title: Onunload   
Name: Himali
Date: 2009-10-29 7:49:00 AM
Onunload method fires on postback so i can't access session in other pages.
Title: Listing 4   
Name: Himali
Date: 2009-10-29 7:19:52 AM
Where to put code of listing 4?In aspx.cs file webmethod is not valid attribute.I hv Put it in Mypage.aspx.cs but it doesnt work.
Title: Web Methods   
Name: Santosh
Date: 2009-10-06 3:29:54 AM
This works only for the single page. If the user navigate to another page then this function called and session abandoned.
Title: did't work   
Name: sam
Date: 2009-10-02 4:28:08 PM
I did same as mensioned above. created Webservice name of PageMethods. and created a method AbandonSession(). But the web method is not firing. And tried just only AbandonSession() in default.aspx.cs file But no Luck. still it is not firing.
Title: in which file   
Name: AlanRR
Date: 2009-09-17 2:33:57 AM
Hi rex,

The AbandonSession method has to be in your .cs file. For example if you have demo.aspx and demo.aspx.cs files. AbandonSession method would be in demo.aspx.cs file.

In demo.aspx you need to include the Listing1, Listing2 and Listing3.
Title: web method   
Name: rex
Date: 2009-09-11 5:24:23 PM
new to this - first site and am a bit confused by: "On the server side, all that you have to do is define the AbandonSession method and add to it the WebMethod attribute."

Where do I create the AbandonSession method? I have tired in Global.azax but that never fires... thanks!
Title: Handle browser close event   
Name: AlanRR
Date: 2009-09-03 7:37:23 PM
It's working.

For me in HandleClose() funtion didn't work:
if(window.event.clientY < 0 && window.event.clientY < -80)

So I used:
if (window.event.clientX < 0 || window.event.clientY < 0)

and with this works.

Title: Handle browser close event   
Name: pavan
Date: 2009-08-28 2:14:41 AM
Thanks a lot, it's working.
Title: not working in postback   
Name: rajesh
Date: 2009-08-10 2:35:17 AM
thanks for the article but this code works good for only single page or if page has no postbacks. I applied this in my application and when i goto other aspx pages from the page where i applied this code, onunload calling and session gets killed.
Title: Developer   
Name: Scott
Date: 2009-08-04 3:52:12 PM
Just wanted to say thanks for posting this. Excellent article.
Title: For all browsers   
Name: Vidyasagar
Date: 2009-06-13 3:07:02 AM
function confirmExit()
if(window.event.clientY < 0 && window.event.clientY < -80)
var xmlhttp;
if (window.ActiveXObject) { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");"GET","AbandonSession.aspx",false);
if (window.XMLHttpRequest)
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();"GET","AbandonSession.aspx",false);
Title: session   
Name: trimp
Date: 2009-06-04 5:42:29 AM
thanks a lot
Title: Superb Article   
Name: S Kumar
Date: 2009-06-04 2:09:59 AM
Really very good article Bilal.Thanks.
Title: how to use it in master page   
Name: bharath
Date: 2009-03-26 12:35:50 AM
hi everyone,
i am using masterpage in my project, where during login i what to lock the logged user in db, and when he close the browser it should be unlocked i have used the example which was stated above of no use as AbandonSession method is not fired so can any one tell me a solution for this
Title: Satisfied Fully   
Name: Arnab
Date: 2009-02-17 8:10:01 AM
I was finding the method to handle event after browser is closed but result was in vain until I came through this Link.
Thanks very much...................
Title: Not totally Ok   
Name: Ali BARMAT
Date: 2008-12-17 4:46:15 AM
this code is nicely done , it works fine but there are some bug : the event onunload do not fire only when the browser window is closed , in fact it's related to any action that makes the page body "empty", and since that , it fires also when you refresh the page....

Bilal , i need to kill the session when i close the window but not when i refresh my page

one other side : if you use window.event.clientY or window.event.clientX , suppose the user closed his window using Alt+F4 and not with X ... is that handled :D :D :D
Title: onunload is not working   
Name: Vishal
Date: 2008-11-25 1:53:48 AM

What ever the is given is working with onclick,onload but it is not working with onunload.Is there any browser setting ot weconfig setting.
Title: page methods undefined when master page is used   
Name: vidya
Date: 2008-08-19 11:49:17 AM

the below function i used for closing the sessions but when i used master page it is giving error as "Page methods" are undefined

function HandleClose()
if(window.event.clientY < 0 && window.event.clientY < -80)
alert("Killing the session on the server!!");
Title: button click   
Name: nazım
Date: 2008-08-15 4:16:26 AM
you can call a asp button click with that javascript

Title: Other way to handle session Abandon...   
Name: Prashant
Date: 2008-07-25 4:48:50 AM
Hi tushar I have tried your code but still I am not able to kill my session.Thanks in advance.
Title: Works well in IE   
Name: Mark
Date: 2008-07-14 5:39:33 PM
I was using a procedure similar to Angelo's where I was changing the LOGIN_STATE in a SQL Server database to prevent the user from running concurrent sessions.

Tushar's solution works really well as is for IE.
I'm using a Master page and placed the script in the master page. I called Session.Abandon() in the Page_Load event of AbandonSession.aspx and got the Session_End event to fire when I closed my browser so I can do whatever database updates I needed. Again mode="InProc"

I'm still unable to modify the script to work with firefox though.
Title: Other way to handle session Abandon...   
Name: Tushar Mehere
Date: 2008-06-28 11:06:55 AM
I kill my session objects on browser close as below....
The request is being made by the friendly xmlhttp object.

You can create an AbandonSession.aspx and on its PageLoad kill the Session object by calling Session.Abandon. The code below is written for IE. You can adapt the routine for firefox or other browsers.

//Abandon Session
window.onbeforeunload= function() {
if(window.event.clientY < 0 && window.event.clientY < -80)
var xmlhttp;
if (window.ActiveXObject) { // IE
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");"GET","AbandonSession.aspx",false);

Let me know if this was helpful.
Title: how can i handle the kill the session?????   
Name: suchi
Date: 2008-05-29 6:20:41 AM
how to kill the session ,if i close the browser window by choosing the task bar close option ..........
Title: Session on Web Farm   
Name: Anser Basheer
Date: 2008-05-02 2:56:40 AM
your solution basically has problems,
it may work if you have one page application with refresh button and F5 button blocked and session mode is inproc.

for web farm scenario or outproc session, it would fail, because session_end is not available in global.asax
Title: session   
Name: ashok
Date: 2008-04-30 12:09:30 AM
in with c#, when i close the window directly, the session will not kills. so i would like to kill the session automatically.
give me the code please
Title: nothing catches my fancy   
Name: snowflake
Date: 2008-04-24 8:59:33 PM
everything about the browser's x and y close button and the unload event etc etc on the browser work's very fine to me cause im working with my auto log-out features on my site but suddenly i found some problems on it.

- why not logout if the user's computer turns off or some power source runs out w/o triggering the close button?

- why not logout if im not only using firefox,ie(standard browsers) but also safari(it does'nt trigger javascript unload events) or other browser?

here are just some of my suggestions and comments regarding of that demonstration's you make.if that meets my requirements i would be glad to use it for my site cause im really really looking for some "realistic" here...
Title: hey am using JSP   
Name: angelo
Date: 2008-02-04 8:46:09 AM
Correct me if am wrong... OnUnload event is trigerred when the window navigate to other pages and not when the window close when [x]close button is clicked.

I used jsp tags embeded in my html. When a user logged-in, it trigers an event that causes a field in my database (LOG-IN STATUS) to be in logged-in state, so when someone try to log-in with the same username and password (let say, he/she intentionally know your password) that user will be automatically redirected on other apge because a user is currently logged-in or using that account.
When the user, while logged-in accidentally closes the window or when the window is left unmoved, the session is automatically killed. So, when the user tries to access his/her account, he will be again ask to log-in. The problem was, he never logged-out, thus the LOG-IN STATUS in the dbase still is still in LOG-IN STATE. Meaning, the user will ot be able to log-in until the is changed directly on the dbase...?
So, how can i chnage my LOG-STATE when the user accidentally closes the window or when the session expired?
I tried using on unload, but as a stated, it is triggered by browsing to other page and not when closing the window.

thanks, hope you can help, even though you're all using ASP..

(email me @
Title: problem with close and Page Methods   
Name: Imran
Date: 2008-01-07 2:35:14 AM
I have found this article very usefull in one of my scenarios. But in one scenario it doesn't work.
I have a window which open another window. the Child window has this onclose script attached on it. The close script saves the size and location of child window in user profile and parent window loads this info on postback to open the child window on its previous location. The flow which is bouthering me is as follows
1. open child window
2. resize/move the child window
3. close the child window
4. postback the parent window
5. open the child window again
6. resize/move the child window
7. close child window
8. postback parent window
on the 8th step the parent window doesn't completes the postback. the little microsoft icon animates as the browser is requesting something from server but it never completes the request.
I have tried the same code after detaching the close event from the child window and attaching it to a button onclick on the child page and it works fine.
I think there is some problem with the incomplete pageMethod call which occurs in on the close window.
Title: onunload window.event.clientY < 0 && window.event.clientY < -80   
Name: Hann
Date: 2007-12-03 10:58:43 AM
window.event.clientY < 0 && window.event.clientY < -80

works when teh browser is closed in IE 6, this does not work in Firefox, is there any workwround, I am just trying to display a survey
Title: onunload   
Name: Joyal
Date: 2007-11-16 1:06:50 AM
Symo - As i know, You have made a mistake. Because refresh event return when following condition has been satisfied.
if(window.event.clientY < 0 && window.event.clientY > -80)

So, it should be (window.event.clientY < -80)

Also, i would like to know from anyone that how much we can rely on onunload method. Because i have seen many times that onunload event fires sometimes and sometimes it does not fired. Any feedback will be appreciated.

Title: onunload   
Name: Symo
Date: 2007-10-04 6:22:56 AM
DAB - you have a minor typo there, it should be > -80

function HandleClose()
if(window.event.clientY < 0 && window.event.clientY > -80)
alert("Killing the session on the server!!");

I really wish there was some kind of window.onclose event..
Title: onUnload Method problem   
Name: DAB
Date: 2007-09-26 2:29:53 PM
It's true that the onUnload event fires each time the page is refreshed or navigating to another page. To prvent this add the statement below which will check if the page itself is closed:

function HandleClose()
if(window.event.clientY < 0 && window.event.clientY < -80)
alert("Killing the session on the server!!");

THis will prevent the function from executing until the window (Browser) is closed
Title: cant make it working on master pages   
Name: msn
Date: 2007-08-07 10:06:43 AM
i want the same code to work with master page.

i can able to make the same code working by putting the AbandonSession() in each aspx page.

i can able to get the message "Killing the session on the server!!" but the function AbandonSession() will not be called

could you please help me.

thanks in advance
Title: can't get to the server side function   
Name: ajaxX'd
Date: 2007-07-26 5:49:34 PM
when sample gets to
call in the JavaScript it produces the following error:

Microsoft JScript runtime error: 'PageMethods' is undefined

reference to AJAXExtensionsToolbox.dll is there so what is missing?
Title: Re: Josh   
Name: Bilal Haidar
Date: 2007-07-26 3:11:03 AM
Thanks Josh for your valuable comments!

Title: It doesn't work   
Name: Mr Test
Date: 2007-07-25 4:13:44 PM
This event fires when users goes to another page.
For example, if the current page has a link to another page, when user clicks that link, with the implementation from this article, he loses his current session.
Title: Very Helpful   
Name: Olasemo Dipo
Date: 2007-07-25 6:12:45 AM
This article was really helpful. Most users find it difficult to use or see the logout button in a web app and usually just close the browser with the close button. It's very annoying you know? then the server has to wait for the session to time out before actually killing the session, imagine hackers out there just waiting to hijack user sessions, although this might be a lil difficult with the ViewState that microsoft has introduced. But all the same the article was really great.
Title: Let's fix this great concept for Bilal   
Name: Josh Stodola
Date: 2007-07-24 11:13:26 AM
Hi Bilal, I am here to help.

This article seemed promising, but unfortunately the javascript chain of events is going to cause undesired results. As already mentioned in the comments, it will fire when the page is unloaded, which will occur every time you leave the page/a postback occurs, etc. The reason it will behave this way is becuase you are handling the unloading of the body tag. With that in mind, it does make perfect sense why it behaves the way it does. As soon as you change the page, the old body goes away, and a new body is loaded.

With that in mind, how about handling the unload of the WINDOW itself? Here is an example for you, I will leave it up to you to test it:

window.onunload = function() {
alert("Killing the session on the server!!");

Hope this helps, my friend.

Best regards...
Title: Hi   
Name: Anil
Date: 2007-07-24 9:24:40 AM
I tried implementing
but javascript function is not fired when i close my browser
will this work for IE 7
Title: onunload Fires Every Time You Leave a Page   
Name: Sumo
Date: 2007-07-24 9:19:02 AM
Unfortunately, the code in this article will not work. The onunload event fires every time you leave a page, so you'll be abandoning the session all the time.

I really don't think there is a single solid solution to prevent issues with lingering sessions. It's the nature of the Web beast. The only real solution is to set absolute expiry on sessions, but practically, that doesn't make sense in most situations. It's a balance between security of the session (preventing replay) and user experience (not logging them out automatically every 5 minutes).
Title: AbandonSession() execute prob   
Name: Nimesh Panchal
Date: 2007-07-24 8:56:39 AM
I write AbandonSession() in code file. but [WebMethod] is not supported. Its giving error.

and I put enablePagemethods = "true" still methods r not displaying at aspx page

so, wht to do for execute this methods?
Title: WebMethod   
Name: M.S.
Date: 2007-07-24 7:57:04 AM
The WebMethod attribute is found in the System.Web.Services namespace. Just add it to the top of your public static method to be called.
Title: Another Solution   
Name: Deepak Davesar
Date: 2007-07-24 6:27:58 AM
Hi All,
Another option for this case is that you use a keep alive functionality in your web application. after implementing keep alive, u can keep your session expire time to a short interval, say 1 or 2 mins. through this u can check for the session after every 1 or 2 mins and abandon it accordingly
Title: AJAX   
Name: Mark Smith
Date: 2007-07-24 4:52:32 AM
"The answer was always, the browser will only fire a client side event and the server side cannot be notified when the page is closed."

The answer is still the same regardless of whether we have "new" AJAX methods in ASP.NET. AJAX is only javascript (and has therefore been around a long, long time) so the concept of notifying the server when the client closes still remains the same.

The problem is that there are multiple scenario's when no matter what you do, the server will not know that the client has "left" your website. Some of these are:

1) The user has javascript disabled
2) The user's browser doesn't support javascript
3) The user kills the browser process
4) The user turns off their machine or has a power cut

So, not matter what "solution" you use there will always be times when your functionality doesn't work. Bearing this in mind, you have two options:

1) Create a solution that will work in some, but not all, cases.
2) Work around this limitation and don't create your site that relies on something happening in the future session life-cycle.

I much prefer option #2 which is why I recommend it and why you always hear the same answer (as in your original quote above) in the forums.
Title: event problem   
Name: overthetop
Date: 2007-07-24 4:09:26 AM
Yes...this is really an issue...then only always working solution for me is to make the session lifetime 1 min :)...any better ideas?
Title: nitin   
Name: nitin khadloya
Date: 2007-07-18 7:58:05 AM
nice articles it is useful for fresher
Title: webmethod   
Name: Fosef
Date: 2007-06-25 6:28:10 PM
"On the server side, all that you have to do is define the AbandonSession method and add to it the WebMethod attribute."

What is this webmethod attribute you speak of?
Title: click   
Name: selvi
Date: 2007-06-20 4:31:45 AM
hw we close the application using button click
Title: restricting multiple access of users through script manager proxy   
Name: Bhanusree
Date: 2007-06-15 7:39:21 AM
I wanted abandon the session from master page through script manager proxy can any one help
Title: RE:   
Name: AzamSharp
Date: 2007-06-07 5:25:44 PM

One proposed solution is to use the mouse pointer to locate the window close button "X". Off course this will be purely based on the mouse movement but then you should also consider the chances of user resizing the window and then closing it. So, basically what is required is to get the mouse coordinates based on the openned browser window.
Title: Re:   
Name: Bilal Haidar [MVP]
Date: 2007-06-07 3:03:06 PM
Well that is an issue then!
Any proposed solution or workaround?

Title: onUnLoad is fired on Refresh and Postbacks   
Name: AzamSharp
Date: 2007-06-07 10:44:40 AM
Hi Bilal,

The problem with onunload is that it will be fired even if you refresh the page or fire an ASP.NET postback event from any server side button.

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2024  |  Page Processed at 2024-04-23 12:57:30 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search