Monday, March 7, 2011

End Session memory When Browser Closed

There is no full-proof technique, but here is some probable solutions ...

When a user closes the browser, the session doesn't literally expire for a default time of 20 minutes. When the session expires the OnEnd event fires. You can code against this in the global.asax file like so ...


Sub Session_OnEnd()
        Dim conn As New SqlConnection(CONNECT_STRING)
        Dim cmd As New SqlCommand( _
            "insert into _DummyTbl (Text) values ('GLOBAL')", conn)

        conn.Open()
        cmd.ExecuteNonQuery()
        conn.Close()
    End Sub
Now if you call the Session.Abandon method the OnEnd event will fire immediately. (NOT quite though, because I noticed that it took up to a few minutes at certain times for a record to appear into the database, but this is the best we are going to get.) Now we need some way to call the Session.Abandon method when a user closes their browser. This trick wont work in all web browsers, but you can tap into the onunload() event like so ... TESTA.ASPX
<body onunload="window.location.href='TestB.aspx';">
...
When the user closes the browser window at TestA.aspx, they are redirected to TestB.aspx ... TESTB.ASPX
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
   Call MyBase.OnLoad(e)

   ' End The Session
   Session.Abandon()

   ' Build A JavaScript String That Will Close This Web Browser Window
   Dim s As String = ""
   s &= "<script language=""javascript"">"
   s &= "window.close();"
   s &= "</script>"
   
   ' Add The JavaScript To The HTML Stream
   Page.RegisterClientScriptBlock("close", s)
End Sub


On page load event of TestB.aspx, the code abandons the session then closes the browser immediately. The user never sees this page. In fact to the user, it looks like they closed TestA.aspx.

This javascript technique speeds up the process of killing the session and calling Session_OnEnd, but is not supported on all browsers. For older browsers, the application is just gonna have to suffer the 20 minute session timeout period.
I hope the above information will be helpful. If you have any issues or concerns, please let me know. It's my pleasure to be of assistance

No comments:

Post a Comment