我想检查何时有人尝试刷新页面。
例如,当我打开一个页面时没有任何反应,但是当我刷新页面时它应该显示一个警报。
⚠️⚠️⚠️
window.performance.navigation.type
已弃用。请参阅Илья Зеленько 的回答.
了解页面实际重新加载的更好方法是使用大多数现代浏览器支持的导航器对象。
//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");
}
window.performance.navigation
属性在 Navigation Timing Level 2 规范中被 deprecated。请改用PerformanceNavigationTiming
界面
这是一个实验技术.
在生产中使用之前,请仔细检查浏览器兼容性表。
const pageAccessedByReload = (
(window.performance.navigation && window.performance.navigation.type === 1) ||
window.performance
.getEntriesByType('navigation')
.map((nav) => nav.type)
.includes('reload')
);
alert(pageAccessedByReload);
type 只读属性返回表示导航类型的字符串。该值必须是以下之一:
navigate——通过单击链接开始导航,在浏览器的地址栏中输入 URL,提交表单,或通过除下面列出的重新加载和 back_forward 之外的脚本操作进行初始化。
location.reload()
.
back_forward — 导航是通过浏览器的历史遍历操作。
prerender — 导航由 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) {
// The cookie doesn't exist. Create it now
document.cookie = 'mycookie=1';
}
else {
// Not the 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:点击链接,在浏览器地址栏输入URL,提交表单,点击书签,通过脚本操作初始化。
1: 单击重新加载按钮或使用
Location.reload()
2: 使用浏览器历史记录(前后)。
3:预渲染活动像
<link rel="prerender" href="//example.com/next-page.html">
4:任何其他方法。
如果
event.currentTarget.performance.navigation.type
退货
0 => 用户刚刚输入了一个 URL
1 => 页面重新加载
2 => 单击后退按钮。
我在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>
这是一个几乎所有浏览器都支持的方法:
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来检查页面是否是第一次打开或者是否被刷新。
这个实现帮助了我:
来自 MDN 参考 2022:Navigation Timing Level 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.performance.navigation
):
使用
window.onbeforeunload
在用户离开页面(可能刷新页面)时存储当前页面的时间和URL(在本地存储中)。
window.onbeforeunload = function(e)
{
localStorage.setItem('reload-url', window.location.href);
}
然后使用
window.onload
从本地存储中获取这些值。
window.onload = function(e)
{
if (localStorage.getItem('reload-url') != null))
{
if (window.location.href == localStorage.getItem('reload-url'))
{
console.log('Reload');
}
}
}
如果最近的 URL 与存储的 URL 匹配并且存储的时间与当前时间匹配(可能有微小的偏移量)那么这是用户重新加载页面。
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();
}
})