tor-browser

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

messaging_helper.js (1249B)


      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 // By default, only the first handler for browser.runtime.onMessage which
     10 // returns a value will get to return one. As such, we need to let them all
     11 // receive the message, and all have a chance to return a response (with the
     12 // first non-undefined result being the one that is ultimately returned).
     13 // This way, about:compat and the shims library can both get a chance to
     14 // process a message, and just return undefined if they wish to ignore it.
     15 
     16 const onMessageFromTab = (function () {
     17  const handlers = new Set();
     18 
     19  browser.runtime.onMessage.addListener((msg, sender) => {
     20    const promises = [...handlers.values()].map(fn => fn(msg, sender));
     21    return Promise.allSettled(promises).then(results => {
     22      for (const { reason, value } of results) {
     23        if (reason) {
     24          console.error(reason);
     25        } else if (value !== undefined) {
     26          return value;
     27        }
     28      }
     29      return undefined;
     30    });
     31  });
     32 
     33  return function (handler) {
     34    handlers.add(handler);
     35  };
     36 })();