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

Redirect user after 60 seconds of idling/inactivity?

本文关键字:重定向 用户 60秒 不活动      更新时间:2023-09-26

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

我知道设置计时器或使用元刷新标签是直截了当的:但我只想重定向不活跃的用户,而不是破坏某人的活跃会话/使用。

这是可能的JavaScript?

你所需要的只是一个像这样的简单函数
(见注释中的解释):

<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

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

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

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

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

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

支持的活动:鼠标移动按下鼠标滚轮dommousescroroll鼠标滚轮鼠标滚轮touchstart touchmove MSPointerDown MSPointerMove

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

在用户登录、点击或移动鼠标时设置计时器。您可以维护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做同样的事情。