Detecting user inactivity over a browser - purely through javascript

Ranjan Sarma picture Ranjan Sarma · Nov 6, 2012 · Viewed 64.5k times · Source

In building a monitor, which would monitor any activity on the browser by the user, like click of a button or typing on a textbox (not mouse hovering on document). So if there is no activity from the user for a long time, the session will time out.

We need to do it without jquery or anything such. I may use ajax. java servlet in other end is preferable.

Answer

AnhSirk Dasarp picture AnhSirk Dasarp · Nov 6, 2012

Here is pure JavaScript way to track the idle time and when it reach certain limit do some action, you can modify accordingly and use

var IDLE_TIMEOUT = 60; //seconds
var _idleSecondsCounter = 0;
document.onclick = function() {
    _idleSecondsCounter = 0;
};
document.onmousemove = function() {
    _idleSecondsCounter = 0;
};
document.onkeypress = function() {
    _idleSecondsCounter = 0;
};
window.setInterval(CheckIdleTime, 1000);

function CheckIdleTime() {
    _idleSecondsCounter++;
    var oPanel = document.getElementById("SecondsUntilExpire");
    if (oPanel)
        oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
    if (_idleSecondsCounter >= IDLE_TIMEOUT) {
        alert("Time expired!");
        document.location.href = "logout.html";
    }
}

This code will wait 60 seconds before showing alert and redirecting, and any action will "reset" the count - mouse click, mouse move or key press.

It should be as cross browser as possible, and straight forward. It also support showing the remaining time, if you add element to your page with ID of SecondsUntilExpire.

Ref: How to know browser idle time?