aboutsummaryrefslogtreecommitdiff
path: root/src/content/MessageListener.ts
blob: 31cc1ae0914e61d00fbb865f44c41d59065b3b4d (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
33
34
35
36
37
38
39
import { injectable } from "tsyringe";
import { Message, valueOf } from "../shared/messages";

export type WebExtMessageSender = browser.runtime.MessageSender;

@injectable()
export default class MessageListener {
  onWebMessage(listener: (msg: Message, sender: Window) => void) {
    window.addEventListener("message", (event: MessageEvent) => {
      const sender = event.source;
      if (!(sender instanceof Window)) {
        return;
      }
      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) => {
        try {
          return Promise.resolve(listener(valueOf(msg), sender));
        } catch (e) {
          console.warn(e);
          return;
        }
      }
    );
  }
}