Tuesday 7 February 2017

How to clear/kill session when browser closed

In this Article I am explain how to clear/kill all session when closed the browser or tab.
We need to know how to detect the browser close event and clear the session.It does that by sending a Jquery ajax call when the browser is closed. 
Here for clear session, I am using WebService.

Designer Source Code :

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title>ClearSession</title> 
    <script src="https://code.jquery.com/jquery-3.1.1.min.js" ></script>
    <script type="text/javascript"> 
        $(document).ready(function () { 
            window.addEventListener('beforeunload', recordeCloseTime);            
        }); 
         
        function recordeCloseTime() 
        { 
            $.ajax({ type: "POST", 
              url: "ServiceToClearSession.asmx/ClearAllSession",
            });              
        } 
         
    </script> 
</head>     
<body> 
    <form id="DefaultForm" runat="server"> 
    <div> 
    </div> 
    </form> 
</body> 
</html>


Web Service:

public class ServiceToClearSession : System.Web.Services.WebService
{
    public ServiceToClearSession()
    {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod(EnableSession = true)]
    public void ClearAllSession()
    {
        HttpContext.Current.Session.Abandon();
        HttpContext.Current.Session.Clear();
    }
}

We should need to add this code to Master Page. When we want to clear session in all pages.