当有人试图刷新页面时,我想检查一下。
例如,当我打开一个页面什么都没有发生,但当我刷新页面时,它应该显示一个警告。
当有人试图刷新页面时,我想检查一下。
例如,当我打开一个页面什么都没有发生,但当我刷新页面时,它应该显示一个警告。
当前回答
在控制台添加以下脚本:
window.addEventListener("beforeunload", function(event) {
console.log("The page is redirecting")
debugger;
});
其他回答
这个实现帮助了我:
来自MDN参考2022:导航授时级别2规范
const navigationType =
(window.performance.getEntriesByType('navigation')
[0] as PerformanceNavigationTiming).type;
const isPageReload = navigationType === 'reload';
const isNavigation = navigationType === 'navigate';
const isBackForwarad = navigationType === 'back_forward';
const isPrerender = navigationType === 'prerender';
在控制台添加以下脚本:
window.addEventListener("beforeunload", function(event) {
console.log("The page is redirecting")
debugger;
});
下面是一个几乎所有浏览器都支持的方法:
if (sessionStorage.getItem('reloaded') != null) {
console.log('page was reloaded');
} else {
console.log('page was not reloaded');
}
sessionStorage.setItem('reloaded', 'yes'); // could be anything
它使用SessionStorage来检查页面是第一次打开还是刷新。
我在JavaScript检测页面刷新中找到了一些信息。他的第一个建议是使用隐藏字段,这些字段往往是通过页面刷新存储的。
function checkRefresh() { if (document.refreshForm.visited.value == "") { // This is a fresh page load document.refreshForm.visited.value = "1"; // You may want to add code here special for // fresh page loads } else { // This is a page refresh // Insert code here representing what to do on // a refresh } } <html> <body onLoad="JavaScript:checkRefresh();"> <form name="refreshForm"> <input type="hidden" name="visited" value="" /> </form> </body> </html>
<script>
var currpage = window.location.href;
var lasturl = sessionStorage.getItem("last_url");
if(lasturl == null || lasturl.length === 0 || currpage !== lasturl ){
sessionStorage.setItem("last_url", currpage);
alert("New page loaded");
}else{
alert("Refreshed Page");
}
</script>