如何在JavaScript中检查页面是否被重新加载或刷新

396 阅读1分钟

有时,我们想检查页面是否被重新加载或刷新。

一个页面可以通过以下方式被刷新或重新加载:

  • 用户按下F5键
  • 使用location.reload()重新加载页面
  • 从浏览器中按下后退或前进按钮
  • 在浏览器中输入URL
  • 或点击一个链接来重新加载一个特定的页面
  • 提交表单
  • 预先渲染一个页面

检查页面是否在javascript中被重新加载或刷新?

Javascript提供了一个window.performance.navigation对象,所有最新的浏览器都支持这个对象。

window.performance.navigation提供了重新加载的类型。

console.log(window.performance.navigation);//PerformanceNavigation {type: 1, redirectCount: 0}
console.log(window.performance.getEntriesByType("navigation")); //

输出:

PerformanceNavigation {type: 1, redirectCount: 0}
[PerformanceNavigationTiming]0: PerformanceNavigationTimingconnectEnd: 0.5connectStart: 0.5decodedBodySize: 0domComplete: 2165.699999988079domContentLoadedEventEnd: 2165.5domContentLoadedEventStart: 2165.5domInteractive: 2165.5domainLookupEnd: 0.5domainLookupStart: 0.5duration: 2165.699999988079encodedBodySize: 0entryType: "navigation"fetchStart: 0.5initiatorType: "navigation"loadEventEnd: 2165.699999988079loadEventStart: 2165.699999988079name: ""nextHopProtocol: ""redirectCount: 0redirectEnd: 0redirectStart: 0requestStart: 0.5responseEnd: 3.100000023841858responseStart: 0.5secureConnectionStart: 0serverTiming: []startTime: 0transferSize: 300type: "reload"unloadEventEnd: 0unloadEventStart: 0workerStart: 0[[Prototype]]: PerformanceNavigationTiminglength: 1[[Prototype]]: Array(0)

它返回四个值 0,1,2,3 0表示页面使用表单提交重新加载或首次加载 1使用刷新或location.reload()重新加载页面 2用户点击了后退和前进历史按钮 3使用prerender方式加载

let data=window.performance.getEntriesByType("navigation")[0].type;
console.log(data);

输出:

reload

你也可以检查其他使用会话或cookie存储时间的方式,并将以前的时间戳与当前的戳进行比较,以知道页面被重新加载。但是,你不能知道哪种类型会导致页面重新加载。