【发布时间】:2023-02-17 17:41:07
【问题描述】:
如何检测是否按下重新加载按钮,然后暂停进程并重新加载。就像按下重新加载或 Ctrl + R 时一样,我想保存它已重新加载到本地存储中。
【问题讨论】:
标签: javascript object-detection reload
如何检测是否按下重新加载按钮,然后暂停进程并重新加载。就像按下重新加载或 Ctrl + R 时一样,我想保存它已重新加载到本地存储中。
【问题讨论】:
标签: javascript object-detection reload
处理onbeforeunload事件的事件处理器是WindowEventHandlersmixin的onbeforeunload属性。当窗口即将卸载其资源时,将触发这些事件。
window.onbeforeunload = function(m) {
return 'Your Statement';
};
你可以参考 Mozilla 文档了解更多,因为你没有共享你的源代码。 https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
【讨论】:
在重新加载/刷新页面时将 localStorage 保存在浏览器中。
添加 Javascript 代码如下
window.onload = function () {
alert(localStorage.variable) //comment this line to avoid alert box
localStorage.setItem("variable", "set a variable value");
}
【讨论】:
如果你想知道你当前运行脚本的页面之前是否被重新加载过,你可以使用PerformanceNavigation或者最近的PerformanceNavigationTiming:
performance?.getEntriesByType("navigation")?.[0]?.type === "reload" || performance.navigation.type === PerformanceNavigation.TYPE_RELOAD
如果这太冗长,您可以省略 optional chaining 和常量:
performance.getEntriesByType("navigation").[0].type === "reload" || performance.navigation.type === 1
如果您只想支持现代浏览器,则可以省略第二部分。
我不确定使用本地存储的目的是什么,但也许你甚至不需要保存它,因为你马上就知道了。
导航对象还包含更多信息,如 redirectCount,这可能也很有趣。
【讨论】: