我想检查何时有人尝试刷新页面。
例如,当我打开一个页面时,什么都没有发生,但是当我刷新页面时,它应该显示一个警报。
⚠️⚠️⚠️window.performance.navigation.type
已弃用,请参阅Илья Зеленько的答案
了解页面实际重新加载的更好方法是使用大多数现代浏览器支持的 navigator 对象。
它使用导航计时 API。
//check for Navigation Timing API support
if (window.performance) {
console.info("window.performance works fine on this browser");
}
console.info(performance.navigation.type);
if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {
console.info( "This page is reloaded" );
} else {
console.info( "This page is not reloaded");
}
来源:https ://developer.mozilla.org/en-US/docs/Web/API/Navigation_timing_API
window.performance.navigation
导航计时级别 2规范中已弃用该属性。请改用界面。PerformanceNavigationTiming
这是一项实验技术。
在生产中使用它之前,请仔细检查浏览器兼容性表。
const pageAccessedByReload = (
(window.performance.navigation && window.performance.navigation.type === 1) ||
window.performance
.getEntriesByType('navigation')
.map((nav) => nav.type)
.includes('reload')
);
alert(pageAccessedByReload);
type 只读属性返回一个表示导航类型的字符串。该值必须是以下之一:
导航- 通过单击链接、在浏览器的地址栏中输入 URL、提交表单或通过除 reload 和 back_forward 之外的脚本操作进行初始化来启动导航,如下所列。
reload — 导航是通过浏览器的重新加载操作或location.reload()
.
back_forward — 导航是通过浏览器的历史遍历操作。
prerender — 导航由预渲染提示启动。
此属性是只读的。
function print_nav_timing_data() {
// Use getEntriesByType() to just get the "navigation" events
var perfEntries = performance.getEntriesByType("navigation");
for (var i=0; i < perfEntries.length; i++) {
console.log("= Navigation entry[" + i + "]");
var p = perfEntries[i];
// dom Properties
console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart));
console.log("DOM complete = " + p.domComplete);
console.log("DOM interactive = " + p.interactive);
// document load and unload time
console.log("document load = " + (p.loadEventEnd - p.loadEventStart));
console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart));
// other properties
console.log("type = " + p.type);
console.log("redirectCount = " + p.redirectCount);
}
}
第一步是检查sessionStorage
一些预定义的值,如果它存在警报用户:
if (sessionStorage.getItem("is_reloaded")) alert('Reloaded!');
第二步是设置sessionStorage
某个值(例如true
):
sessionStorage.setItem("is_reloaded", true);
会话值一直保留到页面关闭,因此只有在页面重新加载到站点的新选项卡中时才会起作用。您也可以以相同的方式保持重新加载计数。
在有人第一次访问该页面时存储一个 cookie。刷新时检查您的 cookie 是否存在,如果存在,则发出警报。
function checkFirstVisit() {
if(document.cookie.indexOf('mycookie')==-1) {
// cookie doesn't exist, create it now
document.cookie = 'mycookie=1';
}
else {
// not first visit, so alert
alert('You refreshed!');
}
}
在你的身体标签中:
<body onload="checkFirstVisit()">
我编写了这个函数来同时检查使用新旧两种window.performance.navigation
方法performance.getEntriesByType("navigation")
:
function navigationType(){
var result;
var p;
if (window.performance.navigation) {
result=window.performance.navigation;
if (result==255){result=4} // 4 is my invention!
}
if (window.performance.getEntriesByType("navigation")){
p=window.performance.getEntriesByType("navigation")[0].type;
if (p=='navigate'){result=0}
if (p=='reload'){result=1}
if (p=='back_forward'){result=2}
if (p=='prerender'){result=3} //3 is my invention!
}
return result;
}
结果说明:
0:点击链接,在浏览器地址栏输入网址,提交表单,点击书签,通过脚本操作进行初始化。
1:单击重新加载按钮或使用Location.reload()
2:使用浏览器历史记录(Bakc 和 Forward)。
3:预渲染活动,如<link rel="prerender" href="//example.com/next-page.html">
4:任何其他方法。
I found some information here Javascript Detecting Page Refresh . His first recommendation is using hidden fields, which tend to be stored through page refreshes.
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>
如果
event.currentTarget.performance.navigation.type
返回
0 => 用户刚刚输入了一个 URL
1 => 页面重新加载
2 => 点击了返回按钮。
我在这里找到了一些信息 Javascript Detecting Page Refresh
function UnLoadWindow() {
return 'We strongly recommends NOT closing this window yet.'
}
window.onbeforeunload = UnLoadWindow;
这是几乎所有浏览器都支持的方法:
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来检查页面是第一次打开还是刷新。
if(sessionStorage.reload) {
sessionStorage.reload = true;
// optionnal
setTimeout( () => { sessionStorage.setItem('reload', false) }, 2000);
} else {
sessionStorage.setItem('reload', false);
}
在控制台中附加以下脚本:
window.addEventListener("beforeunload", function(event) {
console.log("The page is redirecting")
debugger;
});
<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>
document.addEventListener("keydown", (e)=>{
if (e.keyCode === 116) {
e.preventDefault();
// your code here
// var r = confirm("Reload!");
// if (r == true)
// window.location.reload();
}
})