Câu trả lời:
Nếu bạn muốn làm mới trang nếu không có hoạt động thì bạn cần tìm ra cách xác định hoạt động. Giả sử chúng tôi làm mới trang mỗi phút trừ khi có ai đó nhấn phím hoặc di chuyển chuột. Điều này sử dụng jQuery để liên kết sự kiện:
<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>
Điều này có thể được thực hiện mà không cần javascript, với thẻ meta này:
<meta http-equiv="refresh" content="5" >
trong đó nội dung = "5" là giây mà trang sẽ đợi cho đến khi được làm mới.
Nhưng bạn chỉ nói nếu không có hoạt động, loại hoạt động đó sẽ là gì?
setInterval
, rất vui khi biết điều này tồn tại!
Tôi đã xây dựng một giải pháp javascript hoàn chỉnh cũng như không yêu cầu jquery. Có thể biến nó thành một plugin. Tôi sử dụng nó để tự động làm mới chất lỏng, nhưng có vẻ như nó có thể giúp bạn ở đây.
// 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>
Ở trên sẽ làm mới trang cứ sau 10 phút trừ khi được gọi là timeTimeout (). Ví dụ:
<a href="javascript:;" onclick="resetTimeout();">clicky</a>
Dựa trên câu trả lời được chấp nhận của arturnt. Đây là một phiên bản được tối ưu hóa một chút, nhưng về cơ bản là giống nhau:
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);
Chỉ có sự khác biệt là phiên bản này sử dụng setInterval
thay vì setTimeout
, làm cho mã nhỏ gọn hơn.
1000
nếu nó đang tính toán bằng cách sử dụng 60000
?
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();
}
}
Mỗi lần bạn di chuyển chuột, nó sẽ kiểm tra lần cuối bạn di chuyển chuột. Nếu khoảng thời gian lớn hơn 20 ', nó sẽ tải lại trang, nếu không, nó sẽ gia hạn lần di chuột cuối cùng của bạn.
Tự động tải lại với mục tiêu bạn chọn. Trong trường hợp này, mục tiêu được _self
đặt thành chính nó, nhưng bạn có thể thay đổi trang tải lại bằng cách thay đổi window.open('self.location', '_self');
mã thành một cái gì đó giống như ví dụ này window.top.location="window.open('http://www.YourPageAdress.com', '_self'";
.
Với thông báo ALERT xác nhận:
<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>
Không có thông báo xác nhận:
<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>
Mã cơ thể là CÙNG cho cả hai giải pháp:
<body onLoad="set_interval(); document.form1.exp_dat.focus();" onKeyPress="reset_interval();" onmousemove="reset_interval();" onclick="reset_interval();" onscroll="reset_interval();">
sử dụng setInterval
phương pháp JavaScript :
setInterval(function(){ location.reload(); }, 3000);
Vâng, vậy thì bạn phải sử dụng công nghệ Ajax. để thay đổi nội dung của thẻ html cụ thể:
<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>
Tôi sẽ xem xét activity
liệu người dùng có tập trung vào cửa sổ hay không. Ví dụ: khi bạn nhấp từ cửa sổ này sang cửa sổ khác (ví dụ: Google Chrome sang iTunes hoặc Tab 1 đến Tab 2 trong trình duyệt internet), trang web có thể gửi một cuộc gọi lại với nội dung "Tôi không tập trung!" hoặc "Tôi đang tập trung!". Người ta có thể sử dụng jQuery để khai thác sự thiếu hoạt động có thể này để làm bất cứ điều gì họ muốn. Nếu tôi ở vị trí của bạn, tôi sẽ sử dụng đoạn mã sau để kiểm tra lấy nét cứ sau 5 giây, v.v. và tải lại nếu không có tiêu điểm.
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
Và cuối cùng là giải pháp đơn giản nhất:
Với xác nhận cảnh báo:
<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>
Không có xác nhận cảnh báo:
<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>
Mã cơ thể là CÙNG cho cả hai giải pháp
<body onload="StartTimers();" onmousemove="ResetTimers();" onKeyPress="ResetTimers();">
Với văn bản xác nhận trên trang thay vì cảnh báo
Vì đây là một phương pháp khác để tự động tải nếu không hoạt động, tôi cung cấp cho nó câu trả lời thứ hai. Điều này là đơn giản và dễ hiểu hơn.
Với xác nhận tải lại trên trang
<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>
Hộp xác nhận khi sử dụng với xác nhận trên trang
<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>
Mã cơ thể cho cả hai là CÙNG
<body onmousedown="resetTimeout();" onmouseup="resetTimeout();" onmousemove="resetTimeout();" onkeydown="resetTimeout();" onload="timeoutObject=setTimeout('promptForClose()',timePeriod);">
LƯU Ý: Nếu bạn không muốn có xác nhận trên trang, hãy sử dụng Không cần xác nhận
<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>
Sử dụng LocalStorage để theo dõi lần hoạt động cuối cùng, chúng ta có thể viết chức năng tải lại như sau
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()
}
Sau đó, chúng tôi tạo một hàm mũi tên giúp lưu lần tương tác cuối cùng tính bằng mili giây (Chuỗi)
const saveLastInteraction = () => window.localStorage.setItem('last', Date.now().toString())
Chúng tôi sẽ cần lắng nghe beforeunload
sự kiện trong trình duyệt để xóa lastinteraction
hồ sơ của chúng tôi để chúng tôi không bị kẹt trong một vòng lặp tải lại vô hạn.
window.addEventListener('beforeunload', () => window.localStorage.removeItem('lastinteraction'))
Các sự kiện hoạt động người dùng chúng ta sẽ cần theo dõi sẽ mousemove
và keypress
. Chúng tôi lưu trữ thời gian tương tác cuối cùng khi người dùng di chuyển chuột hoặc nhấn phím trên bàn phím
window.addEventListener('mousemove', saveLastInteraction)
window.addEventListener('keypress', saveLastInteraction)
Để thiết lập trình nghe cuối cùng của chúng tôi, chúng tôi sẽ sử dụng load
sự kiện này. Khi tải trang, chúng tôi sử dụng setInterval
chức năng để kiểm tra xem trang đã hết hạn sau một khoảng thời gian nhất định.
const expiryDurationMins = 1
window.addEventListener('load', setInterval.bind(null, reloadPage.bind(null, expiryDurationMins), 1000))
Nhiệm vụ này rất dễ sử dụng mã sau trong phần tiêu đề html
<head> <meta http-equiv="refresh" content="30" /> </head>
Nó sẽ làm mới trang của bạn sau 30 giây.