While testing the web application, programmers need to track every step. For instance, going back to the previous page or refreshing the page using the browser’s buttons at the top left corner of your browser are denoted by arrows (forward arrow, backward arrow, loop arrow). More specifically, they may want to detect browser back button events.
This article will describe the procedure to detect browser back button events.
How to Detect Browser Back Button Event?
To detect browser back button events, use the “onbeforeunload” event. This event is triggered while the page is getting ready to unload. It enables you to show a message in a confirmation dialogue box informing the user whether you want to stay on the current page or leave it. You can also utilize this event for detecting the back button press event.
In the HTML body tag, call the “onbeforeunload” event and invoke the function “backButtonEvent()”:
console.log("Browser back button is clicked...");
Here, you can see when the back button of the browser is clicked, a message has been displayed on the console before moving back:
To detect browser back button events, use the “onbeforeunload” event. It occurs when the page is getting ready to be unloaded. Call this event in the <body> tag that will invoke the defined function on the onbeforeunload event. This article described the procedure to detect browser back button events.