Click here to Skip to main content
15,884,099 members
Articles / Web Development / ASP.NET
Tip/Trick

Execute server side code on close of a browser

Rate me:
Please Sign up or sign in to vote.
4.00/5 (8 votes)
26 Jun 2010CPOL 42.9K   10   5
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)


Written By
Technical Lead Kale Consultants Ltd.
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
PraiseIt worked well Pin
poonam39316-Mar-17 6:17
poonam39316-Mar-17 6:17 
QuestionHow to implement this when I am using master page Pin
srmohanr27-May-14 0:52
srmohanr27-May-14 0:52 
GeneralMay be Dangerous Pin
TheyCallMeMrJames25-Jun-10 6:41
TheyCallMeMrJames25-Jun-10 6:41 
GeneralRe: May be Dangerous Pin
Anuj Khadloya27-Jun-10 18:36
Anuj Khadloya27-Jun-10 18:36 
GeneralThis will only work in IE Pin
sob25-Jun-10 2:46
sob25-Jun-10 2:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.