JavaScript

How to Detect Browser Back Button Event

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.

Example

In the HTML body tag, call the “onbeforeunload” event and invoke the function “backButtonEvent()”:

<body onbeforeunload = "backButtonEvent()">

 
In the JavaScript file, define a function that will be invoked when the onbeforeunload event gets triggered and print the message in console:

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:


We have compiled all the necessary information related to detecting the browser back button event in JavaScript.

Conclusion

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.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.