Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect user after 60 seconds of idling/inactivity?

How can I use JavaScript on my site to redirect the user to a /logout page after 60 seconds of inactivity?

I know setting a timer or using a meta refresh tag is straightforward: but I only want to redirect inactive users, not disrupt someone's active session/usage.

Is this possible with JavaScript?

like image 458
simon Avatar asked Apr 12 '11 06:04

simon


People also ask

What is idle time in browser?

The idle time is the time that the user has no interaction with the web-page. It can be mouse movement, page click or when the user uses the keyboard. The idle time can be detected using either vanilla JavaScript or jQuery code.

How do I check my idle timeout?

These include methods like onload, onmousemove, onmousedown, ontouchstart, onclick and onkeypress. The other function which will be invoked when the user is idle can be used to keep track of the time and perform actions when the user has been inactive for a longer time.


1 Answers

Instead of using a plugin with unnecessary Kbytes, all you need is a simple function like this
(see explanation in comments):

<script>
(function() {

    const idleDurationSecs = 60;    // X number of seconds
    const redirectUrl = '/logout';  // Redirect idle users to this URL
    let idleTimeout; // variable to hold the timeout, do not modify

    const resetIdleTimeout = function() {

        // Clears the existing timeout
        if(idleTimeout) clearTimeout(idleTimeout);

        // Set a new idle timeout to load the redirectUrl after idleDurationSecs
        idleTimeout = setTimeout(() => location.href = redirectUrl, idleDurationSecs * 1000);
    };

    // Init on page load
    resetIdleTimeout();

    // Reset the idle timeout on any of the events listed below
    ['click', 'touchstart', 'mousemove'].forEach(evt => 
        document.addEventListener(evt, resetIdleTimeout, false)
    );

})();
</script>

If you want to redirect to the home page (usually at /), change '/logout' to '/':

    const redirectUrl = '/';  // Redirect idle users to the root directory

If you want to reload/refresh the current page, simply change '/logout' in the code above to location.href:

    const redirectUrl = location.href;  // Redirect idle users to the same page
like image 50
Samuel Liew Avatar answered Sep 17 '22 12:09

Samuel Liew