Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Execute server side code on close of a browser

4.00/5 (8 votes)
26 Jun 2010CPOL 43.7K  
This article provides a solution to the age-long question of How do I execute some server side code when my browser is closed?. The answer to this question is AJAX.
To start with create a new asp.net page and add an instance of the ScriptManager to it. Now configure the ScriptManager to enable calling of page methods marked with WebMethod attribute.


<asp:scriptmanager id="Scriptmanager1" runat="server" enablepagemethods="true" xmlns:asp="#unknown"></asp:scriptmanager>


The next step is to create a web method on the server. The method needs to be marked with the WebMethod attributte.

[WebMethod]
public static void BrowserCloseMethod()
{
    // Write Custom Code
    HttpContext.Current.Session.Abandon();
}   


Finally call the server method on closing the client browser window. Add a javascript method and call this method when the unload event for body of the browser is called.

<script language="javascript" type="text/javascript">
function Browser_Close() 
{
	PageMethods.BrowserCloseMethod();
}
</script>

<body onunload="Browser_Close()"></body>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)