How to Detect Back Button Events in JavaScript
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
popstateevent is fired when the active history entry changes due to the user navigating through session history. If the activated entry was created byhistory.pushState()orhistory.replaceState(), then the event’sstateproperty 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!
Browsers handle the
popstateevent differently on page load. For instance, Chrome (before version 34) and Safari trigger thepopstateevent 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.