tor-browser

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

message.js (1403B)


      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 const REQUEST_DONE_SUFFIX = ":done";
      8 
      9 function wait(win, type) {
     10  return new Promise(resolve => {
     11    const onMessage = event => {
     12      if (event.data.type !== type) {
     13        return;
     14      }
     15      win.removeEventListener("message", onMessage);
     16      resolve();
     17    };
     18    win.addEventListener("message", onMessage);
     19  });
     20 }
     21 
     22 /**
     23 * Post a message to some window.
     24 *
     25 * @param win
     26 *        The window to post to.
     27 * @param typeOrMessage
     28 *        Either a string or and an object representing the message to send.
     29 *        If this is a string, it will be expanded into an object with the string as the
     30 *        `type` field.  If this is an object, it will be sent as is.
     31 */
     32 function post(win, typeOrMessage) {
     33  // When running unit tests on XPCShell, there is no window to send messages to.
     34  if (!win) {
     35    return;
     36  }
     37 
     38  let message = typeOrMessage;
     39  if (typeof typeOrMessage == "string") {
     40    message = {
     41      type: typeOrMessage,
     42    };
     43  }
     44  win.postMessage(message, "*");
     45 }
     46 
     47 function request(win, type) {
     48  const done = wait(win, type + REQUEST_DONE_SUFFIX);
     49  post(win, type);
     50  return done;
     51 }
     52 
     53 exports.wait = wait;
     54 exports.post = post;
     55 exports.request = request;