Redirect user after 60 seconds of idling/inactivity?
Asked Answered
L

4

13

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?

Leslileslie answered 12/4, 2011 at 6:39 Comment(3)
Not sure, but I think you can bind every action to the function that will reset the timer...Rhettrhetta
What is "inactive" defined as? Not moving the mouse? Not pressing keys? What if they take 60 seconds to read something and not hit the mouse and keyboard as they read?Iatrogenic
What if a user passes out in front of the keyboard wouldn't it be good to notify the hospital? Great UI feature I say ;)Zohar
Z
5

I belive you are looking for something like this:
http://paulirish.com/2009/jquery-idletimer-plugin/

If you were to code that yourself, you would need to capture mouse and keyboard events and restart your timer after any of these events. If the timer ever reaches the threshold or counts down to 0 from the threshold you can reset the URL of the page.

Zohar answered 12/4, 2011 at 6:45 Comment(0)
S
23

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
Stir answered 3/9, 2018 at 0:36 Comment(0)
Z
5

I belive you are looking for something like this:
http://paulirish.com/2009/jquery-idletimer-plugin/

If you were to code that yourself, you would need to capture mouse and keyboard events and restart your timer after any of these events. If the timer ever reaches the threshold or counts down to 0 from the threshold you can reset the URL of the page.

Zohar answered 12/4, 2011 at 6:45 Comment(0)
S
4

There is also a more up-to-date version of the plugin.

It will be able to fire idle event on entire document or single elements. For example mouse over some element for x seconds and it fires an event. Another event is fired when user becomes active again.

This idle event will allow you to redirect user after given time of inactivity.

Supported activity: mousemove keydown wheel DOMMouseScroll mousewheel mousedown touchstart touchmove MSPointerDown MSPointerMove

https://github.com/thorst/jquery-idletimer

South answered 8/1, 2015 at 7:18 Comment(0)
O
1

Set a timer whenever a user logs in, clicks something or moves mouse. You can maintain a localStorage, sessionStorage or any global variable to keep track of the idle time.

let obj_date = new Date();
let miliseconds = obj_date.getTime(); // Returns the number of miliseconds since 1970/01/01
localStorage.setItem("idle_time",miliseconds); 

After that, keep calling the following function from within something like setInterval() every 10,20,30 or 60 seconds (as per your choice) to check if that time limit has expired. Or you can call the function whenever a user tries to interact to check if his idle time has exceeded the threshold.

function check_if_session_expired() {
  let max_idle_minutes=1;
  let miliseconds_now = obj_date.getTime();
  let get_idle_time_in_miliseconds = localStorage.getItem("idle_time");
  let one_minute_to_milisecond = 1000 * 60;
  if ((Math.round(miliseconds_now / one_minute_to_milisecond) - Math.round(get_idle_time_in_miliseconds / one_minute_to_milisecond)) >= max_idle_minutes) {
    console.log("expired");
    //clear sessionStorage/localStorage if you want
    localStorage.removeItem("idle_time");
    //end the session and redirect the user to logout page
    window.location.replace('example.com/logout');
  } else {
    localStorage.setItem("idle_time",miliseconds_now);
  }
}

You can use cookies to do the same.

Olid answered 22/4, 2020 at 6:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.