blob: 105d028587308fc9e24fc12c78c2c1f8de693094 (
plain) (
blame)
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
|
import { Message, valueOf } from '../shared/messages';
export type WebMessageSender = Window | MessagePort | ServiceWorker | null;
export type WebExtMessageSender = browser.runtime.MessageSender;
export default class MessageListener {
onWebMessage(
listener: (msg: Message, sender: WebMessageSender) => void,
) {
window.addEventListener('message', (event: MessageEvent) => {
let sender = event.source;
let message = null;
try {
message = JSON.parse(event.data);
} catch (e) {
// ignore unexpected message
return;
}
listener(message, sender);
});
}
onBackgroundMessage(
listener: (msg: Message, sender: WebExtMessageSender) => any,
) {
browser.runtime.onMessage.addListener(
(msg: any, sender: WebExtMessageSender) => {
listener(valueOf(msg), sender);
},
);
}
}
|