在空闲/不活动60秒后重定向用户?

时间:2011-04-12 06:39:40

标签: javascript javascript-events timeout url-redirection user-inactivity

如何在我的网站上使用JavaScript在60秒不活动后将用户重定向到/logout页面?

我知道设置计时器或使用元刷新标签很简单:但我只想重定向非活动用户,而不是破坏某人的活动会话/使用。

这可以用JavaScript吗?

4 个答案:

答案 0 :(得分:6)

我相信你正在寻找这样的事情:
http://paulirish.com/2009/jquery-idletimer-plugin/

如果您自己编写代码,则需要捕获鼠标和键盘事件,并在发生任何这些事件后重新启动计时器。如果计时器达到阈值或从阈值向下计数到0,则可以重置页面的URL。

答案 1 :(得分:4)

还有一个更新的插件版本。

它将能够在整个文档或单个元素上触发空闲事件。例如,将鼠标悬停在某个元素上x秒,然后触发一个事件。当用户再次激活时会触发另一个事件。

此空闲事件将允许您在给定的不活动时间后重定向用户。

支持的活动:mousemove keydown wheel DOMMouseScroll mousewheel mousedown touchstart touchmove MSPointerDown MSPointerMove

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

答案 2 :(得分:3)

您不需要使用具有不必要的千字节大小的插件,而是需要像这样的简单函数
(请参见注释中的说明)

<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>

如果要重定向到主页(通常位于/),请将'/logout'更改为'/'

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

如果您想重新加载/刷新当前页面,只需将上面代码中的'/logout'更改为location.href

    const redirectUrl = location.href;  // Redirect idle users to the same page

答案 3 :(得分:0)

在用户登录,单击某些内容或移动鼠标时设置计时器。您可以维护localStorage,sessionStorage或任何全局变量来跟踪空闲时间。

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

此后,每隔10、20、30或60秒(根据您的选择)从setInterval()之类的内部继续调用以下函数,以检查该时间限制是否已到期。或者,只要用户尝试进行交互以检查其空闲时间是否已超过阈值,就可以调用该函数。

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);
  }
}

您也可以使用cookie。

相关问题