我想检查当有人尝试刷新页面时。
例如,当我打开页面时,什么也不会发生,但当我刷新页面时,它应该显示一个警报。
我想检查当有人尝试刷新页面时。
例如,当我打开页面时,什么也不会发生,但当我刷新页面时,它应该显示一个警报。
⚠️⚠️⚠️ window.performance.navigation.type
已被弃用,请参见Илья Зеленько的答案。
更好的方法是使用大多数现代浏览器支持的navigator对象来知道页面是否已经重新加载。
//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");
}
来源: 导航计时API
performance.navigation.type == performance.navigation.TYPE_RELOAD
更易于阅读,而不是 == 1
。此外,如果您检查 performance.navigation
,您会发现有4种不同的导航类型,例如 TYPE_BACK_FORWARD
、TYPE_NAVIGATE
。 - Vitalij Kornijenkowindow.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 是只读属性,返回一个字符串,表示导航的类型。这个值必须是以下之一:
navigate — 通过点击链接、在浏览器地址栏输入 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);
}
}
getEntriesByType('navigation')
输入项。为什么您要使用 .map
而不是直接使用第一个输入项?在某些情况下是否可能获取多个输入项?我很想了解更多,请解释一下。 - Ashutosh Biswas第一步是检查{{link1:sessionStorage
}}是否存在预定义的值,如果存在,则向用户发出警报:
if (sessionStorage.getItem("is_reloaded")) alert('Reloaded!');
sessionStorage
设置为某个值(例如true
):sessionStorage.setItem("is_reloaded", true);
会话值保留直到页面关闭,因此仅在使用新标签页重新加载站点时才起作用。您也可以以同样的方式保持重新加载计数。
true
会被转换为 "true"
。
2)会话存储会持续到用户关闭浏览器窗口,因此您无法区分页面重新加载和在同一浏览器会话中导航离开并返回您的站点之间的区别。 - Hector在第一次访问页面时存储一个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标签中:
<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>
Uncaught TypeError: Cannot read property 'visited' of undefined
。 - vallentin以下是几乎所有浏览器都支持的方法:
if (sessionStorage.getItem('reloaded') != null) {
console.log('page was reloaded');
} else {
console.log('page was not reloaded');
}
sessionStorage.setItem('reloaded', 'yes'); // could be anything
这个实现对我有所帮助:
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 匹配,并且存储的时间与当前时间匹配(可能有微小偏差),则说明用户进行了页面重新加载。
window.performance.navigation.type
已经被弃用,请参考我的答案。 - Илья Зеленько