I have a site with a session timeout of 15 minutes. On some pages a user occasionally spends longer than 15 minutes filling in a reply. What is the best solution to keep alive the session in this case?
I already use JQuery
on these pages, so possibly pinging a server, but on what events?
The backend is a Struts
on Tomcat
.
If you want to keep the session even if the browser is closed then you need to use persistent cookies which are stored on the user computer rather than HTTP only cookies.
Yes it's safe. As far as load, that's up to your hardware and how you write it, but it has no worse effect than users refreshing the page (arguably less considering the overhead of an AJAX call over a standard page load). You can adjust the timeout in the web.
Given you don't want to change the site's session timeout..
Set a timeout/interval (< 15min) event in javascript and decide what to do when the event triggers. If you want the session to be active as long as the page is open, then fine, keep pinging every < 15 min. But that's probably not what you want as a user leaving a public computer should get logged out at some point.
You could maintain a variable lastActivity
, which is updated on each document mousemove or document keydown. If there's been any activity since last ping, ping again.
To get more sophisticated, you could count the events and ping the server only if number of events > threshold at timeout.
The basic example:
setInterval(function(){
$.get('/ImStillAlive.action');
}, 840000); // 14 mins * 60 * 1000
With basic check for typing activity:
$(function(){
var lastUpdate = 0;
var checkInterval = setInterval(function(){
if(new Date().getTime() - lastUpdate > 840000){
clearInterval(checkInterval);
}else{
$.get('/ImStillAlive.action');
}
}, 840000); // 14 mins * 60 * 1000
$(document).keydown(function(){
lastUpdate = new Date().getTime();
});
});
I'm thinking that you really don't want this for ALL pages though. If you were to do this on every page, even the ones that really don't depend on session variables, you'd consume a lot of memory.
I'd suggest throwing in a conditional to do it only on certain pages where it's necessary, i.e.
if (location.href.indexOf('/checkout') !== -1) {
setInterval(function(){
$.get('/keepalive.action');
}, 840000); // 14 mins
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With