如何单独检测浏览器刷新 [英] How to detect browser refresh alone
本文介绍了如何单独检测浏览器刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想单独检测JavaScript中的浏览器刷新.下面的代码正在使用来检测浏览器的关闭以及刷新,返回等.
Hi i want to detect browser refresh alone in javascript. The below code am using is detecting the browser close as well as refresh, back etc.
window.onbeforeunload = function (evt) {
var message = 'Are you sure you want to leave?';
console.log(evt);
console.log(window.event);
console.log(event);
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return evt;
}
推荐答案
您可以将当前时间从onbeforeunload
保存到会话存储中,然后在页面加载时在会话存储中查找一段时间,如果找到一个并且(假设)几秒钟之内.
You can save the current time to session storage from onbeforeunload
, then when the page loads look in session storage for a time and, if you find one and it's within (say) a couple of seconds, assume it's a refresh.
window.onbeforeunload = function() {
sessionStorage.setItem("left", Date.now());
};
和其他地方,在页面加载时运行的代码中:
and elsewhere, in code that runs when the page loads:
var left = sessionStorage.getItem("left");
if (left && (Date.now() - left) < 2000) {
// Refreshed
}
完整示例(实时复制):
(function() {
"use strict";
window.onbeforeunload = function() {
sessionStorage.setItem("left", Date.now());
};
var left = sessionStorage.getItem("left");
if (left && (Date.now() - left) < 2000) {
// Refreshed
display("Refreshed");
} else {
// Freshly loaded
}
})();
这篇关于如何单独检测浏览器刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文