How do you capture browser back button?
Assesses fundamental understanding of JavaScript conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
The beforeunload event is triggered when the window, the document and its resources are about to be unloaded. This event is helpful to warn users about losing the current data and detect back button event.
window.addEventListener("beforeunload", () => {
console.log("Clicked browser back button");
});
You can also use popstate event to detect the browser back button.
Note: The history entry has been activated using history.pushState method.
window.addEventListener("popstate", () => {
console.log("Clicked browser back button");
box.style.backgroundColor = "white";
});
const box = document.getElementById("div");
box.addEventListener("click", () => {
box.style.backgroundColor = "blue";
window.history.pushState({}, null, null);
});
In the preceeding code, When the box element clicked, its background color appears in blue color and changed to while color upon clicking the browser back button using popstate event handler. The state property of popstate contains the copy of history entry's state object.
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.