forked from vueuse/vueuse
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
79 lines (66 loc) · 1.78 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { ref } from 'vue-demi'
import { isSup, tryOnMounted, tryOnScopeDispose } from '@vueuse/shared'
import type { ConfigurableWindow } from '../_configurable'
import { defaultWindow } from '../_configurable'
export interface UseBroadcastChannelOptions extends ConfigurableWindow {
/**
* The name of the channel.
*/
name: string
}
/**
* Reactive BroadcastChannel
*
* @see https://vueuse.org/useBroadcastChannel
* @see https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel
* @param options
*
*/
export const useBroadcastChannel = (options: UseBroadcastChannelOptions) => {
const {
name,
window = defaultWindow,
} = options
const isSupported = isSup(() => Boolean(window && 'BroadcastChannel' in window))
const isClosed = ref(false)
const channel = ref<BroadcastChannel | undefined>()
const data = ref()
const error = ref<Event | null>(null)
const post = (data: unknown) => {
if (channel.value)
channel.value.postMessage(data)
}
const close = () => {
if (channel.value)
channel.value.close()
isClosed.value = true
}
if (isSupported.value) {
tryOnMounted(() => {
error.value = null
channel.value = new BroadcastChannel(name)
channel.value.addEventListener('message', (e: MessageEvent) => {
data.value = e.data
}, { passive: true })
channel.value.addEventListener('messageerror', (e: MessageEvent) => {
error.value = e
}, { passive: true })
channel.value.addEventListener('close', () => {
isClosed.value = true
})
})
}
tryOnScopeDispose(() => {
close()
})
return {
isSupported,
channel,
data,
post,
close,
error,
isClosed,
}
}
export type UseBroadcastChannelReturn = ReturnType<typeof useBroadcastChannel>