
Predictable Single-Page Routing with the Browser Navigation API
For more than a decade, client-side routers relied on a fragile patchwork of the History API (history.pushState and popstate), delegated click event listeners on <a> tags, and custom scroll caches. Because history.pushState never fires popstate, application code had to duplicate navigation hooks everywhere URLs changed, manually ignore modifier-key clicks (Ctrl, Meta, middle-click) and download links, and guess whether a popstate event came from a forward or backward traversal. Worse still, client-side route swaps routinely broke accessibility by leaving keyboard focus stranded on a removed element or failing to announce the newly rendered page title to assistive technologies.
The browser window.navigation interface—standard across modern rendering engines—replaces those workarounds with a unified, asynchronous navigation lifecycle. A single navigate listener captures link clicks, form submissions, programmatic navigation.navigate() calls, and browser back/forward history traversals in one place. Calling event.intercept() automatically updates the URL, provides an AbortSignal (event.signal) that cancels stale in-flight fetch() requests if the user clicks another link mid-transition, and gives explicit lifecycle controls for scroll and focusReset. Combined with progressive enhancement—where standard server-rendered URLs work if window.navigation is absent or a route cannot be intercepted—single-page routing becomes dramatically smaller, race-free, and accessible by default.
Example
if ('navigation' in window) {
window.navigation.addEventListener('navigate', (event) => {
if (!event.canIntercept || event.hashChange || event.downloadRequest) {
return;
}
const destination = new URL(event.destination.url);
if (destination.origin !== location.origin) return;
event.intercept({
scroll: 'after-transition',
focusReset: 'after-transition',
async handler() {
const response = await fetch(destination.pathname, {
signal: event.signal,
headers: { 'X-Partial-Route': '1' }
});
if (!response.ok) throw new Error(`Route load failed: ${response.status}`);
document.querySelector('#app-main').innerHTML = await response.text();
}
});
});
}
Implementation
/**
* Progressive Navigation API Router
* Intercepts same-origin document navigations, aborts superseded fetches,
* restores scroll cleanly, and announces route changes to screen readers.
*/
export function initNavigationRouter({
outletSelector = '#app-main',
announcerSelector = '#route-announcer',
allowedPrefixes = ['/']
} = {}) {
if (!('navigation' in window)) {
// Graceful progressive enhancement: fall back to standard full-page loads
return () => {};
}
const outlet = document.querySelector(outletSelector);
const announcer = document.querySelector(announcerSelector);
if (!outlet) return () => {};
const isEligiblePath = (pathname) =>
allowedPrefixes.some((prefix) => pathname.startsWith(prefix));
const syncPageChrome = (doc, targetUrl) => {
const nextTitle = doc.querySelector('title')?.textContent?.trim();
if (nextTitle) {
document.title = nextTitle;
}
const incomingOutlet = doc.querySelector(outletSelector);
if (!incomingOutlet) {
throw new Error(`Missing ${outletSelector} in response for ${targetUrl.pathname}`);
}
outlet.replaceChildren(...incomingOutlet.childNodes);
// Update active navigation links for sighted and assistive tech users
document.querySelectorAll('nav a[href]').forEach((link) => {
const linkUrl = new URL(link.href, location.origin);
const isCurrent = linkUrl.pathname === targetUrl.pathname;
if (isCurrent) {
link.setAttribute('aria-current', 'page');
} else {
link.removeAttribute('aria-current');
}
});
// Move focus to the primary landmark or main heading when traversing routes
const heading = outlet.querySelector('h1');
const focusTarget = heading || outlet;
if (!focusTarget.hasAttribute('tabindex')) {
focusTarget.setAttribute('tabindex', '-1');
}
focusTarget.focus({ preventScroll: true });
if (announcer && nextTitle) {
announcer.textContent = `Navigated to ${nextTitle}`;
}
};
const onNavigate = (event) => {
// Let the browser handle downloads, cross-origin links, POST forms, or hash jumps
if (
!event.canIntercept ||
event.hashChange ||
event.downloadRequest ||
event.formData
) {
return;
}
const targetUrl = new URL(event.destination.url);
if (targetUrl.origin !== location.origin || !isEligiblePath(targetUrl.pathname)) {
return;
}
event.intercept({
scroll: 'after-transition',
focusReset: 'manual',
async handler() {
outlet.setAttribute('aria-busy', 'true');
try {
const response = await fetch(targetUrl.href, {
signal: event.signal,
headers: { Accept: 'text/html' }
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const html = await response.text();
const parsedDoc = new DOMParser().parseFromString(html, 'text/html');
if (document.startViewTransition) {
const transition = document.startViewTransition(() => {
syncPageChrome(parsedDoc, targetUrl);
});
await transition.finished;
} else {
syncPageChrome(parsedDoc, targetUrl);
}
} catch (error) {
if (error.name === 'AbortError') return;
// Fall back to hard navigation if partial parsing or network fails
location.assign(targetUrl.href);
} finally {
outlet.removeAttribute('aria-busy');
}
}
});
};
window.navigation.addEventListener('navigate', onNavigate);
return () => window.navigation.removeEventListener('navigate', onNavigate);
}
Main Point: The window.navigation API unifies link clicks, history traversals, request cancellation via event.signal, and deterministic scroll and focus lifecycle hooks behind one progressively enhanced browser primitive.
Credits
Photo by uve sanchez on Unsplash