Click here to Skip to main content
15,499,289 members
Articles / Web Development / ASP.NET
Tip/Trick
Posted 24 Jun 2010

Stats

40.5K views
10 bookmarked

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
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 7:17
Memberpoonam39316-Mar-17 7:17 
QuestionHow to implement this when I am using master page Pin
srmohanr27-May-14 1:52
Membersrmohanr27-May-14 1:52 
GeneralMay be Dangerous Pin
TheyCallMeMrJames25-Jun-10 7:41
MemberTheyCallMeMrJames25-Jun-10 7:41 
GeneralRe: May be Dangerous Pin
Anuj Khadloya27-Jun-10 19:36
MemberAnuj Khadloya27-Jun-10 19:36 
A user need not to be logged out of the application using this trick. The article shows the way to execute a server side code on the close of a browser or any other javascript event. It is possible to log out the user from the application, but need not necessarily be done. One possible use I can think on the fly could be to calculate the amount of time the user spent on a page.

Cheers!!
GeneralThis will only work in IE Pin
sob25-Jun-10 3:46
Membersob25-Jun-10 3: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.