Alert on Session Timeout in ASP.NetTags:, web — 10th of October 2009


You must have seen this before, you left your online banking open for a while and then suddenly a pop up comes up telling you, "Hey your session is about to run out!"
This message helps the user keep their session alive so that they do not get logged out.


The session timeout can be changed in your web config
The value 60 here represents 60 minutes.
So after 60 minutes inactivity from the user, the session will expire. We can't just send a message from the server on that event to the user but we can make an assumption of when that timeout might happen on the client.
We will assume that the timer resets every time the user
  1. Goes to another page
  2. Makes an Ajax Postback
  3. Makes a Callback
And with that note I give you the following script
var timeOut = 60 * 60 * 1000; // minutes * seconds * millseconds
var timer = null;
var reset = function()
   if (timer) clearTimeout(timer);
   timer = setTimeout(function() { window.onbeforeunload=null; window.location = "/TimeOut.aspx"; }, timeOut);

if (Sys) Sys.Application.add_load(reset); // If Ajax Client Library available, apply reset on postback
var orig = WebForm_DoCallback; /// Hijack the callback function to allow us to know when a callback is made, callbacks reset the session timer!
WebForm_DoCallback = function() {reset(); orig.apply(this, arguments); };
After 60 minutes of inactivity, the script will redirect the user to the "TimeOut.aspx" page to let them know that their session has expired.
But it would be lot nicer to let the user keep their session alive, so just set the timer to something less then the actual timeout time such as 50 minutes and then give the user the option to keep their session alive. And if the user chooses to do so just do a Callback/Postback to reset the timeout.