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

发布于 2024-11-01 09:02:01 字数 164 浏览 18 评论 0原文

如何在我的网站上使用 JavaScript 在用户处于非活动状态 60 秒后将其重定向到 /logout 页面?

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

这可以用 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

恍梦境° 2024-11-08 09:02:01

您不需要使用具有不必要的 Kbytes 的插件,您所需要的只是一个像这样的简单函数
(请参阅注释中的说明)

<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

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
深爱成瘾 2024-11-08 09:02:01

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

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

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.

沐歌 2024-11-08 09:02:01

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

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

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

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

https://github.com/thorst/jquery-空闲定时器

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

心清如水 2024-11-08 09:02:01

每当用户登录、单击某项或移动鼠标时设置计时器。您可以维护 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 来执行相同的操作。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文