| 34 | }; |
| 35 | |
| 36 | export class WindowMessage implements Message { |
| 37 | EE = new EventEmitter<string, any>(); |
| 38 | |
| 39 | // source: Window 消息来源 |
| 40 | // target: Window 消息目标 |
| 41 | constructor( |
| 42 | private source: Window, |
| 43 | private target: Window, |
| 44 | private serviceWorker?: boolean |
| 45 | ) { |
| 46 | // 监听消息 |
| 47 | this.source.addEventListener("message", (e) => { |
| 48 | if (e.source === this.target || e.source === this.source) { |
| 49 | this.messageHandle(e.data, new WindowPostMessage(this.target)); |
| 50 | } |
| 51 | }); |
| 52 | // 是否监听serviceWorker消息 |
| 53 | if (this.serviceWorker) { |
| 54 | navigator.serviceWorker.addEventListener("message", (e) => { |
| 55 | if (e.source) { |
| 56 | this.messageHandle(e.data, e.source as Window); |
| 57 | } |
| 58 | }); |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | messageHandle(data: WindowMessageBody, target: PostMessage) { |
| 63 | // 处理消息 |
| 64 | if (data.type === "sendMessage") { |
| 65 | // 接收到消息 |
| 66 | this.EE.emit("message", data.data, (resp: any) => { |
| 67 | // 发送响应消息 |
| 68 | // 无消息id则不发送响应消息 |
| 69 | if (!data.messageId) { |
| 70 | return; |
| 71 | } |
| 72 | const body: WindowMessageBody = { |
| 73 | messageId: data.messageId, |
| 74 | type: "respMessage", |
| 75 | data: resp, |
| 76 | }; |
| 77 | target.postMessage(body); |
| 78 | }); |
| 79 | } else if (data.type === "respMessage") { |
| 80 | // 接收到响应消息 |
| 81 | this.EE.emit(`response:${data.messageId}`, data); |
| 82 | } else if (data.type === "connect") { |
| 83 | this.EE.emit("connect", data.data, new WindowMessageConnect(data.messageId, this.EE, target)); |
| 84 | } else if (data.type === "disconnect") { |
| 85 | this.EE.emit(`disconnect:${data.messageId}`); |
| 86 | } else if (data.type === "connectMessage") { |
| 87 | this.EE.emit(`connectMessage:${data.messageId}`, data.data); |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | onConnect(callback: (data: TMessage, con: MessageConnect) => void): void { |
| 92 | this.EE.addListener("connect", callback); |
| 93 | } |
nothing calls this directly
no outgoing calls
no test coverage detected