Home|Sitemap|Contact

How can you warn a user that his ASP session is about to timeout?

5 minute session time out with warning if 2 minutes or less remain and auto refresh if the user confirms.


<%
Session.Timeout = 5 ' set to 5 minutes for example
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">

<head>
<title>Client Side Session Timeout Check</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="author" content="Roderick Divilbiss">
<meta name="copyright" content="© 2005, 2006 Roderick Divilbiss">
<script type="text/javascript">
<!--
// make match your session.timeout from ASP
var timeout=300000; // 5 minutes * 60 seconds * 1000 milliseconds
var warning=120000; // 2 minute warning
var dt = new Date();
var start=dt.getTime();
var warned=false;

function checkTime() {
  var d=new Date();
  var now=d.getTime();
  var timeSpent=(now-start);

  var secondsLeft=((timeout-timeSpent)/1000);
  var minutesLeft=Math.floor(secondsLeft/60);
  secondsLeft=Math.floor(secondsLeft-(minutesLeft*60));
  var refresh;
  if (timeSpent > timeout) {
    document.location='sessionExpired.asp';
  }
  if (timeSpent > (timeout-warning)) {
    refresh=confirm('Your session is about to expire.\nRefresh the page.\nYou have in '+minutesLeft+' minutes: '+secondsLeft+' seconds remaining.\n\nClick OK to refresh your session or click Cancel to ignore.');
    warned=true;
    if (refresh)
      top.location=document.location;
  } else
    document.getElementById('sessionStatus').innerHTML='You have in '+minutesLeft+' minutes: '+secondsLeft+' seconds remaining.';

    setTimeout('checkTime()',1000); 
}
//-->
</script>
</head>

<body onload="checkTime();">
<span id="sessionStatus"></span></div>
</body>

</html>