A client-side router keeps one document and swaps views, while making the address bar and back button behave as if pages changed. The History API gives it two pieces:
history.pushState(state, unused, url)adds a session history entry for the same document and sets the URL. Nothing is fetched, nothing unloads, and no event fires, so the router renders the new view itself.replaceState()does the same without adding an entry: use it for redirects and for filter or tab changes that shouldn't add a back step.popstatefires onwindowwhen a traversal (back, forward,history.go()) lands on another entry of the same document. The router renders fromlocationand readsevent.state, the clone of what was pushed. A traversal to an entry that belongs to another document loads or restores that document instead; nopopstatefires.
The router also has to handle:
- Clicks. Listen for
clickon the document, ignore anything that isn't a plain left click on a same-origin link withouttargetor modifier keys, thenpreventDefault()to cancel the navigation. - First load. Render from
locationat startup. Current browsers don't firepopstateon load. - Deep links. A reload or shared link requests
/aboutfrom the server, which must return the app shell for every route. - Scroll, focus, title. Update
document.title, move focus to the new content, and decide on scrolling.
Rules worth knowing: the state is stored with StructuredSerializeForStorage, so functions and DOM nodes throw DataCloneError; a URL with another scheme, host or port throws SecurityError; and history.state survives a reload.
Framework routers wrap these same calls. The Navigation API replaces the click interception with one navigate event.