如果在给定的时间段内页面上没有任何活动,我如何自动重新加载网页?
如何在给定的不活动时间后自动重新加载页面
IT技术
javascript
ajax
2021-01-28 12:00:22
6个回答
这可以在没有 javascript 的情况下完成,使用这个元标记:
<meta http-equiv="refresh" content="5" >
其中 content ="5" 是页面等待刷新的秒数。
但是你说只有没有活动,那是什么活动?
如果你想在没有活动的情况下刷新页面,那么你需要弄清楚如何定义活动。假设我们每分钟刷新一次页面,除非有人按下某个键或移动鼠标。这使用 jQuery 进行事件绑定:
<script>
var time = new Date().getTime();
$(document.body).bind("mousemove keypress", function(e) {
time = new Date().getTime();
});
function refresh() {
if(new Date().getTime() - time >= 60000)
window.location.reload(true);
else
setTimeout(refresh, 10000);
}
setTimeout(refresh, 10000);
</script>
我还构建了一个不需要 jquery 的完整 javascript 解决方案。也许可以把它变成一个插件。我用它来进行流畅的自动刷新,但看起来它可以在这里帮助你。
// Refresh Rate is how often you want to refresh the page
// bassed off the user inactivity.
var refresh_rate = 200; //<-- In seconds, change to your needs
var last_user_action = 0;
var has_focus = false;
var lost_focus_count = 0;
// If the user loses focus on the browser to many times
// we want to refresh anyway even if they are typing.
// This is so we don't get the browser locked into
// a state where the refresh never happens.
var focus_margin = 10;
// Reset the Timer on users last action
function reset() {
last_user_action = 0;
console.log("Reset");
}
function windowHasFocus() {
has_focus = true;
}
function windowLostFocus() {
has_focus = false;
lost_focus_count++;
console.log(lost_focus_count + " <~ Lost Focus");
}
// Count Down that executes ever second
setInterval(function () {
last_user_action++;
refreshCheck();
}, 1000);
// The code that checks if the window needs to reload
function refreshCheck() {
var focus = window.onfocus;
if ((last_user_action >= refresh_rate && !has_focus && document.readyState == "complete") || lost_focus_count > focus_margin) {
window.location.reload(); // If this is called no reset is needed
reset(); // We want to reset just to make sure the location reload is not called.
}
}
window.addEventListener("focus", windowHasFocus, false);
window.addEventListener("blur", windowLostFocus, false);
window.addEventListener("click", reset, false);
window.addEventListener("mousemove", reset, false);
window.addEventListener("keypress", reset, false);
window.addEventListener("scroll", reset, false);
document.addEventListener("touchMove", reset, false);
document.addEventListener("touchEnd", reset, false);
<script type="text/javascript">
var timeout = setTimeout("location.reload(true);",600000);
function resetTimeout() {
clearTimeout(timeout);
timeout = setTimeout("location.reload(true);",600000);
}
</script>
除非调用 resetTimeout(),否则上面将每 10 分钟刷新一次页面。例如:
<a href="javascript:;" onclick="resetTimeout();">clicky</a>
基于arturnt的公认答案。这是一个稍微优化的版本,但本质上是一样的:
var time = new Date().getTime();
$(document.body).bind("mousemove keypress", function () {
time = new Date().getTime();
});
setInterval(function() {
if (new Date().getTime() - time >= 60000) {
window.location.reload(true);
}
}, 1000);
唯一的区别是这个版本使用了setInterval
而不是setTimeout
,这使得代码更加紧凑。