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.

6 comments:

  1. In this approach which you describe for logout here one problem will appear .When user click back button from browser then logout page will call automatically in this case session will lost so you can not immplement this method due to this problem .

    ReplyDelete
  2. Interesting point highlighted by Farrukh, I will check this problem and see that what can be possible resolution for this problem.

    ReplyDelete
  3. Excellent post I must say.. Simple but yet interesting and engaging.. Keep up the awesome work!

    cialis

    ReplyDelete
  4. A great article indeed and a very detailed, realistic and superb analysis of the current and past scenarios.


    Web Hosting | Web Design

    ReplyDelete