Home » Asp.net

End Session When Browser Closed

Hi, I am quite new to asp.net and web tech.

I created a site something like bookstore, and now I am creating shopping cart for it.

I used datatable which i store in session for store shopping cart data.

The problem is that, I put some items in cart and then close the browser immediately and next time when i open it the data are stills there unless the session is expire.
I like to abandon the session when user close the browser.
Is there any solution for it and is this a good way to create my shopping cart?

Thx in advance.



17 Answers Found


Answer 1

Why don't you empty all sessions on Page Load? 


Answer 2

I don't think emptying all sessions on page Load will work. Cos then whenever the user posts back to the page, the session will be emptied.

Try emptying all the session in Session_Start of the global.asax. That might work. Not 100% sure though.


Answer 3

Why don't you empty all sessions on Page Load? 



I tried that but its clear everytime page is refresh, It doesn't work.


Answer 4

I have a question. Where are you storing the contents of the shopping cart ? In a session object or the Application Data Cache ?


Answer 5


 Sorry, you already stated that you are saving it in a session object.

 It is very weird that your shopping cart info is still displayed after the browser is closed and reopened. It should be reset on closing the browser

 There is one thing you could try, which is storing the SessionID in the url. In the web.config file put the following segment.




 I hope this helps.



Answer 6

HI, mgkoko: 

There is no full-proof technique, but here is some probable solutions ...

When a user closes the browser, the session doesn't literally expire for a default time of 20 minutes. When the session expires the OnEnd event fires. You can code against this in the global.asax file like so ...

    Sub Session_OnEnd()
        Dim conn As New SqlConnection(CONNECT_STRING)
        Dim cmd As New SqlCommand( _
            "insert into _DummyTbl (Text) values ('GLOBAL')", conn)

    End Sub

Now if you call the Session.Abandon method the OnEnd event will fire immediately. (NOT quite though, because I noticed that it took up to a few minutes at certain times for a record to appear into the database, but this is the best we are going to get.) Now we need some way to call the Session.Abandon method when a user closes their browser. This trick wont work in all web browsers, but you can tap into the onunload() event like so ... TESTA.ASPX

<body onunload="window.location.href='TestB.aspx';">

When the user closes the browser window at TestA.aspx, they are redirected to TestB.aspx ... TESTB.ASPX

Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
   Call MyBase.OnLoad(e)

   ' End The Session

   ' Build A JavaScript String That Will Close This Web Browser Window
   Dim s As String = ""
   s &= "<script language=""javascript"">"
   s &= "window.close();"
   s &= "</script>"
   ' Add The JavaScript To The HTML Stream
   Page.RegisterClientScriptBlock("close", s)
End Sub

On page load event of TestB.aspx, the code abandons the session then closes the browser immediately. The user never sees this page. In fact to the user, it looks like they closed TestA.aspx.

This javascript technique speeds up the process of killing the session and calling Session_OnEnd, but is not supported on all browsers. For older browsers, the application is just gonna have to suffer the 20 minute session timeout period.

I hope the above information will be helpful. If you have any issues or concerns, please let me know. It's my pleasure to be of assistance


Answer 7

Thank you all, my mistake, I've got it.

Answer 8

what was the mistake and what was the solution?


Answer 9


Sorry, Tarique_s I should have tell you,

Actually it cleans all the session when you close the whole browser.

The problem seems that When I open multiple tabs in one browser and my website is running on one of those tab.

I close my website tab and reopen it in new tab, the session is still there.

but If I close the whole explorer, and reopen it in new browser it clear the session.

I didn't write any code in Global.asax. 

it's funny, I don't know why is that. maybe I don't understand well enough in session and application.

sorry my eng is a bit poor, and you might not quite understand,

if you have further question please let me know


best regard




Answer 10

There is no way to detect the Session_End on browser close .  You can do it by adding some extra logic in Page_Load like  If (!IsPostBack){ }. but make sure this page is not being called from any other page within the site. If this is the case you can use the query string to detect from where the page is coming from.


Answer 11

Yes there is

Session_End event get fired when you close the browser. at least it does for me :)


Answer 12

Session_end does *not* get fired when you close the browser. Session_End gets fired when the Session Timeout has expired. It happens on the server, and is completely independent of whether the user's browser is open or closed. Unless you use one of the mostly unreliable hacks such as a call created by onUnload browser dom event, the server has no idea whether the browser is open or closed.


Answer 13

I found this article and it was very helpfull

CodeSnip: Handle Browser Close Event on the Server-Side


Answer 14

i hav a similar prob.. i have a flag in my login table which is set to 'Y' when logged in and 'N' when logget out... it works ..with logout link/button ..

but if user closes the browser window i cant update the flag to 'N'...

I HAV CODE IN Global.asax on 'Session_End' like.. 

"Session End") and then


the update statement to update the flag to 'N' ...now when the browser is closed i can only see the Messagebox but the flag is unchanged... that to after a long time the messagebox appears..!!  where and how should i control/edit the session timeout...?

PLZ HELP ME OUT WITH A SOLUTION .. am not familiar with ajax or any other scripting.. plz provide a simple [sample] code.. :)

thanks a lot..in advance..




Answer 15

Hi ,

when user close the browser find the unload event and

put Session("SessionName") = Nothing





Answer 16

This code will clears the session when browser tab is attempted to close.

<body onclick="clicked=true;" onunload="CheckBrowser()"> <script type ="text/javascript" > var clicked = false; var xmlHttp var browser = navigator.appName; function CheckBrowser() { if (clicked == false) { xmlHttp = GetXmlHttpObject(); xmlHttp.open("GET", "SessionEnd.aspx", true); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4) { // alert(xmlhttp.responseText) } } xmlHttp.send(null) if (browser == "Netscape") { window.location=".../SessionEnd.aspx"; alert("Browser Terminated"); openInNewWindow(); } } else { //alert("Redirected"); clicked = false; } } function GetXmlHttpObject() { var xmlHttp = null; try { // Firefox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest(); } catch (e) { //Internet Explorer try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } function openInNewWindow() { // Change "_blank" to something like "newWindow" to load all links in the same new window var newWindow = window.open(".../SessionEnd.aspx"); newWindow.focus(); return false; } </script>

I've added SessionEnd.aspx an extra form just to do session clear process and alert again by popping new tab.

You can remove that part if you dont want redirection.


Answer 17


I am using master page... so there would be only one form tag. i want to handle browser close event and then kill the session. how can i do this?expecting for all browsers , not just IE.

any help would be highly appreciated.




Hi, I am quite new to asp.net and web tech.

I created a site something like bookstore, and now I am creating shopping cart for it.

I used datatable which i store in session for store shopping cart data.

The problem is that, I put some items in cart and then close the browser immediately and next time when i open it the data are stills there unless the session is expire.
I like to abandon the session when user close the browser.
Is there any solution for it and is this a good way to create my shopping cart?

Thx in advance.



Hi I need to kill the session and log the excetions when we try to close the browser without logging out

when we try to close the browser using alt-f4, browser close(X) and right click on browser and close -> this all is done and is working fine.

Now I need to handle the events

1. when we try to close the browser using Task Manager and kill the iexplore.exe.[ I need some event so that I can kill the session and log the event]

2. when we try to close the browser using right click->close from windows task bar [I need some event.clientY so that I can kill the session]

Kindly help me in resolving this Issues




If a session cookie is a cookie without an expiration date, and session cookies expire when the browser is closed, then why are these cookies remaining on my computer? I have cookies on my computer that were created as many as 5 days ago that have"none" as the expiration date. Shouldn't these types of cookies be deleted when I close my browser?  This behavior is present in IE7.  I am not expiriencing it in IE8.  Is there an IE setting to set how long session cookies should be stored? 
I am developing an application that sets a cookie.  When I view the cookie in Windows Explorer the expires attribute is set to 'None'.  I expect that when a user closes their browser, this cookie will delete.  What I see is that even if a user restarts their computer, the cookie is still there.


hi all.

i am beginner to .NET . i developed one mini project in asp.net. 

my problem is when i close the browser after running my application,  only the browser isl closing. but i need to close whole application also. how can i achieve this. it doesnt seems good to click on "stop debugging" every time. 

please help me. Thank you.


Session_End events never fire on my server. This results in an unending accumulation of "logged in guests" on my forum, and, in the chat application I've just developed, a failure to recognise that users are no longer logged in if they don't explicitly log out. Let me eliminate the obvious: I am using "InProc" session mode. In fact my application works perfectly on my development machine, using all the same settings, but on the live server, the Session_End in global.asax never fires, even when I invoke Session.Abandon(). So I'm assuming this has something to do with IIS (7) - but what?



I have a multi-user desktop running Vista Home Premium, with a Windows Home server on the local network, and SyncToy 2.1 to tie it all together.

I would like SyncToy to run at the *end* of each users' session, to copy (echo) any work done during the session over to the server for backup and/or remote access. 

I can use Task Scheduler to automatically run SyncToyCmd with the "-R" "folder pair" command, triggered by Disconnect From User Session.  Works fine... but it runs invisibly, and there's no way at runtime to control which folder pairs are run.

I'd like to give users the ability to choose which pairs to run, so that (for example) the entire photo library isn't scanned every time someone Switches User after reading their mail.

I tried having Task Scheduler just launch SyncToy (non-command-line) at Disconnect, but the SyncToy window doesn't appear before the user's desktop disappears (though the window *is* waiting there on their desktop next time they log in!). 

If I can just get SyncToy in front of them when they disconnect, I think my users are smart enough to run the folder pairs they need, based on what they were doing... but they're not smart enough to always remember to run it manually before they disconnect!

Can anybody suggest a method to automatically get SyncToy to appear for the user, *before* they leave their user session?





I'm wondering if ther's a simple way of achieving the following.

When a new session starts, I create some cookies and session objects from global.asax session start.

If a user logs out, I want to abandon the session - I presume using session.abandon, and i also want to clear the cookies.  They are set to expire after the session ends (no expiry date).  This may be an automatic thing, but I've not tested as yet.

When a user logs back in again I want to recreate those objects - in other words, kick off global.asax again.  Is that what happens or do I need to recreate manually?





How does it reelate Session_End and SessionState in web config?

I have the following setting in web config but the session_end never been invoked after 1 minute elapsed. any ideas?


<sessionState mode="InProc" timeout="1"/> <!-- timeout within 1 minutes -->




I need to handle "session end" event for my web application when user closes his browser. Session is stored in Sql.  Maybe you can provide some ideas hot to do it? 



Can I modify the global.asax in sharepoint.

I want to implement httpModule and global.asax for session start and session end events.

Kindly help.


as you see popfly gadget fits into the picture of my blog, and did not hurt anyone.

however as it looks it is to be discontinued within a few days.

will this alienate people?

POPFLY indeed is not a very looky nomer and i was thinking it could be rebranded.

it is a little like QBASIC.EXE - did simple battery operated calculators vanish with the introduction of complicated mathematics software?
did matches vanish with the introduction of gas lighters?

you know they did not vanish. there might be situations when you either want to use the one or the other gadget!

i do not understand why QBASIC was discontinued. i found it very useful to try out algorithms, and test mathematics formula, and indeed, very quick (virtually instant execution).

with some 100s hours training and more books i oculd do these things in EXCEL, not to mention real visual studio!
but why? QBASIC worked for me, i liked it. i still have a secondary computer with win98SE but it is maybe just switched on once a month (bootup time for WIN98SE on AMD Athlon: 30 seconds!).

i just feel a little alienated about Microsoft abandoning products- of course the new stuff is 10 times better! but maybe I'd like to use both things! can they bring back QBASIC, at least?

my suggestion is indeed to abandon the mashup creator and the homepage creator (which is sort of ____), but to keep the game creator! maybe just rebrand it. it could be useful for some purposes.

maybe there are internal reasons not to continue it, but at least, popfly did not hurt me personally. i just get a little upset about the time i have spent- 30 hours, 50 hours or more! and i am happy that i did not author larger projects. all the work would be lost now!

a warning for the future not to trust remote cloud computing? they just can pull the plug, treat your data as collective propery, and if the like, send it nero and ultimatively stop you from continuing to use or even to access it.

and where is the FTP interface?

i think it would be better publicity if at least the game engine is maintained as it is, and in the near future, rebranded.

to be honest i did not really like most of the graphics design but i would not say the game creator is useless...

Hello everyone,

I am working on a website which uses a common database shared by another 2-3 websites.  Now i am having a requirement that whenever a user clicks a link provided on another website and comes to my website and if the user is already logged in to my website then my website should not ask him to login again it should by pass the login page and show the next page.

Here the problem is i am not able to get the session objects in newly opened browser window even if the user is already logged in to my website in another browser window. I am not sure but i thing IE uses two different processes for two different browser instance and because of that i am not getting the session objects required.

Deos anyone have some idea on my problem.

Note: I can not ask the another website vendor to pass anything as a querystring.


I want my tabs in my browser to have separate sessions. I  was told to use

<sessionState mode="InProc" cookieless="UseUri"></sessionState> in web.config

 but when I read about it here: http://msdn.microsoft.com/en-us/library/h6bb9cz9(v=VS.100).aspx

the text says “When you configure an AJAX-enabled ASP.NET Web site, use only the default value of UseCookies for the cookieless attribute. Settings that use cookies encoded in the URL are not supported by the ASP.NET AJAX client script libraries.”

I’m using Ajax so are there any ideas what I can do about this problem.



I have a button control where I retreive 2 strings with 2 URL like in the code below.

What I wonder how it is possible to do, is how to open up 1 browser window with 2 Session Tabs where 1 Tab is http://www.google.com and the other http://www.yahoo.com

How can this be possible to do from code behind (C#)?

    protected void Button1_Click(object sender, EventArgs e)
		String URL1 = "http://www.google.com";
		String URL2 = "http://www.yahoo.com";

		//How to open up a browser with two session tabs with each URL in each?



Hi guys,

Really confused on this... let me explain the scenario.

i have a application on .net 2.0 .

once user is logged in, various session variables are stored for that users profile information (normal stuff). when user open a browser window and after doing some operation, closes the browser window directly.

and then reopen new window and try to access homepage of same application... he is presented with profile of the user which was logged in before (and widnow was shut down)

is this behaviour normal and common across all IE versions?

this behaviour is not consistent.... sometimes, its showing homepage of old user and sometimes its  showing login page (as if session is invalidated)

is there any way to abandon all session if browser window is closed (apart from capturing browser window close event)

hope i get some replies on this...


Hi All,

I have to design a web browser application in WPF with a session timeout facility. The requirement to provide a session timeout after 1 hours. How can this be achieved? Also i need to implement login based menu access levels in this application. How can i achieve both these?



Hello, everybody!

I have an application with multiple threads, that uses WASAPI for rendering audio. Each thread starts playback. For each thread I create separate SimpleVolume control and set a GUID to Audio Session. But after I close the thread and release all the interfaces, the volume sldebar is still exists in SndVol.

So here is a question. How to close an Audio Session correctly, so the level control of it will disappear from SndVol?




I am running VS2010 Ultimate on 2003 server SP-2. Is there any command or series of commands which we can use to instruct our server to close all previously opened IE windows before executing test cases? I would appreciate your help.





We have 2 BizTalk Server 2009 receive locations extracting data, from an Oracle 10g Enterprise Edition Release - 64bit Database, by calling the same packaged procedure which uses a global temporay table.

The receive locations poll the database every 10 seconds. Intermittently we get the 'error ORA-14450: attempt to access a transactional temp table already in use' which causes the extract to fail continually until we intervene.

At first we thought the cause was the two receive locations competing for the use of the global temporary table as the error always occurs on insert into this temporary table.

However we now thing that the problem is due to a connection failing to disconnect. I say this because this morning the problem was occuring and there were two sessions open from the BizTalk server. One had been open for 21 hrs and was showing that it was doing 'select x from dual', which is not code in our package.

We killed this session and the problem resolved itself.

Any idea of how I can prove that connection issues are the problem and if it is proved, how to overcome them?

Can anyone suggest some way I could try and diagnose what the issue is in the event the unclosed connection is not the issue?



I am using vb.net (Visual Studio 2008 with framework 3.5). I have a server that exposes several services requiring sessions. I am using wsHttpBinding for all. One of my requirements is to allow non-dot net third parties to access these services. When a client connects to a service and then some time later the server goes away, the state of the connection is still reporting "open".

Currently I have implemented a "ping" function on the server. My client calls this function every 5 to 10 seconds and if the server does shutdown, I get alerted with an exception error. This works, but I was wondering if there is a way where I don't have to call my ping function?

I don't want to use a dual connection binding and I was hoping to use the connection state variable? But, I don't know how to get it to update by itself. The client user application could just wait until it goes to invoke a service method, but I was wondering if there was another way.

Thanks in advance!!



<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure