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

标签 javascript redirect timeout dom-events user-inactivity

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

我知道设置计时器或使用元刷新标签很简单:但我只想重定向非事件用户,而不是中断某人的事件 session /使用。

这可以用 JavaScript 实现吗?

最佳答案

与其使用不必要的 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

关于javascript - 在空闲/不活动 60 秒后重定向用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5631307/

相关文章:

tcp - 哪个超时值决定了多长时间空闲的TCP连接会被关闭?

javascript - 代码中硬编码的 Web API 调用与多种环境的比较

javascript - 利用jquery html编码XSS

python - Pyramid 中的条件重定向

macos - 没有端口的本地名称解析 - MAMP Pro

video - 将 'timeout' 标志添加到 ffprobe/ffmpeg 会导致它立即失败

timeout - Weblogic 文件存储,发出请求时事务超时

JavaScript:从数组调用函数

javascript - 如何在我的vue js中实现无限滚动

javascript - 设置cookie并重定向,不带express