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();">
2.

function bodyUnload()
{
var xhr = GetXHR();
xhr.open("GET","Abondon.aspx",true);
xhr.send();
}
function GetXHR()
{
var xhr = null;
if(window.XMLHttpRequest)
{
//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();">

3.

[WebMethod]
public static void AbandonSession()
{
HttpContext.Current.Session.Abandon();
}

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.