如何在给定的不活动时间后自动重新加载页面

如网页在一段时间内没有任何活动,我怎样可以自动重新载入网页?

448169 次浏览
<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>

这可以在没有 javascript 的情况下通过这个 metatag 实现:

<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 解决方案。也许能把它变成一个插件。我用它来自动清洗液体,但看起来它可以帮助你。

JSFiddle 自动刷新

// 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);

这个任务是非常容易使用下面的 HTML 头部分的代码

<head> <meta http-equiv="refresh" content="30" /> </head>

它会在30秒后刷新你的页面。

是的,亲爱的,那么您必须使用 Ajax 技术 特定 html 标签:

 <html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title>Ajax Page</title>
<script>
setInterval(function () { autoloadpage(); }, 30000); // it will call the function autoload() after each 30 seconds.
function autoloadpage() {
$.ajax({
url: "URL of the destination page",
type: "POST",
success: function(data) {
$("div#wrapper").html(data); // here the wrapper is main div
}
});
}
</script>
</head>
<body>
<div id="wrapper">
contents will be changed automatically.
</div>
</body>
</html>
var bd = document.getElementsByTagName('body')[0];
var time = new Date().getTime();


bd.onmousemove = goLoad;
function goLoad() {
if(new Date().getTime() - time >= 1200000) {
time = new Date().getTime();
window.location.reload(true);
}else{
time = new Date().getTime();
}
}

每次你移动鼠标,它都会检查你最后一次移动鼠标的时间。如果时间间隔大于20’,它将重新加载页面,否则它将更新上次移动鼠标的时间。

我认为 activity是用户是否专注于窗口。例如,当你从一个窗口点击到另一个窗口(例如 Google Chrome 到 iTunes,或者在一个互联网浏览器中从 Tab 1到 Tab 2) ,网页会发送一个回调说“我失焦了!”或者“我在焦点上!”.人们可以使用 jQuery 来利用这种可能的缺乏活动的情况来做任何他们想做的事情。如果我在你的位置,我会使用下面的代码检查焦点每5秒,等重新加载如果没有焦点。

var window_focus;
$(window).focus(function() {
window_focus = true;
}).blur(function() {
window_focus = false;
});
function checkReload(){
if(!window_focus){
location.reload();  // if not focused, reload
}
}
setInterval(checkReload, 5000);  // check if not focused, every 5 seconds

基于 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,这使得代码更加紧凑。

自动重新加载与您选择的目标。在这种情况下,目标是将 _self设置为它自己,但是您可以通过简单地将 window.open('self.location', '_self');代码更改为类似于 examplewindow.top.location="window.open('http://www.YourPageAdress.com', '_self'";的内容来更改重新加载页面。

附上确认提醒信息:

<script language="JavaScript">
function set_interval() {
//the interval 'timer' is set as soon as the page loads
var timeoutMins = 1000 * 1 * 15; // 15 seconds
var timeout1Mins = 1000 * 1 * 13; // 13 seconds
itimer=setInterval("auto_logout()",timeoutMins);
atimer=setInterval("alert_idle()",timeout1Mins);


}


function reset_interval() {
var timeoutMins = 1000 * 1 * 15; // 15 seconds
var timeout1Mins = 1000 * 1 * 13; // 13 seconds
//resets the timer. The timer is reset on each of the below events:
// 1. mousemove   2. mouseclick   3. key press 4. scrolling
//first step: clear the existing timer
clearInterval(itimer);
clearInterval(atimer);
//second step: implement the timer again
itimer=setInterval("auto_logout()",timeoutMins);
atimer=setInterval("alert_idle()",timeout1Mins);
}


function alert_idle() {
var answer = confirm("Session About To Timeout\n\n       You will be automatically logged out.\n       Confirm to remain logged in.")
if (answer){


reset_interval();
}
else{
auto_logout();
}
}


function auto_logout() {
//this function will redirect the user to the logout script
window.open('self.location', '_self');
}
</script>

在没有确认警报的情况下:

<script language="JavaScript">
function set_interval() {
//the interval 'timer' is set as soon as the page loads
var timeoutMins = 1000 * 1 * 15; // 15 seconds
var timeout1Mins = 1000 * 1 * 13; // 13 seconds
itimer=setInterval("auto_logout()",timeoutMins);


}


function reset_interval() {
var timeoutMins = 1000 * 1 * 15; // 15 seconds
var timeout1Mins = 1000 * 1 * 13; // 13 seconds
//resets the timer. The timer is reset on each of the below events:
// 1. mousemove   2. mouseclick   3. key press 4. scrolling
//first step: clear the existing timer
clearInterval(itimer);
clearInterval(atimer);
//second step: implement the timer again
itimer=setInterval("auto_logout()",timeoutMins);
}




function auto_logout() {
//this function will redirect the user to the logout script
window.open('self.location', '_self');
}
</script>

两种解决方案的主体代码是相同的:

<body onLoad="set_interval(); document.form1.exp_dat.focus();" onKeyPress="reset_interval();" onmousemove="reset_interval();" onclick="reset_interval();" onscroll="reset_interval();">

用页面确认文本代替警报

因为这是另一种在不活动时自动加载的方法,所以我给出了第二个答案。这个更简单,更容易理解。

在页面上带有重新加载确认

<script language="javaScript" type="text/javascript">
<!--
var autoCloseTimer;
var timeoutObject;
var timePeriod = 5100; // 5,1 seconds
var warnPeriod = 5000; // 5 seconds
// Warning period should always be a bit shorter then time period


function promptForClose() {
autoCloseDiv.style.display = 'block';
autoCloseTimer = setTimeout("definitelyClose()", warnPeriod);
}




function autoClose() {
autoCloseDiv.style.display = 'block'; //shows message on page
autoCloseTimer = setTimeout("definitelyClose()", timePeriod); //starts countdown to closure
}


function cancelClose() {
clearTimeout(autoCloseTimer); //stops auto-close timer
autoCloseDiv.style.display = 'none'; //hides message
}


function resetTimeout() {
clearTimeout(timeoutObject); //stops timer
timeoutObject = setTimeout("promptForClose()", timePeriod); //restarts timer from 0
}




function definitelyClose() {


// If you use want targeted reload: parent.Iframe0.location.href = "https://URLHERE.com/"
// or  this: window.open('http://www.YourPageAdress.com', '_self');


// of for the same page reload use: window.top.location=self.location;
// or window.open(self.location;, '_self');


window.top.location=self.location;
}
-->
</script>

在页面确认时使用确认框

<div class="leftcolNon">
<div id='autoCloseDiv' style="display:none">
<center>
<b>Inactivity warning!</b><br />
This page will Reloads automatically unless you hit 'Cancel.'</p>
<input type='button' value='Load' onclick='definitelyClose();' />
<input type='button' value='Cancel' onclick='cancelClose();' />
</center>
</div>
</div>

两者的身体代码是相同的

<body onmousedown="resetTimeout();" onmouseup="resetTimeout();" onmousemove="resetTimeout();" onkeydown="resetTimeout();" onload="timeoutObject=setTimeout('promptForClose()',timePeriod);">

注意: 如果您不想在页面上进行确认,请使用 < strong >

<script language="javaScript" type="text/javascript">
<!--
var autoCloseTimer;
var timeoutObject;
var timePeriod = 5000; // 5 seconds


function resetTimeout() {
clearTimeout(timeoutObject); //stops timer
timeoutObject = setTimeout("definitelyClose()", timePeriod); //restarts timer from 0
}


function definitelyClose() {


// If you use want targeted reload: parent.Iframe0.location.href = "https://URLHERE.com/"
// or  this: window.open('http://www.YourPageAdress.com', '_self');


// of for the same page reload use: window.top.location=self.location;
// or window.open(self.location;, '_self');


window.top.location=self.location;
}
-->
</script>

最后一个最简单的解决办法:

警报确认:

<script type="text/javascript">
// Set timeout variables.
var timoutWarning = 3000; // Display warning in 1Mins.
var timoutNow = 4000; // Timeout in 2 mins.


var warningTimer;
var timeoutTimer;


// Start timers.
function StartTimers() {
warningTimer = setTimeout("IdleWarning()", timoutWarning);
timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
}


// Reset timers.
function ResetTimers() {
clearTimeout(warningTimer);
clearTimeout(timeoutTimer);
StartTimers();
$("#timeout").dialog('close');
}


// Show idle timeout warning dialog.
function IdleWarning() {
var answer = confirm("Session About To Timeout\n\n       You will be automatically logged out.\n       Confirm to remain logged in.")
if (answer){


ResetTimers();
}
else{
IdleTimeout();
}
}


// Logout the user and auto reload or use this window.open('http://www.YourPageAdress.com', '_self'); to auto load a page.
function IdleTimeout() {
window.open(self.location,'_top');
}
</script>

未经警报确认:

<script type="text/javascript">
// Set timeout variables.
var timoutWarning = 3000; // Display warning in 1Mins.
var timoutNow = 4000; // Timeout in 2 mins.


var warningTimer;
var timeoutTimer;


// Start timers.
function StartTimers() {
warningTimer = setTimeout(timoutWarning);
timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
}


// Reset timers.
function ResetTimers() {
clearTimeout(warningTimer);
clearTimeout(timeoutTimer);
StartTimers();
$("#timeout").dialog('close');
}


// Logout the user and auto reload or use this window.open('http://www.YourPageAdress.com', '_self'); to auto load a page.
function IdleTimeout() {
window.open(self.location,'_top');
}
</script>

两种解决方案的正文代码是相同的

<body onload="StartTimers();" onmousemove="ResetTimers();" onKeyPress="ResetTimers();">

使用 JavaScript setInterval方法:

setInterval(function(){ location.reload(); }, 3000);

使用 LocalStorage 跟踪最后一次活动的时间,我们可以编写 reload 函数,如下所示

function reloadPage(expiryDurationMins) {
const lastInteraction = window.localStorage.getItem('lastinteraction')
if (!lastInteraction) return // no interaction recorded since page load
const inactiveDurationMins = (Date.now() - Number(lastInteraction)) / 60000
const pageExpired = inactiveDurationMins >= expiryDurationMins
if (pageExpired) window.location.reload()
}

然后我们创建一个箭头函数,它将上次交互的时间保存为毫秒(String)

const saveLastInteraction = () => window.localStorage.setItem('last', Date.now().toString())

我们将需要在浏览器中听取 beforeunload事件来清除我们的 lastinteraction记录,这样我们就不会陷入无限重载循环。

window.addEventListener('beforeunload', () => window.localStorage.removeItem('lastinteraction'))

我们需要监视的用户活动事件是 mousemovekeypress。当用户移动鼠标或按下键盘上的一个键时,我们存储最后的交互时间

window.addEventListener('mousemove', saveLastInteraction)
window.addEventListener('keypress', saveLastInteraction)

要设置最终的侦听器,我们将使用 load事件。 在页面加载时,我们使用 setInterval函数来检查页面是否在一段时间后过期。

const expiryDurationMins = 1


window.addEventListener('load', setInterval.bind(null, reloadPage.bind(null, expiryDurationMins), 1000))

我是这样做的:

let lastActionTaken = new Date().getTime();
function checkLastAction() {
let now = new Date().getTime();
if (now - lastActionTaken > 1000 * 60 * 60) window.location.reload();
else lastActionTaken = now;
}
window.addEventListener("mousemove", checkLastAction);
window.addEventListener("touchstart", checkLastAction);
window.addEventListener("keydown", checkLastAction);

当用户移动鼠标,点击一个键或触摸一个触摸屏(如果它已经停止运行1小时)时,这将重新加载页面。此外,这也照顾到了 focus,因此,如果一个用户在一个不同的程序中移动他们的鼠标,然后返回到这个 window,它将重新加载,这是好的,因为关键是没有旧的数据显示。

许多其他的答案要么没有回答“没有活动”这个问题的主要部分,要么是难以置信的,不必要的复杂。我已经接受了公认的答案(这里: https://stackoverflow.com/a/4644315/9008140) 并对其进行修改,以利用可以为变量分配计时器这一事实。这允许我们去掉第二个计时器以及时间戳。

/**
* create a timer that refreshes the page after the number of
minutes has passed without user interaction.
* Moving the mouse or pressing a key on the current page will start
the timer over.
* @param {any} minutes
*/
var refreshTimer;
function setPageRefreshTimer(minutes) {
var refreshInterval = minutes * 60 * 1000; //interval is in milliseconds.  We refresh every x minutes.
$(document.body).bind("mousemove keypress", function (e) {
if (refreshTimer != null && refreshTimer != undefined) {
window.clearTimeout(refreshTimer);
}
refreshTimer = window.setTimeout(function () { window.location.reload(true); }, refreshInterval);
});
refreshTimer = window.setTimeout(function () { window.location.reload(true); }, refreshInterval);

}

这个示例代码将在几分钟内根据传入的参数进行刷新,其准确性与 javascript 计时器一样高。在测试中,总是不到一秒钟。我创建了这个作为一个函数,但你可以拉到你的网页,如果你愿意。