tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

shim_messaging_helper.js (1684B)


      1 /* This Source Code Form is subject to the terms of the Mozilla Public
      2 * License, v. 2.0. If a copy of the MPL was not distributed with this
      3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
      4 
      5 "use strict";
      6 
      7 /* globals browser */
      8 
      9 if (!window.Shims) {
     10  window.Shims = new Map();
     11 }
     12 
     13 if (!window.ShimsHelperReady) {
     14  window.ShimsHelperReady = true;
     15 
     16  browser.runtime.onMessage.addListener(details => {
     17    const { shimId, warning } = details;
     18    if (!shimId) {
     19      return;
     20    }
     21    window.Shims.set(shimId, details);
     22    if (warning) {
     23      console.warn(warning);
     24    }
     25  });
     26 
     27  async function handleMessage(port, shimId, messageId, message) {
     28    let response;
     29    const shim = window.Shims.get(shimId);
     30    if (shim) {
     31      const { needsShimHelpers, origin } = shim;
     32      if (origin === location.origin) {
     33        if (needsShimHelpers?.includes(message)) {
     34          const msg = { shimId, message };
     35          try {
     36            response = await browser.runtime.sendMessage(msg);
     37          } catch (_) {}
     38        }
     39      }
     40    }
     41    port.postMessage({ messageId, response });
     42  }
     43 
     44  window.addEventListener(
     45    "ShimConnects",
     46    e => {
     47      e.stopPropagation();
     48      e.preventDefault();
     49      const { port, pendingMessages, shimId } = e.detail;
     50      const shim = window.Shims.get(shimId);
     51      if (!shim) {
     52        return;
     53      }
     54      port.onmessage = ({ data }) => {
     55        handleMessage(port, shimId, data.messageId, data.message);
     56      };
     57      for (const [messageId, message] of pendingMessages) {
     58        handleMessage(port, shimId, messageId, message);
     59      }
     60    },
     61    true
     62  );
     63 
     64  window.dispatchEvent(new CustomEvent("ShimHelperReady"));
     65 }