How to keep alive a user's session while they are posting on a forum?

拥有回忆 提交于 2019-11-28 06:02:20
Alexander Sagen

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
}

You could set an interval ever 5 minutes:

setInterval(function() {
    // check if a reply textarea is present on the page and focussed
    // assuming it's e.g. a textarea with the id "reply"
    if ($('#reply:focussed').length) {
        // user is still on the reply page
        // call on a script on the server that renews the session
    }
}, 300000);

Or check whether he/she is still typing something:

<textarea id="reply"></textarea>
<input type="hidden" id="reply_length" name="length" />
setInterval(function() {
    // get length of text in textarea
    var len = $('#reply').val().length;

    // get previous length
    var prev = $('#reply_length').val().length;

    // if they don't match, assume they're doing something
    if (len != prev) {
        // renew session
    }

    // update previous length
    $('#reply_length').val(len);
}, 300000);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!