views:

32

answers:

1

I want to clear the session on Page unload.

Here is a condition :

  • If user goes from Page A to Page B of the same site session must not get cleared.
  • If user close the browser window or Tab(close the site),session must gets cleared.

I have tried using AJAX PageMethod to call server-side procedure to remove session from client side script.But the procedure is not getting hit,I have checked it using Breakpoint.

server side procedure is in master.cs file

I will appreciate your help.

Here is code in site.master

<body onunload="HandleClose();">
    <script type="text/javascript">
        function HandleClose()
        {            
            PageMethods.AbandonSessions();
        }

and here is a code in master.cs :

[System.Web.Services.WebMethod]
        public static void AbandonSessions()
        {

            HttpContext.Current.Session.Abandon();

        }
A: 

You need to register a javascript event for page unload and send an AJAX request to clear the session. This event will be trigerred when the user closes the browser window or tab. Here's an example page:

<html> 
<head> 
<script type="text/javascript"> 
function clearSession() {
    // TODO: Send an AJAX call to a server side script 
    // that will clear the session
}
</script> 

</head> 
<body onunload="clearSession();"> 

</body> 
</html>
Darin Dimitrov
I did the same,but the server procedure not getting hit.
Jignesh
Could you try sending the request with jQuery and enable synchronous request?
Darin Dimitrov
jQuery will do the same thing.
Jignesh
Not the same if you set the `async` parameter to false.
Darin Dimitrov
I will try,thanks.
Jignesh