Friendly Session Timeouts, the JavaScript Way

A client recently asked me if there was any way to notify visitors to their Web site that their session was about to expire. Fortunately, there’s an easy way to do this using JavaScript.

First, add the following code block to your standard JavaScript include file. (You are using an included file for your JavaScripts, aren’t you?) Essentially, you want the following piece of JavaScript code to be available on each page:

function ShowTimeoutWarning ()
    window.alert( "You will be automatically logged out in five minutes unless you do something!" );

That little function does nothing more than show a popup message to the user. The text of the message (and the five minutes) duration is arbitrary; you can make them whatever you want.

How will we invoke the popup? By using a simple JavaScript function called setTimeout. Pass two parameters to this function: the name of another JavaScript function to call, and the amount of time to wait (in milliseconds) before calling that function. I add the following line into the HTML <HEAD> section within a <SCRIPT> tag.

setTimeout( 'ShowTimeoutWarning();', 900000 );

90,000 milliseconds is 15 minutes (15 minutes * 60 seconds per minute * 1000 milliseconds per second), so in 15 minutes the ShowTimeoutWarning() function will be called automatically. Of course, if the user unloads this Web page (by going to another Web page), the timer disappears.

That 15 minute threshold for the timer was based on five minutes less than the 20 minute session timeout in the Web application.

But what if your Web site (like my client’s Web site) had different session timeouts for different users? You can use a little in-line .Net code to dynamically calculate the timeout period. Here’s how I did it for my client — by adding the following lines within a <SCRIPT> tag:

if ( HttpContext.Current.User.IsInRole( "User" ) )
    Response.Write( "setTimeout('ShowTimeoutWarning();', " +
        ( ( Session.Timeout - 5 ) * 60000 ).ToString() + " );" );

Notice how I calculated the timeout dynamically by using the Session object’s Timeout property. Session.Timeout is stored in minutes, so subtract your announcement time (5 minutes) from that number, then multiply by 60,000 (milliseconds per minute) to get your user-customized timeout alert.