For clarification: I am not trying to differentiate between a refresh and a reload, hence this is not a duplicate of refresh vs reload. I am trying to find out if there is a way to detect when a user triggers a hard reload instead of a normal reload. I am asking because I want to execute some code prior to a hard reload only.
Using JavaScript, via the browsers' reload button, or by a shortcut like Shift+Ctrl+R it is possible to perform a hard reload of a browser tab. Is it possible to detect such a hard reload with JavaScript and if so how?
I know one can detect when a normal reload event is triggered with the onbeforeunload
event and I can find out the navigation type to differentiate between a refresh and a reload but I am unable to detect a hard reload.
So far I'am using the following JS code to detect a reload:
window.addEventListener('beforeunload', function (e) {
// Cancel the event
e.preventDefault();
// Chrome requires returnValue to be set
e.returnValue = '';
// For older browsers
console.log('Is reloading?', event.currentTarget.performance.navigation.type === 1);
// For modern browsers
const perfEntries = performance.getEntriesByType("navigation");
for (let i = 0; i < perfEntries.length; i++) {
console.log('Is reloading? ', perfEntries[i].type === 1);
}
});
I would like to be able to distinguish between a normal reload, e.g., location.reload()
, and a forced reload, e.g., location.reload(true)
.