How to end session when browser is closed

In high traffic sites sessions are very costly and they use lots of server's memory. Generally session timeout is 20 min (by default) and even if user closes the browser. Values in session still exist until session get expired after timeout. We can save lots of server memory if we destroy session as user closes the browser.

Here is how you can do it:-

1)First create a page AutoLogOut.aspx and in Page_Load event write this code:-
protected void Page_Load(object sender, EventArgs e)
{
    Session.Abandon();
}

2- Then add following javascript code in your page or Master Page:-
<script type="text/javascript">
     var clicked = false;
    function CheckBrowser()
    {
        if (clicked == false)
        {
            //Browser closed
        }
        else
        {
            //redirected 
            clicked = false;
        }
    }
 
    function bodyUnload()
    {
        if (clicked == false)//browser is closed
        {
            var request = GetRequest();
            
            request.open("GET""AutoLogOut.aspx"true);
            request.send();
        }
    }
 
    function GetRequest()
    {
        var request = null;
        if (window.XMLHttpRequest)
        {
            //incase of IE7,FF, Opera and Safari browser
            request = new XMLHttpRequest();
        }
        else
        {
            //for old browser like IE 6.x and IE 5.x
            request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
        }
        return request;
    } 

3- Finally on your body tag add these event handlers:-
<body onunload="bodyUnload();" onclick ="clicked=true;>

Now when user closes the browser, it will close session on server. However I just like to highlight that this solution might not work 100% time as there are chances that when user close the browser, he is not connected to internet.

Feel free to share your comments on my post.