gpt4 book ai didi

javascript - 如何单独检测浏览器刷新

转载 作者:行者123 更新时间:2023-12-03 10:42:27 25 4
gpt4 key购买 nike

嗨,我想在 JavaScript 中单独检测浏览器刷新。我使用的下面的代码是检测浏览器关闭以及刷新、返回等。

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 将当前时间保存到 session 存储中,然后当页面加载时在 session 存储中查找一段时间,如果您找到一个并且它在(比如说)几秒钟内,假设这是一次刷新。

window.onbeforeunload = function() {
sessionStorage.setItem("left", Date.now());
};

以及其他地方,在页面加载时运行的代码中:

var left = sessionStorage.getItem("left");
if (left && (Date.now() - left) < 2000) {
// Refreshed
}

完整示例(live copy):

(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
}
})();

关于javascript - 如何单独检测浏览器刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28712173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com