link-interceptor
v0.1.2
Published
Intercept all <a> tag clicks in your SPA — framework-agnostic core for handling internal and external link navigation.
Downloads
294
Maintainers
Readme
link-interceptor
Framework-agnostic core for intercepting all <a> tag clicks in your SPA. Provides callbacks for internal and external links with URL mutation support.
For framework-specific wrappers, see:
- vue-link-interceptor — Vue 3 plugin
- react-link-interceptor — React hook
- svelte-link-interceptor — Svelte action
Install
npm install link-interceptorUsage
import { interceptLinks } from 'link-interceptor'
const cleanup = interceptLinks({
onInternalLink(ctx) {
ctx.preventDefault()
history.pushState(null, '', ctx.path)
},
onExternalLink(ctx) {
ctx.url.searchParams.set('utm_source', 'myapp')
},
})
// When done:
cleanup()API
interceptLinks(options): () => void
Registers a capture-phase click listener on document. Returns a cleanup function.
LinkContext
| Property | Type | Description |
|----------|------|-------------|
| url | URL | Parsed URL (mutable — changes reflected on anchor.href) |
| anchor | HTMLAnchorElement | The clicked <a> element |
| event | MouseEvent | The original click event |
| path | string | url.pathname + url.search + url.hash |
| isExternal | boolean | Whether the link is external |
| isModifierClick | boolean | Whether Ctrl/Meta/Shift/Alt was held |
| preventDefault() | () => void | Cancel the default navigation |
