Shared Worker
useSharedWorker() (vue-worker-kit/shared) — reuses a single SharedWorker across every tab/window of the same origin that connects to it, instead of one worker per tab.
import { useSharedWorker } from 'vue-worker-kit/shared'
const { run, connect, disconnect, portCount } = useSharedWorker<typeof import('./shared.worker')>(
() => new SharedWorker(new URL('./shared.worker.ts', import.meta.url), { type: 'module' }),
)
// Optional — run() connects lazily on its own; call this to connect ahead of time.
connect()
const result = await run(data)
// Closes this tab's port. Does NOT terminate the worker — other tabs stay connected to it.
disconnect()The worker-side file is a normal defineWorkerHandler() module — the exact same file works with both new Worker(...) (via useWorker()) and new SharedWorker(...) (via useSharedWorker()); it doesn't need to know which one it's running under.
// shared.worker.ts
import { defineWorkerHandler } from 'vue-worker-kit/worker'
export default defineWorkerHandler(async (data: In, ctx) => {
return processData(data)
})Browser support: Chrome, Firefox, Edge Desktop. ❌ Not supported in Safari iOS or Chrome Android — no SharedWorker constructor exists there at all. connect()/run() throw WorkerUnavailableError in that case, the same way useWorker() does under SSR.
Options
Same as useWorker(): retries, retryDelay, cache, streaming. There is no idleTimeout/hardCancelOnAbort — a shared worker's lifetime isn't owned by any single tab, so connect()/disconnect() is the whole lifecycle story, not an idle timer.
Return value
connect()
() => void
Establishes this tab's connection. Idempotent; run() also calls it lazily if you skip this.
disconnect()
() => void
Closes this tab's port only; the shared worker keeps running for every other connected tab. Called automatically on onScopeDispose when used inside setup().
portCount
Ref<number>
Number of tabs the worker has seen connect, as last broadcast by the worker itself. Best-effort: a MessagePort has no platform-level "the other end went away" notification, so this only decrements on a cooperative disconnect() call — a crashed or force-closed tab is never subtracted.
run, isRunning, progress, error, cancel()
Same semantics as useWorker().