Categories
JavaScript Answers

How to detect back button or hash change in URL with JavaScript?

Spread the love

Sometimes, we want to detect back button or hash change in URL with JavaScript.

In this article, we’ll look at how to detect back button or hash change in URL with JavaScript.

How to detect back button or hash change in URL with JavaScript?

To detect back button or hash change in URL with JavaScript, we listen to the popstate event.

For instance, we write

window.addEventListener("popstate", (event) => {
  console.log(document.location, event.state);
});

to call addEventListener to listen to the popstate event triggered by window.

In the event handler callback, we get the current location with document.location.

And we get the change made with event.state.

Conclusion

To detect back button or hash change in URL with JavaScript, we listen to the popstate event.

By John Au-Yeung

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

Leave a Reply

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