-
-
Notifications
You must be signed in to change notification settings - Fork 473
/
createMessageChannel.ts
46 lines (41 loc) · 1018 Bytes
/
createMessageChannel.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
import {
ServiceWorkerFetchEventMap,
ServiceWorkerIncomingEventsMap,
} from '../../glossary'
export interface ServiceWorkerMessage<
EventType extends keyof ServiceWorkerIncomingEventsMap,
EventPayload,
> {
type: EventType
payload: EventPayload
}
export interface WorkerMessageChannel {
send<Event extends keyof ServiceWorkerFetchEventMap>(
message: Parameters<ServiceWorkerFetchEventMap[Event]>[0] extends undefined
? { type: Event }
: {
type: Event
payload: Parameters<ServiceWorkerFetchEventMap[Event]>[0]
},
): void
}
/**
* Creates a communication channel between the client
* and the Service Worker associated with the given event.
*/
export function createMessageChannel(
event: MessageEvent,
): WorkerMessageChannel {
const port = event.ports[0]
return {
/**
* Send a text message to the connected Service Worker.
*/
send(message) {
if (!port) {
return
}
port.postMessage(message)
},
}
}