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 | |
| 24 | const action = e.data?.action; |
| 25 | const request = e.data?.request; |
| 26 | return this.handler(uuid, action, request); |
| 27 | } |
| 28 | |
| 29 | _respond(uuid, response) { |
| 30 | const data = { |
| 31 | target: this.MWTarget, |
| 32 | uuid, |
| 33 | response, |
| 34 | }; |
| 35 | window.postMessage(data, window.origin); |
| 36 | } |
| 37 | } |