检查页面是否在 JavaScript 中重新加载或刷新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5004978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if page gets reloaded or refreshed in JavaScript
提问by Ahmed
I want to check when someone tries to refresh a page.
我想检查何时有人尝试刷新页面。
For example, when I open a page nothing happens but when I refresh the page it should display an alert.
例如,当我打开一个页面时什么也没有发生,但是当我刷新页面时它应该显示一个警报。
回答by Rahul Jain
A better way to know that the page is actually reloaded is to use the navigator object that is supported by most modern browsers.
了解页面实际重新加载的更好方法是使用大多数现代浏览器支持的导航器对象。
It uses the Navigation Timing API.
它使用导航计时 API。
//check for Navigation Timing API support
if (window.performance) {
console.info("window.performance works fine on this browser");
}
if (performance.navigation.type == 1) {
console.info( "This page is reloaded" );
} else {
console.info( "This page is not reloaded");
}
source : https://developer.mozilla.org/en-US/docs/Web/API/Navigation_timing_API
来源:https: //developer.mozilla.org/en-US/docs/Web/API/Navigation_timing_API
回答by DitherSky
First step is to check sessionStorage
for some pre-defined value and if it exists alert user:
第一步是检查sessionStorage
一些预定义的值,如果它存在警报用户:
if (sessionStorage.getItem("is_reloaded")) alert('Reloaded!');
Second step is to set sessionStorage
to some value (for example true
):
第二步是设置sessionStorage
某个值(例如true
):
sessionStorage.setItem("is_reloaded", true);
Session values kept until page is closed so it will work only if page reloaded in a new tab with the site. You can also keep reload count the same way.
会话值一直保留到页面关闭,因此只有在站点的新选项卡中重新加载页面时,它才会工作。您也可以以相同的方式保持重新加载计数。
回答by Илья Зеленько
New standard 2018-now (PerformanceNavigationTiming)
新标准 2018-现在(PerformanceNavigationTiming)
window.performance.navigation
property is deprecatedin the Navigation Timing Level 2specification. Please use the PerformanceNavigationTiming
interface instead.
window.performance.navigation
属性在Navigation Timing Level 2规范中被弃用。请改用接口。PerformanceNavigationTiming
PerformanceNavigationTiming.type
PerformanceNavigationTiming.type
This is an experimental technology.
这是一项实验技术。
Check the Browser compatibility tablecarefully before using this in production.
在生产中使用它之前,请仔细检查浏览器兼容性表。
Support on 2019-07-08
支持 2019-07-08
The type read-only property returns a string representing the type of navigation. The value must be one of the following:
type 只读属性返回一个表示导航类型的字符串。该值必须是以下之一:
navigate— Navigation started by clicking a link, entering the URL in the browser's address bar, form submission, or initializing through a script operation other than reload and back_forward as listed below.
reload— Navigation is through the browser's reload operation or
location.reload()
.back_forward— Navigation is through the browser's history traversal operation.
prerender— Navigation is initiated by a prerender hint.
导航- 通过单击链接、在浏览器的地址栏中输入 URL、提交表单或通过脚本操作初始化而不是 reload 和 back_forward 来启动导航,如下所列。
重新加载- 导航是通过浏览器的重新加载操作或
location.reload()
.back_forward— 导航是通过浏览器的历史遍历操作。
预渲染- 导航由预渲染提示启动。
This property is Read only.
此属性为只读。
The following example illustrates this property's usage.
以下示例说明了此属性的用法。
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);
}
}
回答by techfoobar
Store a cookie the first time someone visits the page. On refresh check if your cookie exists and if it does, alert.
在有人第一次访问该页面时存储一个 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!');
}
}
and in your body tag:
并在您的身体标签中:
<body onload="checkFirstVisit()">
回答by nPcomp
if
如果
event.currentTarget.performance.navigation.type
returns
返回
0 => user just typed in an Url
1 => page reloaded
2 => back button clicked.
0 => 用户刚刚输入了一个 URL
1 => 页面重新加载
2 => 单击后退按钮。
回答by VoronoiPotato
I found some information here Javascript Detecting Page Refresh. His first recommendation is using hidden fields, which tend to be stored through page refreshes.
我在这里找到了一些信息Javascript Detecting Page Refresh。他的第一个建议是使用隐藏字段,这些字段往往通过页面刷新进行存储。
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>
回答by Ali Sheikhpour
I have wrote this function to check both methods using old window.performance.navigation
and new performance.getEntriesByType("navigation")
in same time:
我编写了这个函数来同时使用旧的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;
}
Result description:
结果说明:
0:clicking a link, Entering the URL in the browser's address bar, form submission, Clicking bookmark, initializing through a script operation.
0:点击链接,在浏览器地址栏中输入网址,提交表单,点击书签,通过脚本操作初始化。
1:Clicking the Reload button or using Location.reload()
1:单击重新加载按钮或使用Location.reload()
2:Working with browswer history (Bakc and Forward).
2:使用浏览器历史记录(Bakc 和 Forward)。
3:prerendering activity like <link rel="prerender" href="//example.com/next-page.html">
3:预渲染活动如<link rel="prerender" href="//example.com/next-page.html">
4:any other method.
4:任何其他方法。
回答by Manpreet
I found some information here Javascript Detecting Page Refresh
我在这里找到了一些信息 Javascript Detecting Page Refresh
function UnLoadWindow() {
return 'We strongly recommends NOT closing this window yet.'
}
window.onbeforeunload = UnLoadWindow;
回答by Alexis Gatuingt
if(sessionStorage.reload) {
sessionStorage.reload = true;
// optionnal
setTimeout( () => { sessionStorage.setItem('reload', false) }, 2000);
} else {
sessionStorage.setItem('reload', false);
}