Redirection with timer and user usage identifier

0

My question is a bit complex:

Today I use a simple redirect just using HTML:

<meta HTTP-EQUIV='Refresh' CONTENT='480;URL=./logout.php?type=2'>

Where "CONTENT" is the regressive time (in seconds) it will count before redirecting. But I use this code as an auto-logout. Since 480 seconds is 8 minutes, after 8 minutes without a page change or update the system will automatically "unplug". However, I had to add a new feature in the system, where it is now normal to exceed this time.

What I really need is something (whether in JavaScript / ajax / PHP / html / Jquery) that kills the time if the user is moving the mouse or keyboard (ie interacting with the page) so that the system does not close in the middle of the job.

In my head this is a seven-headed animal, if anyone can help me ... I thank you very much!

    
asked by anonymous 05.04.2016 / 23:00

1 answer

1

I do not know how you control the validity of the session on the server, so I will focus exclusively on the client.

The basic idea is to use the function 'setTimeout (function, TimeEmMiligeconds)' to 'schedule' the function call 'logoutFunction'. In this function I use the time of the last interaction with the system to decide whether the user will be redirected to the logout page or whether the redirect will be delayed.

In order to save the time of the last modification, a function ('setLastModified') was created that simply modifies the variable used in the time comparison ('var lastModified'), then the function is assigned to the events 'onmousemove' and 'onkeypress' so every time a mouse movement or a key is pressed the time will be updated.

(function(){
    var minutesToLogout = 8 * 60 * 1000; // Configure o tempo que achar melhor
    var logoutUrl = './logout.php?type=2'; // Configure a URL de logout

    var lastModified = Date.now();
    var html = document.getElementsByTagName('html')[0];
    var setLastModified = function(){lastModified = Date.now();}

    html.onmousemove = setLastModified;
    html.onkeypress = setLastModified;

    var logoutFunction = function(){
        var timeDiff = Date.now() - lastModified;
        if(timeDiff > minutesToLogout)
            document.location = logoutUrl;
        else
            setTimeout(logoutFunction, minutesToLogout - timeDiff);
    }
    setTimeout(logoutFunction, minutesToLogout);
})();

Obs. The setTimeout function is not exact, it may be slightly delayed in some circumstances, but nothing very disturbing.

    
06.04.2016 / 01:22