From 9b0141ca32e4d2a4dee4d1186c70e4f40cb7119e Mon Sep 17 00:00:00 2001 From: Evan Date: Thu, 9 Nov 2023 16:06:59 +0100 Subject: [PATCH] fix(useWebSocket): webworker support (#3469) Co-authored-by: Anthony Fu --- packages/core/useWebSocket/index.ts | 7 ++++--- packages/shared/utils/is.ts | 1 + tsconfig.json | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/core/useWebSocket/index.ts b/packages/core/useWebSocket/index.ts index bbbfc2a90a4..85dbf2bc77f 100644 --- a/packages/core/useWebSocket/index.ts +++ b/packages/core/useWebSocket/index.ts @@ -1,7 +1,7 @@ import type { Ref } from 'vue-demi' import { ref, watch } from 'vue-demi' import type { Fn, MaybeRefOrGetter } from '@vueuse/shared' -import { isClient, toRef, tryOnScopeDispose, useIntervalFn } from '@vueuse/shared' +import { isClient, isWorker, toRef, tryOnScopeDispose, useIntervalFn } from '@vueuse/shared' import { useEventListener } from '../useEventListener' export type WebSocketStatus = 'OPEN' | 'CONNECTING' | 'CLOSED' @@ -288,12 +288,13 @@ export function useWebSocket( } if (autoClose) { - useEventListener('beforeunload', () => close()) + if (isClient) + useEventListener('beforeunload', () => close()) tryOnScopeDispose(close) } const open = () => { - if (!isClient) + if (!isClient && !isWorker) return close() explicitlyClosed = false diff --git a/packages/shared/utils/is.ts b/packages/shared/utils/is.ts index 977d2fa17f2..24fc7b3eabf 100644 --- a/packages/shared/utils/is.ts +++ b/packages/shared/utils/is.ts @@ -1,5 +1,6 @@ /* eslint-disable antfu/top-level-function */ export const isClient = typeof window !== 'undefined' && typeof document !== 'undefined' +export const isWorker = typeof WorkerGlobalScope !== 'undefined' && globalThis instanceof WorkerGlobalScope export const isDef = (val?: T): val is T => typeof val !== 'undefined' export const notNullish = (val?: T | null | undefined): val is T => val != null export const assert = (condition: boolean, ...infos: any[]) => { diff --git a/tsconfig.json b/tsconfig.json index 5f727dcb430..4a690cc04b0 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "target": "es2020", "jsx": "preserve", - "lib": ["ESNext", "DOM", "DOM.Iterable"], + "lib": ["ESNext", "DOM", "DOM.Iterable", "webworker"], "baseUrl": ".", "rootDir": ".", "module": "esnext",