[英]How to get check if a page gets reloaded with js
How do you now check if a page gets reloaded?您现在如何检查页面是否重新加载?
It used to be like this:以前是这样的:
//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"); }
But now I found out that navigation type is deprecated: https://developer.mozilla.org/en-US/docs/Web/API/Performance/navigation但现在我发现导航类型已被弃用: https://developer.mozilla.org/en-US/docs/Web/API/Performance/navigation
So then I checked the replacement: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming然后我检查了替换: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming
Even after reading it it's still not very clear on how I could accomplish this.即使在阅读之后,我仍然不太清楚我是如何做到这一点的。 So how does the new way work of checking if a page gets refreshed?
那么检查页面是否刷新的新方法是如何工作的呢?
I also tried this after I had read it:我读过之后也试过这个:
if (PerformanceNavigationTiming.type == "reload") { alert('page reloaded') }
But then the alert won't be displayed.但随后将不会显示警报。
And after that I tried this:之后我尝试了这个:
if (PerformanceNavigationTiming.type == PerformanceNavigationTiming.TYPE_RELOAD) { alert('page reloaded') }
But then It would display the alert also without a page refresh.但是它也会在没有页面刷新的情况下显示警报。
Then the last thing I tried:然后我尝试的最后一件事:
const pageAccessedByReload = ( (PerformanceNavigationTiming && PerformanceNavigationTiming.TYPE === 1) || window.performance.getEntriesByType('navigation').map((nav) => nav.type).includes('reload') ); alert(pageAccessedByReload);
But this also gives me an alert either false when it's not reloaded and true when it is reloaded.但这也给了我一个警报,要么在未重新加载时为假,在重新加载时为真。 And I only want that alert when the page is reloaded.
而且我只希望在重新加载页面时发出警报。
You must remember to always pay attention when reading a new API docs, type in PerformanceNavigationTiming is a string and not a number so the correct way would be:您必须记住在阅读新的 API 文档时始终注意,输入 PerformanceNavigationTiming 是一个字符串而不是数字,因此正确的方法是:
if (window.PerformanceNavigationTiming) { console.info("window.performance works fine on this browser"); if (PerformanceNavigationTiming.type === "reload") { console.info("This page is reloaded"); } else { console.info("This page is not reloaded"); } }
I have finally found a solution:我终于找到了解决方案:
const pageAccessedByReload = ( (PerformanceNavigationTiming && PerformanceNavigationTiming.TYPE === 1) || window.performance.getEntriesByType('navigation').map((nav) => nav.type).includes('reload') ); if (pageAccessedByReload == true) { alert(pageAccessedByReload); }
Now it will only show when the page is refreshed.现在它只会在页面刷新时显示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.