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

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.