Subscribing APIs

These APIs notify your JavaScript code when URL modifications or navigation events occur.


onPage

Subscribes to a specific route pattern. The callback triggers whenever the matched state transitions (e.g., active to inactive, or parameters change).

typescript
1function onPage(2    pattern: string,3    callback: (active: boolean, location: PageLocation) => void,4    exact: boolean = true,5    matchGroup?: string6): () => void

Example

javascript
1import { onPage } from '@beforesemicolon/router'2 3const unsubscribe = onPage('/users/:userId', (active, location) => {4    if (active) {5        console.log(`Now viewing user: ${location.params.userId}`)6        console.log('State payload:', location.data)7    } else {8        console.log('Navigated away from user profile')9    }10})11 12// Later: clean up listener13// unsubscribe();

Use exact = false to subscribe to a layout path and its descendants:

javascript
1onPage(2    '/docs',3    (active) => {4        docsShell.hidden = !active5    },6    false7)

onPageChange

Subscribes to all global location transitions. Triggered after any navigation event, regardless of which paths are active.

typescript
1type PageChangeCallback = (2    pathname: string,3    searchParams: Record<string, string>,4    pageData: Record<string, unknown>5) => void6 7function onPageChange(callback: PageChangeCallback): () => void

Example

javascript
1import { onPageChange } from '@beforesemicolon/router'2 3onPageChange((pathname, query, state) => {4    // Send analytics view event5    trackPageView(pathname)6})

isOnPage

Helper to verify if a specific path matches the current browser location.

typescript
1function isOnPage(pathname: string, exact: boolean = true): boolean

Examples

javascript
1// Browser is at: /todos/123?filter=all2 3isOnPage('/todos') // false (not exact)4isOnPage('/todos', false) // true  (subpath match)5isOnPage('/todos/123') // true  (exact path match)6isOnPage('/todos/123?filter=all') // true  (exact match including queries)

[!NOTE] Search query matches inside isOnPage are order-sensitive. Parameters must appear in the exact order specified.

edit this doc