Thursday, December 22

Session End on Browser Close or Tab Close or Moving out of the site

I have seen lots of post in the forum asking about kill session on close of browser or tab or moving out of the site.

We can kill session on any of the following case mentioned above using Ajax Callback with Javascript.
Here are the steps to follow:

Step 1: Add ScriptManager in the aspx page
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
Step 2: Add onuload in body tag which will call BrowserClose method in Javascript.
<body onunload="BrowserClose()">
Step 3: Now add javascript method of BrowserClose which will call KillSession method of code behind
<script language="javascript" type="text/javascript">
function BrowserClose()
{
   PageMethods.KillSession();
}

<script>
Step 4: In code behind file, KillSession method will contain the Session.Abandon which will abandon the session.
KillSession method has to be signatured with WebMethod.
Make the KillSession method static
[System.Web.Services.WebMethod()]
public static void KillSession()
{

   HttpContext.Current.Session.Abandon();
}

Step 5 : The code which needs to be executed on should be placed in Session_End method of Global.asax.cs
protected void Session_End(object sender, EventArgs e)
{
   //Code to execute on Session End

}
Live Demo Like us if you find this post useful. Thanks! 
Shibashish mohanty
Download Code 

1 comment:

  1. In body onunload="BrowserClose()" means browser back button also or any navigation link also... so it is hard to adjust in master form. what you say about it?

    ReplyDelete

Please don't spam, spam comments is not allowed here.

.

ShibashishMnty
shibashish mohanty