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.
One reply on “How to force reloading a page when using browser back button with JavaScript?”
Hi,
I tried this function on my website here: https://ipostal1.com/contact.php trying to force the page to refresh to the original dropdown when someone selects “Become an iPostal1 customer” but it does work as intended. Any suggestions would be appreciated.
Thank you,
Eddie