summaryrefslogtreecommitdiff
path: root/src/lib/SyncMessage.js
blob: de1d784db725b6ab509083e1da2a0cd8d681edb1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
"use strict";
(() => {
  let ENDPOINT_PREFIX = `https://sync-messages.invalid/${browser.extension.getURL("")}?`;
  let MOZILLA = "mozSystem" in XMLHttpRequest.prototype;

  if (browser.webRequest) {
    if (typeof browser.runtime.onSyncMessage !== "object") {
      // Background Script side

      let pending = new Map();
      if (MOZILLA) {
        // we don't care this is async, as long as it get called before the
        // sync XHR (we are not interested in the response on the content side)
        browser.runtime.onMessage.addListener((m, sender) => {
          let wrapper = m.__syncMessage__;
          if (!wrapper) return;
          let {id} = wrapper;
          pending.set(id, wrapper);
          let result;
          let unsuspend = result => {
            pending.delete(id);
            if (wrapper.unsuspend) {
              setTimeout(wrapper.unsuspend, 0);
            }
            return result;
          }
          try {
            result = notifyListeners(JSON.stringify(wrapper.payload), sender);
          } catch(e) {
            unsuspend();
            throw e;
          }
          console.debug("sendSyncMessage: returning", result);
          return (result instanceof Promise ? result
            : new Promise(resolve => resolve(result))
          ).then(result => unsuspend(result));
        });
      }

      let tabUrlCache = new Map();
      let asyncResults = new Map();
      let tabRemovalListener = null;
      let CANCEL = {cancel: true};
      let {TAB_ID_NONE} = browser.tabs;


      let obrListener = request => {
        try {
        let {url, tabId} = request;
        let params = new URLSearchParams(url.split("?")[1]);
        let msgId = params.get("id");
        if (asyncResults.has(msgId)) {
          return asyncRet(msgId);
        }
        let msg = params.get("msg");

        if (MOZILLA || tabId === TAB_ID_NONE) {
          // this shoud be a mozilla suspension request
          return params.get("suspend") ? new Promise(resolve => {
            if (pending.has(msgId)) {
              let wrapper = pending.get(msgId);
              if (!wrapper.unsuspend) {
                wrapper.unsuspend = resolve;
                return;
              }
            }
            resolve();
          }).then(() => ret("go on"))
          : CANCEL; // otherwise, bail
        }
        // CHROME from now on
        let documentUrl = params.get("url");
        let {frameAncestors, frameId} = request;
        let isTop = frameId === 0 || !!params.get("top");
        let tabUrl = frameAncestors && frameAncestors.length
          && frameAncestors[frameAncestors.length - 1].url;

        if (!tabUrl) {
          if (isTop) {
            tabUrlCache.set(tabId, tabUrl = documentUrl);
            if (!tabRemovalListener) {
              browser.tabs.onRemoved.addListener(tabRemovalListener = tab => {
                tabUrlCache.delete(tab.id);
              });
            }
          } else {
            tabUrl = tabUrlCache.get(tabId);
          }
        }
        let sender = {
          tab: {
            id: tabId,
            url: tabUrl
          },
          frameId,
          url: documentUrl,
          timeStamp: Date.now()
        };

        if (!(msg !== null && sender)) {
          return CANCEL;
        }
        let result = notifyListeners(msg, sender);
        if (result instanceof Promise) {

          // On Chromium, if the promise is not resolved yet,
          // we redirect the XHR to the same URL (hence same msgId)
          // while the result get cached for asynchronous retrieval
          result.then(r => {
            asyncResults.set(msgId, result = r);
          });
          return asyncResults.has(msgId)
          ? asyncRet(msgId) // promise was already resolved
          : {redirectUrl: url.replace(
              /&redirects=(\d+)|$/, // redirects count to avoid loop detection
              (all, count) => `&redirects=${parseInt(count) + 1 || 1}`)};
        }
        return ret(result);
      } catch(e) {
        console.error(e);
        return CANCEL;
      } };

      let ret = r => ({redirectUrl:  `data:application/json,${JSON.stringify(r)}`})
      let asyncRet = msgId => {
        let result = asyncResults.get(msgId);
        asyncResults.delete(msgId);
        return ret(result);
      }

      let listeners = new Set();
      function notifyListeners(msg, sender) {
        // Just like in the async runtime.sendMessage() API,
        // we process the listeners in order until we find a not undefined
        // result, then we return it (or undefined if none returns anything).
        for (let l of listeners) {
          try {
            let result = l(JSON.parse(msg), sender);
            if (result !== undefined) return result;
          } catch (e) {
            console.error("%o processing message %o from %o", e, msg, sender);
          }
        }
      }
      browser.runtime.onSyncMessage = {
        ENDPOINT_PREFIX,
        addListener(l) {
          listeners.add(l);
          if (listeners.size === 1) {
            browser.webRequest.onBeforeRequest.addListener(obrListener,
              {urls: [`${ENDPOINT_PREFIX}*`],
                types: ["xmlhttprequest"]},
              ["blocking"]
            );
          }
        },
        removeListener(l) {
          listeners.remove(l);
          if (listeners.size === 0) {
            browser.webRequest.onBeforeRequest.removeListener(obrListener);
          }
        },
        hasListener(l) {
          return listeners.has(l);
        }
      };
    }
  } else if (typeof browser.runtime.sendSyncMessage !== "function") {
    // Content Script side
    let uuid = () => (Math.random() * Date.now()).toString(16);
    let docUrl = document.URL;
    browser.runtime.sendSyncMessage = msg => {
      let msgId = `${uuid()},${docUrl}`;
      let url = `${ENDPOINT_PREFIX}id=${encodeURIComponent(msgId)}` +
        `&url=${encodeURIComponent(docUrl)}`;
      if (window.top === window) {
        // we add top URL information because Chromium doesn't know anything
        // about frameAncestors
        url += "&top=true";
      }
      if (MOZILLA) {
        // on Firefox we first need to send an async message telling the
        // background script about the tab ID, which does not get sent
        // with "privileged" XHR
        let result;
        browser.runtime.sendMessage(
          {__syncMessage__: {id: msgId, payload: msg}}
        ).then(r => {
          result = r;
        }).catch(e => {
          throw e;
        });

        // In order to cope with inconsistencies in XHR synchronicity,
        // allowing DOM element to be inserted and script to be executed
        // (seen with file:// and ftp:// loads) we additionally suspend on
        // Mutation notifications and beforescriptexecute events
        let suspendURL = url + "&suspend=true";
        let suspended = false;
        let suspend = () => {
          if (result || suspended) return;
          suspended = true;
          try {
            let r = new XMLHttpRequest();
            r.open("GET", suspendURL, false);
            r.send(null);
          } finally {
            suspended = false;
          }
        };
        let domSuspender = new MutationObserver(suspend);
        domSuspender.observe(document.documentElement, {childList: true});
        addEventListener("beforescriptexecute", suspend, true);
        try {
          suspend();
        } finally {
          removeEventListener("beforescriptexecute", suspend, true);
          domSuspender.disconnect();
        }
        return result;
      }
      // then we send the payload using a privileged XHR, which is not subject
      // to CORS but unfortunately doesn't carry any tab id except on Chromium

      url += `&msg=${encodeURIComponent(JSON.stringify(msg))}`; // adding the payload
      let r = new XMLHttpRequest();
      try {
        r.open("GET", url, false);
        r.send(null);
        return JSON.parse(r.responseText);
      } catch(e) {
        console.error(`syncMessage error in ${document.URL}: ${e.message} (response ${r.responseText})`);
      }
      return null;
    };
  }
})();