原文 https://www.jb51.net/article/161965.htm
1 利用window.name属性在页面刷新时不会重置判断(在该属性空置的情况下可使用)
2 使用sessionStorage或cookie来判断
与window.name实现方法类似在首次加载时设置一个固定值 之后判断即可
这里以sessionStorage来为例
1
2
3
4
5
6
|
if
(sessionStorage.getItem(
"isReload"
)){
console.log(
"页面被刷新"
);
}
else
{
console.log(
"首次被加载"
);
sessionStorage.setItem(
"isReload"
,
true
)
}
|
3 可以使用window.chrome对象 (该方法只在谷歌浏览器中可用 其他浏览器无chrome对象)
该对象提供了一个loadTimes() 方法 执行该方法我们会得到一个有关页面性能的对象
其中有一个navigationType属性可以帮助我们判断页面是加载还是刷新
它有两个值 Reload(刷新) 和 Other(首次加载)
所以我们可以通过if判断:
1
2
3
4
5
6
|
if
(sessionStorage.getItem(
"isReload"
)){
console.log(
"页面被刷新"
);
}
else
{
console.log(
"首次被加载"
);
sessionStorage.setItem(
"isReload"
,
true
)
}
|
使用window.chrome.loadTimes方法会报警告
isreload.html:20 [Deprecation] chrome.loadTimes() is deprecated, instead use standardized API: Navigation Timing 2. https://www.chromestatus.com/features/5637885046816768.
官方已经说明该方法被弃用了 让我们使用 标准化API: Navigation Timing 2
所有上面代码需要改下:
1
2
3
4
5
|
if
(window.performance.navigation.type == 1) {
console.log(
"页面被刷新"
)
}
else
{
console.log(
"首次被加载"
)
}
|
总结