Monday, 27 July 2009

How to end the session when the browser is closed?

Approach 1: using window object
1. <body onunload="window.location.href='abandon.asp';">
2. Add abondon.asp page and put only this there: <% Session.Abondon %>

There is a problem with this method that if the user changes the url, it navigates back to the abondon.asp page.

Approach 2: using AJAX
1. <body onunload="bodyUnload();">

function bodyUnload()
var xhr = GetXHR();"GET","Abondon.aspx",true);
function GetXHR()
var xhr = null;
//this object is standard in IE7, FF, Opera, Safari
xhr=new XMLHttpRequest();
else {
//IE 6.x and IE 5.x
xhr=new ActiveXObject('MSXML2.XMLHTTP.3.0');
return xhr;

3. Add abondon.asp page and put only this there: <% Session.Abondon %>

Approach 3: using Page Methods

1. <asp:scriptmanager id="ScriptManager1" runat="server" enablepagemethods="true" />

2. <body onunload="PageMethods.AbandonSession();">


public static void AbandonSession()

1 comment:

Mirza Ateeq said...

Hi Pooya,

Its nice and straight forward post. However i m not able to understand approach#3. Can you please provide more details like,
where this method AbandonSession() is written ??
and what is [WebMethod] ??

thanks in advance.