Categories
JavaScript Answers

How to detect browser back button click with JavaScript?

Spread the love

Sometimes, we want to detect browser back button click with JavaScript.

In this article, we’ll look at how to detect browser back button click with JavaScript.

How to detect browser back button click with JavaScript?

To detect browser back button click with JavaScript, we listen the popstate event.

For instance, we write

window.onpopstate = () => {
  alert("clicked back button");
};
history.pushState({}, "");

to set the window.onpopstate property to a function that calls alert to show an alert.

The method is called when we click the back button on the browser.

Conclusion

To detect browser back button click with JavaScript, we listen 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 *