views:

769

answers:

1

I've got a Classic ASP application that relies on session; if the user leaves a screen idle and then runs a form post or other operation, I'd like to know whether the session has expired.

Currently I'm checking session in each page to see if it's timed out, but is there a better, dynamic, JavaScripty approach that will do what banks do and time out sessions with a notification and redirect to login?

+1  A: 

During your page's onload event, start a timer, and then redirect the page after N seconds.

  • For the timer, use the window.setTimeout function.
  • For the redirect, set the value of window.location.

Reusable Example:

<head>
<script type="text/javascript">
<!--
 function redirect(url) {
   window.location = url;
 }
 function beginSessionTimer() {
   // 30000ms = 30s
   window.setTimeout(redirect, 30000, 
                     "http://www.yoursite.com/login.asp?session=clear");
 }
//-->
</script>
</head>
<body onload='beginSessionTimer();'>
</body>

Quick-n-dirty Example w/ an inline function:

<body onload='window.setTimeout(function(){
window.location="http://www.yoursite.com/login.asp?session=clear";}, 
30000);'>

Note that if your page performs any AJAX calls, that keeps the session alive, so you'll want to reset the timer using the clearTimeout method (combined w/ a new call to setTimeout). For details on clearTimeout, click here for excellent documentation from Mozilla.)

David