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.