Categories
JavaScript Answers

How to force reloading a page when using browser back button with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to force reloading a page when using browser back button with JavaScript?”

Leave a Reply

Your email address will not be published. Required fields are marked *