First of all, create a new ASP.NET page in your favorite IDE
and add an instance of the ScriptManager to it. Make sure you configure the
ScriptManager to enable Page Methods.
Listing 1
<asp:scriptmanager id="ScriptManager1" runat="server" enablepagemethods="true" />
Next, we will subscribe to the unload event of the body tag
of the ASP.NET page and assign a callback method to be called when this event
fires.
Listing 2
<body onunload="HandleClose()">
The HandleClose function is placed within the Head section
of the page.
Listing 3
<script language="javascript" type="text/javascript">
//<![CDATA[
function HandleClose()
{
alert("Killing the session on the server!!");
PageMethods.AbandonSession();
}
//]]>
</script>
As you can see, the function shows an alert message box
informing the user that the session will be killed on the server side. Then it
makes a call to the AbandonSession server side method that is a Script-enabled
method. For more information about the Page Methods in AJAX 1.0, make sure you
check the AJAX
documentation.
On the server side, all that you have to do is define the
AbandonSession method and add to it the WebMethod attribute.
Listing 4
[WebMethod]
public static void AbandonSession()
{
HttpContext.Current.Session.Abandon();
}
The above line of code makes sure that the session is now
cleared and causes the Session_End event, which is defined inside the
Global.asax to fire.
Inside the Global.asax you can place any code you want to
execute when the session ends.
That is all what you have to do to run any server side code
when the browser is closed by the user!
Hope this snippet is helpful and that you have enjoyed it!!