Question
We have a web app where the users can navigate some nested folders and make changes to the items in the folders. The problem is that when the users use the browser back button, the page is restored from the browser back/forward cache and it displays an outdated view.
We already tried setting the HTTP cache headers (e.g. Cache-Control: no-cache
) but they don’t have any effect in this case.
Is there any solution to detect when the user clicks the browser back button?
Is it possible to detect when the page is restored from the back/forward cache?
Answer
There is a simple solution based on the pageshow
event and the persisted
property:
window.addEventListener('pageshow', (event) => {
if (event.persisted) {
console.log('Page restored from the bfcache');
} else {
console.log('Page loaded normally');
}
});
This solution works on all major browsers (including Chrome, Firefox and Safari) and it allows to detect the usage of the browser back button.
You can find more information about the bfcache on Google Developers.