Adrià Vilanova Martínez | 2548e44 | 2023-03-05 18:45:30 +0100 | [diff] [blame] | 1 | export default class MainWorldContentScriptBridgeServer { |
| 2 | constructor(CSTarget, MWTarget) { |
| 3 | if (!CSTarget || !MWTarget) { |
| 4 | throw new Error( |
| 5 | `[MWOptionsWatcherServer] CSTarget and MWTarget are compulsory.`); |
| 6 | } |
| 7 | |
| 8 | this.CSTarget = CSTarget; |
| 9 | this.MWTarget = MWTarget; |
| 10 | this.handler = () => {}; |
| 11 | } |
| 12 | |
| 13 | // Handler should be an action of the form (uuid, action, request) => {...}. |
| 14 | setUpHandler(handler) { |
| 15 | this.handler = handler; |
| 16 | window.addEventListener('message', e => this.#handleMessage(e)); |
| 17 | } |
| 18 | |
| 19 | #handleMessage(e) { |
| 20 | const uuid = e.data?.uuid; |
| 21 | if (e.source !== window || e.data?.target !== this.CSTarget || !uuid) |
| 22 | return; |
| 23 | |
Adrià Vilanova Martínez | eb1c44d | 2023-07-23 00:06:01 +0200 | [diff] [blame] | 24 | // If chrome.runtime.id is undefined, then this content script belongs to a |
| 25 | // dead extension (see https://stackoverflow.com/a/69603416). |
| 26 | if (typeof chrome.runtime.id === 'undefined') { |
| 27 | console.debug( |
| 28 | '[MainWorldContentScriptBridgeServer] Not handling message because this is a dead server.'); |
| 29 | return; |
| 30 | } |
| 31 | |
Adrià Vilanova Martínez | 2548e44 | 2023-03-05 18:45:30 +0100 | [diff] [blame] | 32 | const action = e.data?.action; |
| 33 | const request = e.data?.request; |
| 34 | return this.handler(uuid, action, request); |
| 35 | } |
| 36 | |
| 37 | _respond(uuid, response) { |
| 38 | const data = { |
| 39 | target: this.MWTarget, |
| 40 | uuid, |
| 41 | response, |
| 42 | }; |
| 43 | window.postMessage(data, window.origin); |
| 44 | } |
| 45 | } |