The popstate Event
Respond to browser back and forward navigation.
What popstate Does
The popstate event fires on the window when the user navigates through the history (back, forward, or a JavaScript history.back call). It lets the SPA re-render the right view in response to browser-initiated navigation.
When It Fires
popstate fires on back/forward button clicks, history.back(), history.forward(), and history.go(n). It does NOT fire when pushState/replaceState are called manually — those are programmatic updates and the page already knows about them.
window.addEventListener("popstate", (e) => {
console.log("Navigated to", location.pathname, "state:", e.state);
renderPage(location.pathname);
});