history: Browser Navigation and SPA RoutingThe JavaScript window.history object lets your code move backward or forward through the current tab's session history and update URLs without full page reloads. Modern Single Page Applications (SPAs) rely on history.pushState() and popstate to keep client routes synced with browser Back and Forward buttons.
history.back() / history.forward(): Moves one step backward or forward, identical to clicking the browser toolbar buttons.history.go(delta): Jumps relative steps (history.go(-2) goes back two pages; history.go(0) reloads).history.pushState(stateObj, "", url): Appends a new same-origin URL entry to browser history without fetching from the server.history.replaceState(stateObj, "", url): Updates the current history entry URL/state without adding a new Back step.popstateflowchart TD
Click["User clicks SPA link"] --> Push["history.pushState(state, '', '/next')"]
Push --> Render["Render new view in JS"]
BackBtn["User clicks Browser Back"] --> Pop["window fires popstate event"]
Pop --> Render2["Read location.pathname & re-render"]
Notice that calling pushState() does not fire the popstate event automatically—popstate fires only when the user clicks Back/Forward or your code calls history.back().
console.log("Tab history entries:", history.length);
// Update URL query filter cleanly without triggering a page reload
const url = new URL(window.location.href);
url.searchParams.set("tab", "syntax");
// In a live page: history.replaceState({ tab: "syntax" }, "", url);
window.addEventListener("popstate", (event) => {
console.log("Navigated via history! State:", event.state);
});
history from other tabs or sites: For security and privacy, history only exposes history.length—JavaScript cannot read the list of URLs the user visited earlier.pushState(): pushState() strictly requires a same-origin URL; changing protocol or hostname throws a SecurityError.pushState() URLs: If a user refreshes /tutorials/js/closures pushed by pushState(), the server must serve your SPA shell (or SSR page) instead of returning a 404."" in history.pushState(state, "", url)?It is a legacy title argument ignored by all modern browsers; passing an empty string "" is the standard practice while setting document.title directly.
replaceState() instead of pushState()?Use replaceState() when updating search filters, scroll offsets, or pagination state where hitting the Back button ten times to undo tiny filter tweaks would annoy users.
state object of pushState()?Most browsers allow several megabytes of structured-cloneable data, though keeping state small (IDs, tab names, filter keys) is best for memory.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.