blob: 0d30aac6c8423dc7e614e585da11dc5a4f0f6bcd [file] [log] [blame]
Adrià Vilanova Martínezac2a5612022-12-27 21:51:40 +01001import OptionsWatcher from '../../common/optionsWatcher.js';
2
3// Main World OptionsWatcher server (used in content scripts to be able to serve
4// the options to Main World (MW) scripts).
5export default class MWOptionsWatcherServer {
6 constructor(CSTarget, MWTarget) {
7 if (!CSTarget || !MWTarget)
8 throw new Error(
9 `[MWOptionsWatcherServer] CSTarget and MWTarget are compulsory.`);
10
11 this.optionsWatcher = null;
12 this.CSTarget = CSTarget;
13 this.MWTarget = MWTarget;
14
15 window.addEventListener('message', e => this.handleMessage(e));
16 }
17
18 handleMessage(e) {
19 const uuid = e.data?.uuid;
20 if (e.source !== window || e.data?.target !== this.CSTarget || !uuid)
21 return;
22
23 if (e.data?.action === 'setUp') {
24 this.optionsWatcher = new OptionsWatcher(e.data?.request?.options);
25 return;
26 }
27
28 if (!this.optionsWatcher) {
29 console.warn(`[MWOptionsWatcherServer] Action '${
30 e.data?.action}' called before setting up options watcher.`);
31 return;
32 }
33
34 switch (e.data?.action) {
35 case 'getOption':
36 this.optionsWatcher.getOption(e.data?.request?.option).then(value => {
37 this.respond(uuid, value);
38 });
39 return;
40
41 case 'getOptions':
42 var promises = [];
43 var options = e.data?.request?.options ?? [];
44 for (const option of options) {
45 promises.push(this.optionsWatcher.getOption(option));
46 }
47 Promise.all(promises).then(responses => {
48 const response = {};
49 for (let i = 0; i < responses.length; i++) {
50 response[options[i]] = responses[i];
51 }
52 this.respond(uuid, response);
53 });
54 return;
55
56 case 'isEnabled':
57 this.optionsWatcher.isEnabled(e.data?.request?.option).then(value => {
58 this.respond(uuid, value);
59 });
60 return;
61
62 case 'areEnabled':
63 var promises = [];
64 var options = e.data?.request?.options ?? [];
65 for (const option of options) {
66 promises.push(this.optionsWatcher.isEnabled(option));
67 }
68 Promise.all(promises).then(responses => {
69 const response = {};
70 for (let i = 0; i < responses.length; i++) {
71 response[options[i]] = responses[i];
72 }
73 this.respond(uuid, response);
74 });
75 return;
76
77 default:
78 console.error(`[MWOptionsWatcherServer] Invalid action received (${
79 e.data?.action})`);
80 }
81 }
82
83 respond(uuid, response) {
84 const data = {
85 target: this.MWTarget,
86 uuid,
87 response,
88 };
89 window.postMessage(data, window.origin);
90 }
91}