如何在我的网站上使用 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/