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

sim*_*mon 7 javascript timeout javascript-events user-inactivity url-redirection

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

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

这可以用JavaScript吗?

jal*_*mer 5

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

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


Sam*_*iew 5

您不需要使用一个不必要的KB插件,而需要的只是一个简单的函数,如下所示
(请参见注释中的说明)

<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>
Run Code Online (Sandbox Code Playgroud)

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

    const redirectUrl = '/';  // Redirect idle users to the root directory
Run Code Online (Sandbox Code Playgroud)

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

    const redirectUrl = location.href;  // Redirect idle users to the same page
Run Code Online (Sandbox Code Playgroud)