How to capture logoff time when user closes browser?
How to end user session when browser closed?
These are some of the frequently asked questions in asp.net forums.
In this post I'll show you how to do this when you're building an ASP.NET web application.
Before we start, one fact:
There is no full-proof technique to catch the browser close event for 100% of time. The trouble lies in the stateless nature of HTTP. The Web server is out of the picture as soon as it finishes sending the page content to the client. After that, all you can rely on is a client side script. Unfortunately, there is no reliable client side event for browser close.
The first thing you need to do is create the web service. I've added web service and named it AsynchronousSave.asmx.
Make this web service accessible from Script, by setting class qualified with the ScriptServiceAttribute attribute...
Add a method (SaveLogOffTime) marked with [WebMethod] attribute. This method simply accepts UserId as a string variable and writes that value and logoff time to text file. But you can pass as many variables as required. You can then use this information for many purposes.
To end user session, you can just call Session.Abandon() in the above web method.
To enable web service to be called from page’s client side code, add script manager to page. Here i am adding to SessionTest.aspx page
When the user closes the browser, onbeforeunload event fires on the client side. Our final step is adding a java script function to that event, which makes web service calls. The code is simple but effective
HTML:( SessionTest.aspx )
C#:( SessionTest.aspx.cs )
That’s’ it. Run the application and after browser close, open the text file to see the log off time.
The above code works well in IE 7/8. If you have any questions, leave a comment.