summaryrefslogtreecommitdiff
path: root/src/lib/SyncMessage.js
blob: 6d48b2311b22e5e6228ab7294aebcfad48837da2 (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
(() => {
  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 unprivileged requests to track tab ids in Firefox
      let pending = new Map();
      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) {
            // this was the unprivileged, messageless preliminary request
            // to set tabId and frameId
            pending.set(msgId, sender);
          }
        }
        if (!(msg !== null && sender && url.startsWith(ENDPOINT_PREFIX))) {
          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(e);
          }
        }
        return {
          redirectUrl: `data:application/json,${JSON.stringify(result)}`
        };
      };

      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}*`, `*://*/${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 = sendSyncMessage = msg => {
      let msgId = `id=${encodeURIComponent(`${uuid()},${docUrl}`)}`;
      let url = `${ENDPOINT_PREFIX}${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) try {
        // on Firefox first we send an unprivileged XHR to notify the listener
        // about the tab ID, which is not sent in privileged XHR
        let r = new content.XMLHttpRequest();
        let unprivilegedUrl = docUrl.startsWith("http")
          ? `${document.location.origin}/${url}` : url;
        r.open("GET", unprivilegedUrl, false);
        r.send(null);
      } catch (e) {
        // we ignore the likely CORS error
      }
      // adding the payload
      url += `&msg=${encodeURIComponent(JSON.stringify(msg))}`;
      try {
        // 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
        let r = new XMLHttpRequest();
        r.open("GET", url, false);
        r.send(null);
        return JSON.parse(r.responseText);
      } catch(e) {
        console.error(`syncMessage error in ${document.URL}: ${e.message}`);
      }
      return null;
    };
  }
})();