window.history lets you move through the session history (back(), forward(), go(n)) and change the URL without reloading (pushState() adds an entry, replaceState() overwrites the current one). When the user presses Back/Forward between entries you created, the browser fires popstate and your code must render the matching view. This is the foundation of client-side routing in SPAs. The newer Navigation API (window.navigation) is a more complete replacement (shipped first in Chromium, with other engines following).
history.length; // entries in this tab's session history
history.back(); // like the Back button
history.forward();
history.go(-2); // relative jump; go(0) reloads
history.pushState({ productId: 42 }, '', '/products/42'); // new entry
history.replaceState({ ...history.state, tab: 'reviews' }, '', '?tab=reviews'); // update current
history.state; // state object of the current entry
history.scrollRestoration = 'manual'; // take control of scroll on traversal
title) is ignored by browsers; pass ''.SecurityError is thrown.pushState doesn't fire popstate and doesn't load anything. You update the UI yourself.function render(path) {
const view = routes[path] ?? routes['/404'];
document.querySelector('main').replaceChildren(view());
}
document.addEventListener('click', (e) => {
const a = e.target.closest('a[href]');
if (!a || a.origin !== location.origin || a.target || e.metaKey || e.ctrlKey || e.shiftKey) return;
e.preventDefault();
history.pushState({}, '', a.href);
render(location.pathname);
});
window.addEventListener('popstate', () => render(location.pathname));
render(location.pathname);
Respecting modifier keys keeps "open in new tab" working, and using real <a href> keeps links crawlable and accessible.
document.title per route./products/42 must return the app shell (or SSR content) from the server, not a 404.hashchange and #/route URLs are the legacy approach, still useful for static hosting without rewrites.navigation.addEventListener('navigate', (event) => {
if (!event.canIntercept || event.hashChange) return;
event.intercept({ handler: () => render(new URL(event.destination.url).pathname) });
});
It centralises link clicks, form submissions and back/forward into one event, and supports navigation.entries() and abortable navigations. Check support before relying on it, and keep a History API fallback.
pushState/replaceState don't fire popstate; traversal does.Spotted a mistake or a rights concern? Report an issue