The one problem all web developers face is how to make Session Timeouts more user-friendly.
What do you do when a user decides to go do something else and doesn't finish what they are doing on your site? You know that there are Web Sessions and possibly even a Database Session that needs to be maintained. So how do you make that friendly to your user?
A good answer would be to prompt the user before timeout and give them the option to extend the Session.
If the user doesn't see or otherwise react to this prompt, you should simply log the user out and return to some sort of "home" or otherise "landing" page to make sure they don't come back only to find nothing works.
The following code can be tweaked to do just that.
To start off, we need to seed the Session Timeout. In this case we are converting to seconds so however many minutes you have your Session Timeout set to, we will multiply that by 60 to break down the minutes.
But we can't just pop up a dialog when the user hits the timeout mark. So, we will handle that by setting up a "countdown" interval to watch for.
In the case of this demo, we will use 120 seconds or 2 minutes. You may wish to go with something shorter and can easily change that by seting countdownSeconds
to whatever you want.
From the start we need to set sessionTimeoutSeconds
to match the number of seconds that equals our Session Timeout. I would suggest doing this from the server-side as you can grab that value from what was set on the server but in the event you simply want to hard-code you can just set the value for sessionTimeoutSeconds
and you will be good to go.
NOTE: In ASP.Net you can set the SessionState
"timeout" in the Web.config
and use that.
When the timeout period is met (Session Timeout - Countdown Time) we should display some sort of prompt.
As I typically use Bootstrap, I went with the Bootbox.js plugin but you can easily change this out to jQuery UI or whatever mechanism you want.
When and if the user opts to extend the Session we need a URL to call. For my implementation, I need to also maintain a Security Session with my Database so I am using a quick AJAX call that makes an inocuous Database call to extend the Session. You may instead opt to load an image from the server into a variable. This will work just as well.
An example of using an image would be something like this:
var img = new Image(1, 1);
img.src = extendSessionUrl;
You will definitely want to modify the refreshSession
method to suit your needs.
Along with a method for refreshing the Session, you will also need to provide a URL for where to go if the user opts to Log Out or the Session times out.
var extendSessionUrl = '/Account/ExtendSession',
var expireSessionUrl = '/Account/LogOff';
This code was borrowed by and inspired by the following example:
https://fairwaytech.com/2012/01/handling-session-timeout-gracefully