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
So then I checked the replacement: 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:
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");
}
}