Automatically refresh your user's Session behind the scenes using jQuery and Asp.Net

Incredibly simple script will keep your user's Session alive without any worries

Now this is something that may or may not be useful to a lot of people, depending on you situation, you may want the user to elect to refresh their Session or not (like banks usually do); but this is for applications that may have a lot of idle time and users are annoyed with their Sessions dying... considering most users don't know what a Session is, but they know that the application stops working correctly.

It uses jQuery and is incredibly simple, just a few lines of code, and no screen flicker or any annoyance to the user at all; ignorance is bliss. First I include the following in the code-behind in any page you need to keep refreshed (works on masterpages as well):

protected int timeout;
protected void Page_Load(object sender, EventArgs e)
    // one minute prior to timeout (milliseconds)
    timeout = (Session.Timeout * 60000) - 60000; 

Then add this jQuery to your script:

aspx or master
var to;
$().ready(function() {
  to = setTimeout("TimedOut()", <%= timeout %> );
function TimedOut() {
  $.post( "refresh_session.aspx", null,
    function(data) { 
      if(data == "success") {
        to = setTimeout("TimedOut()", <%= timeout %>);
      else { $("#timeout").slideDown('fast'); }

Notice that the jQuery calls the $.post() function, where it calls the page refresh_session.aspx. That page does only one thing: Response.Write("success"); so if data comes back and it does not equal 'success' (something went wrong) it then stops the cycle of checking for timeout and shows my 'timeout' div that tells the user it is not a current session.

infinitely refreshing session...

Yup, it is just that easy. The code-behind gets the Session.Timeout, and subtracts one minute from it, this is when the refresh will be triggered. Inside the script, the setTimeout() call will then wait that amount of time and use the jQuery $.post() to hit the page in in turn refresh the Session; once that is done, it starts the cycle over again, so it should repeat on into infinite. And since this is all done via a jQuery ajax call, there is no evidence to the user this is even happening, no flicker or popup, nothing.

Comments (1) -

  • This is just what I am looking for, thanks. I need to keep a short-lived session on some of my sites, especially so that when a window closes, the session expires. However, the session needs to stay alive long enough for the user to complete their task, which could be 15 minutes before they submit one form in particular. This is gonna help me with that.

    It would also be nice to see an example of forcing a Session.Abandon if the window is closed, to complete my set of client-side session management scripts.

Pingbacks and trackbacks (3)+

Comments are closed