|
| 1 | +# link-interceptor |
| 2 | + |
| 3 | +Framework-agnostic core for intercepting all `<a>` tag clicks in your SPA. Provides callbacks for internal and external links with URL mutation support. |
| 4 | + |
| 5 | +For framework-specific wrappers, see: |
| 6 | +- [vue-link-interceptor](https://www.npmjs.com/package/vue-link-interceptor) — Vue 3 plugin |
| 7 | +- [react-link-interceptor](https://www.npmjs.com/package/react-link-interceptor) — React hook |
| 8 | +- [svelte-link-interceptor](https://www.npmjs.com/package/svelte-link-interceptor) — Svelte action |
| 9 | + |
| 10 | +## Install |
| 11 | + |
| 12 | +```bash |
| 13 | +npm install link-interceptor |
| 14 | +``` |
| 15 | + |
| 16 | +## Usage |
| 17 | + |
| 18 | +```ts |
| 19 | +import { interceptLinks } from 'link-interceptor' |
| 20 | + |
| 21 | +const cleanup = interceptLinks({ |
| 22 | + onInternalLink(ctx) { |
| 23 | + ctx.preventDefault() |
| 24 | + history.pushState(null, '', ctx.path) |
| 25 | + }, |
| 26 | + onExternalLink(ctx) { |
| 27 | + ctx.url.searchParams.set('utm_source', 'myapp') |
| 28 | + }, |
| 29 | +}) |
| 30 | + |
| 31 | +// When done: |
| 32 | +cleanup() |
| 33 | +``` |
| 34 | + |
| 35 | +## API |
| 36 | + |
| 37 | +### `interceptLinks(options): () => void` |
| 38 | + |
| 39 | +Registers a capture-phase click listener on `document`. Returns a cleanup function. |
| 40 | + |
| 41 | +### LinkContext |
| 42 | + |
| 43 | +| Property | Type | Description | |
| 44 | +|----------|------|-------------| |
| 45 | +| `url` | `URL` | Parsed URL (mutable — changes reflected on `anchor.href`) | |
| 46 | +| `anchor` | `HTMLAnchorElement` | The clicked `<a>` element | |
| 47 | +| `event` | `MouseEvent` | The original click event | |
| 48 | +| `path` | `string` | `url.pathname + url.search + url.hash` | |
| 49 | +| `isExternal` | `boolean` | Whether the link is external | |
| 50 | +| `isModifierClick` | `boolean` | Whether Ctrl/Meta/Shift/Alt was held | |
| 51 | +| `preventDefault()` | `() => void` | Cancel the default navigation | |
| 52 | + |
| 53 | +## License |
| 54 | + |
| 55 | +[MIT](https://github.com/babu-ch/link-interceptor/blob/main/LICENSE) |
0 commit comments