如何在我的网站上使用 JavaScript 将用户重定向到/logout
60 秒不活动后页面?
我知道设置计时器或使用元刷新标记很简单:但我只想重定向不活动的用户,而不是中断某人的活动会话/使用。
这可以用 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'
to '/'
:
const redirectUrl = '/'; // Redirect idle users to the root directory
如果您想重新加载/刷新当前页面,只需更改'/logout'
在上面的代码中location.href
:
const redirectUrl = location.href; // Redirect idle users to the same page
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)