summaryrefslogtreecommitdiff
path: root/src/lib/SyncMessage.js
blob: a644507a63745dbfb166efae8833913b1fbca36e (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
"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

      // cache of senders from early async messages to track tab ids in Firefox
      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) => {
          if (!m.___syncMessageId) return;
          pending.set(m.___syncMessageId, sender);
        });
      }

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


      let obrListener = request => {
        let {url, tabId} = request;
        let params = new URLSearchParams(url.split("?")[1]);
        let msgId = params.get("id");
        let msg = params.get("msg");
        let documentUrl = params.get("url");
        let sender;
        if (tabId === TAB_ID_NONE) {
          // Firefox sends privileged content script XHR without valid tab ids
          // so we cache sender info from unprivileged XHR correlated by msgId
          if (pending.has(msgId)) {
            sender = pending.get(msgId);
            pending.delete(msgId);
          } else {
            throw new Error(`sendSyncMessage: cannot correlate sender info for ${msgId}.`);
          }
        } else {
          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);
            }
          }
          sender = {
            tab: {
              id: tabId,
              url: tabUrl
            },
            frameId,
            url: documentUrl,
            timeStamp: Date.now()
          };
        }
        if (!(msg !== null && sender)) {
          return CANCEL;
        }
        // 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).
        let result;
        for (let l of listeners) {
          try {
            if ((result = l(JSON.parse(msg), sender)) !== undefined) break;
          } catch (e) {
            console.error("%o processing message %o from %o", e, msg, sender);
          }
        }
        return result instanceof Promise ? (async () => ret(await result)) : ret(result);
      };
      let ret = r => ({redirectUrl:  `data:application/json,${JSON.stringify(r)}`})

      let listeners = new Set();
      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
    if (typeof uuid !== "function") {
      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
        browser.runtime.sendMessage({___syncMessageId: msgId});
      }
      // 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;
    };
  }
})();