最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Redirect user after 60 seconds of idlinginactivity? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Apr 22, 2020 at 7:33 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Apr 12, 2011 at 6:39 simonsimon 6,11713 gold badges32 silver badges28 bronze badges 3
  • Not sure, but I think you can bind every action to the function that will reset the timer... – user684934 Commented Apr 12, 2011 at 6:43
  • 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? – Chris Cherry Commented Apr 12, 2011 at 6:46
  • 1 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 ;) – jallmer Commented Apr 12, 2011 at 8:27
Add a comment  | 

4 Answers 4

Reset to default 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

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.

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

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.

发布评论

评论列表(0)

  1. 暂无评论