Skip to content

Commit

Permalink
fix(useWebSocket): webworker support (#3469)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
binary-signal and antfu committed Nov 9, 2023
1 parent 6985152 commit 9b0141c
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 4 deletions.
7 changes: 4 additions & 3 deletions 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'
Expand Down Expand Up @@ -288,12 +288,13 @@ export function useWebSocket<Data = any>(
}

if (autoClose) {
useEventListener('beforeunload', () => close())
if (isClient)
useEventListener('beforeunload', () => close())
tryOnScopeDispose(close)
}

const open = () => {
if (!isClient)
if (!isClient && !isWorker)
return
close()
explicitlyClosed = false
Expand Down
1 change: 1 addition & 0 deletions 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 = <T = any>(val?: T): val is T => typeof val !== 'undefined'
export const notNullish = <T = any>(val?: T | null | undefined): val is T => val != null
export const assert = (condition: boolean, ...infos: any[]) => {
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Expand Up @@ -2,7 +2,7 @@
"compilerOptions": {
"target": "es2020",
"jsx": "preserve",
"lib": ["ESNext", "DOM", "DOM.Iterable"],
"lib": ["ESNext", "DOM", "DOM.Iterable", "webworker"],
"baseUrl": ".",
"rootDir": ".",
"module": "esnext",
Expand Down

0 comments on commit 9b0141c

Please sign in to comment.