| |
Sign In
I put this function in a 'Util' class so pages can easily turn on the 'Keep Alive' functionality, simply call Util.KeepAlive(this);
public static void KeepAlive(Page p){ p.ClientScript.RegisterClientScriptInclude("KeepAlive", "/KeepAlive.js");}
[WebMethod]public void Ping(){ HttpContext.Current.Response.Write("OK"); HttpContext.Current.Response.End(); // this makes the result easier to parse than an XML web service message}
var timerID = 0; // used to track the timer functionvar interval = 1000*60*15; // 15 minsvar KeepAliveUrl = '/Ping.asmx/Ping'; // replace your web service address herevar xmlhttpKeepAlive;function AutoSaveSubmit(){ if(confirm('15 minutes of idle time has passed, do you want to keep your session active?')) InvokeWebService();}function InvokeWebService() { if (window.XMLHttpRequest) { xmlhttpKeepAlive=new XMLHttpRequest(); xmlhttpKeepAlive.onreadystatechange = xmlhttpChangeKeepAlive; xmlhttpKeepAlive.open('GET',KeepAliveUrl + '?T=' + timerID,true); xmlhttpKeepAlive.send(null); } // code for IE else if (window.ActiveXObject) { xmlhttpKeepAlive=new ActiveXObject('Microsoft.XMLHTTP') if (xmlhttp) { xmlhttpKeepAlive.onreadystatechange = xmlhttpChangeKeepAlive; xmlhttpKeepAlive.open('GET', KeepAliveUrl + '?T=' + timerID, true); xmlhttpKeepAlive.send(); } } return false;}function xmlhttpChangeKeepAlive(){ var text; if (xmlhttpKeepAlive.readyState == 4) { text = xmlhttpKeepAlive.responseText; if (xmlhttpKeepAlive.status==200) // OK { if(text == 'OK') // reset the timer timerID = setTimeout('AutoSaveSubmit()', interval); else alert('Your session has already expired.\nIf you have any information on this page you will lose it if you try to save this page now. You have 2 options to avoid losing the information on this screen.\n\nOption 1: open a new internet window and log in again to the web site, then close that window and go back to this window, at which point you will have a new session and you will be able to save the information.\n\nOption 2: Copy all the text you have typed on this page and paste it into another program (such as Word or Notepad), then log in to the web site again (click the home page) and come back to this page, and paste in the text again.\n\nTo prevent this happening in the future, click OK on the 15 minute reminder box each time it appears, this will keep your session active. If you do not answer the reminder within 10 minutes the session may expire.'); } else alert('Error: ' + xmlhttpKeepAlive.status + '. The session may have already expired, please try to save the page now'); }}window.setTimeout('AutoSaveSubmit()',interval);
You might be wondering why i append the timer code/number to the url of the web service. The reason is because IE has a caching bug and will not actually send the XmlHttp request unless the URL is different to what it has in its history, it will just return the previous result.
Remember Me