A router needs to handle link clicks, form submissions, history traversal, and code-initiated route changes without giving each one a separate rendering path. The Navigation API dispatches a navigate event on the global navigation object when a navigation begins. The event describes its destination and type, and indicates whether it can be intercepted. Navigation API support is Baseline 2026, so older browsers and web views still need a fallback. section 10.3.2 section 11.2
For a same-document router:
- Check event.canIntercept before taking over. Leave hash changes, downloads, cross-origin destinations, and unmatched routes to the browser. section 10.3.2
- For a matched route, call event.intercept() with a handler that loads and renders the view. The browser updates the URL and session history; the handler takes responsibility for the current document’s content. section 10.3.2
- If focusReset and scroll are set to "manual", move focus after rendering and call event.scroll() once the new DOM exists. Pass event.signal to asynchronous route work. section 10.3.2
Listing 10.1 Using the Navigation API to intercept same-document navigations
if ("navigation" in globalThis) {
navigation.addEventListener("navigate", (event) => {
if (!event.canIntercept || event.hashChange) return; #1
if (event.downloadRequest) return; #1
const url = new URL(event.destination.url);
if (url.origin !== location.origin) return; #1
// matchRoute is defined in a separate function.
const match = matchRoute(url.pathname);
if (!match) return; #2
event.intercept({
focusReset: "manual", #3
scroll: "manual", #3
async handler() {
const page = await match.handler(match.params, {
signal: event.signal #4
});
renderPage(page); #5
document.title = page.title;
focusMainHeading(); #6
event.scroll(); #7
}
});
});
}
A complete listener shows route matching, eligibility checks, rendering, focus management, and scroll restoration in one place. section 10.3.2
Forms use the same event. A GET submission puts its fields in event.destination.url as query parameters; a POST submission exposes submitted data through event.formData. The History API fallback does not intercept forms by itself, so supporting them in older browsers requires a separate submit listener. section 10.3.4 section 10.3.4
Navigate after a successful save
Call navigation.navigate() after saving to start the normal navigate-event flow rather than rendering the destination separately. Await its finished promise when the caller needs the intercepted handler to complete; committed only confirms that the URL and current entry changed. section 11.2
