10LOC

#spa

Chrome APIsadvanced

The Navigation API for SPA routing without a router library

// TypeScript's DOM lib has neither URLPattern nor the Navigation API yet --
// narrow casts for just the shapes this snippet actually uses.
type UrlMatch = { pathname: { groups: Record<string, string | undefined> } };
type UrlPatternLike = { test: (i: { pathname: string }) => boolean; exec: (i: { pathname: string }) => UrlMatch | null };
const URLPattern = (globalThis as any).URLPattern as new (init: { pathname: string }) => UrlPatternLike;

navigation.addEventListener('navigate', ...) intercepts every link click and history change from one place — the primitive most routers wrap.