blob: 70e567bb98be3359c1830191212ded8b6fff5f81 [file] [log] [blame]
Adrià Vilanova Martínez2548e442023-03-05 18:45:30 +01001export const kDefaultTimeout = 10 * 1000; // 10 seconds
2
3export default class MainWorldContentScriptBridgeClient {
4 constructor(CSTarget, MWTarget, timeout) {
5 if (!CSTarget || !MWTarget) {
6 throw new Error(
7 `[MWOptionsWatcherClient] CSTarget and MWTarget are compulsory.`);
8 }
9
10 this.CSTarget = CSTarget;
11 this.MWTarget = MWTarget;
12 this.timeout = timeout ?? kDefaultTimeout;
13 }
14
15 _sendRequestWithoutCallback(action, request, uuid) {
16 if (!uuid) uuid = self.crypto.randomUUID();
17 const data = {
18 target: this.CSTarget,
19 uuid,
20 action,
21 request,
22 };
23 window.postMessage(data, '*');
24 }
25
26 _sendRequest(action, request) {
27 return new Promise((res, rej) => {
28 const uuid = self.crypto.randomUUID();
29
30 let timeoutId;
31 let listener = e => {
32 if (e.source !== window || e.data?.target !== this.MWTarget ||
33 e.data?.uuid !== uuid)
34 return;
35
36 window.removeEventListener('message', listener);
37 clearTimeout(timeoutId);
38 res(e.data?.response);
39 };
40 window.addEventListener('message', listener);
41
42 timeoutId = setTimeout(() => {
43 window.removeEventListener('message', listener);
44 rej(new Error('Timed out while waiting response.'));
45 }, this.timeout);
46
47 this._sendRequestWithoutCallback(action, request, uuid);
48 });
49 }
50}