javascript 在闲置/不活动 60 秒后重定向用户?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5631307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Redirect user after 60 seconds of idling/inactivity?
提问by simon
How can I use JavaScript on my site to redirect the user to a /logout
page after 60 seconds of inactivity?
如何在我的网站上使用 JavaScript 将用户重定向到/logout
60 秒不活动后的页面?
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?
这可以用 JavaScript 实现吗?
采纳答案by jallmer
I belive you are looking for something like this:
http://paulirish.com/2009/jquery-idletimer-plugin/
我相信你正在寻找这样的东西: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.
如果您要自己编写代码,则需要捕获鼠标和键盘事件,并在这些事件发生后重新启动计时器。如果计时器达到阈值或从阈值倒计时到 0,您可以重置页面的 URL。
回答by Samuel Liew
Instead of using a plugin with unnecessary Kbytes, all you need is a simple function like this
(see explanation in comments):
与其使用具有不必要的 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>
If you want to redirect to the home page (usually at /
), change '/logout'
to '/'
:
如果要重定向到主页(通常在/
),请更改'/logout'
为'/'
:
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
:
如果您想重新加载/刷新当前页面,只需将'/logout'
上面的代码更改为location.href
:
const redirectUrl = location.href; // Redirect idle users to the same page
回答by Firze
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.
它将能够在整个文档或单个元素上触发空闲事件。例如,将鼠标悬停在某个元素上 x 秒并触发一个事件。当用户再次激活时会触发另一个事件。
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
支持的活动: mousemove keydown wheel DOMMouseScroll mousewheel mousedown touchstart touchmove MSPointerDown MSPointerMove
回答by Plabon Dutta
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.
每当用户登录、点击某物或移动鼠标时设置一个计时器。您可以维护一个 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);
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.
之后,setInterval()
每隔 10、20、30 或 60 秒(根据您的选择)继续调用以下函数以检查该时间限制是否已过期。或者您可以在用户尝试交互时调用该函数来检查他的空闲时间是否超过阈值。
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 so the same.
您可以使用 cookie 来做同样的事情。