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.
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.
The HandleClose function is placed within the Head section of the page.
alert("Killing the session on the server!!");
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.
public static void AbandonSession()
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!