Sometimes, we want to force reloading a page when using browser back button with JavaScript.
In this article, we’ll look at how to force reloading a page when using browser back button with JavaScript.
How to force reloading a page when using browser back button with JavaScript?
To force reloading a page when using browser back button with JavaScript, we watch the pageshow event.
For instance, we write
window.addEventListener("pageshow", (event) => {
const historyTraversal =
event.persisted ||
(typeof window.performance != "undefined" &&
window.performance.navigation.type === 2);
if (historyTraversal) {
window.location.reload();
}
});
to call window.addEventListener to watch for the 'pageshow' event.
In the event listener, we check if we navigated with
const historyTraversal =
event.persisted ||
(typeof window.performance != "undefined" &&
window.performance.navigation.type === 2);
If that’s true, then we call window.location.reload to reload the page.
Conclusion
To force reloading a page when using browser back button with JavaScript, we watch the pageshow event.