How to Detect Back Button Events in JavaScript

How to Detect Back Button Events in JavaScript

D
dongAuthor
2 min read

What happens when a user clicks the browser’s back button? We often think of the “back” action as simply “navigating to the previous page.” However, if we look a bit deeper, we find that this brief moment can involve a multitude of user experience issues. A draft message might disappear, a payment process could be interrupted, or even critical data might be lost. 😰

Today, let’s walk through how to detect back button events using JavaScript and improve the user experience step by step. 🚀

Handling with the popstate Event

Browsers trigger a popstate event when the URL changes or the session history is modified.

Using this event, we can detect whether the user has pressed the back button.

The popstate event is fired when the active history entry changes due to the user navigating through session history. If the activated entry was created by history.pushState() or history.replaceState(), then the event’s state property will contain a copy of the state object associated with that history entry.

Here’s how you can use it!

javascript

window.addEventListener("popstate", (event) => {
  console.log("Back button pressed!", event);
});

Be careful—behavior may vary across browsers!

popstate compatibility screenshot

Browsers handle the popstate event differently on page load. For instance, Chrome (before version 34) and Safari trigger the popstate event when the page loads, while Firefox does not.

Need an interrupt like alert? Handle with the beforeunload event

Alternatively, you can use the beforeunload event. This event fires when the window, document, or its resources are about to be unloaded! 💪

window.addEventListener("beforeunload", (e) => {
  const message = "Your current input may be lost. Are you sure you want to leave?";
  e.returnValue = message; // Works in most browsers
  return message;
});

You can apply this depending on the situation! 😉


For high-quality, AI-powered translations in 100+ languages, I recommend using HIX Translate — powered by ChatGPT 3.5/4.

How to Detect Back Button Events in JavaScript | devdong