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/. */
7 var EXPORTED_SYMBOLS = [
8 "DOMContentLoadedPromise",
13 const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
16 * Wait for a single event to be fired on a specific EventListener.
18 * The returned promise is guaranteed to not be called before the
19 * next event tick after the event listener is called, so that all
20 * other event listeners for the element are executed before the
21 * handler is executed. For example:
23 * const promise = new EventPromise(element, "myEvent");
24 * // same event tick here
26 * // next event tick here
28 * @param {EventListener} listener
29 * Object which receives a notification (an object that implements
30 * the Event interface) when an event of the specificed type occurs.
31 * @param {string} type
32 * Case-sensitive string representing the event type to listen for.
33 * @param {boolean?} [false] options.capture
34 * Indicates the event will be despatched to this subject,
35 * before it bubbles down to any EventTarget beneath it in the
37 * @param {boolean?} [false] options.wantsUntrusted
38 * Receive synthetic events despatched by web content.
39 * @param {boolean?} [false] options.mozSystemGroup
40 * Determines whether to add listener to the system group.
42 * @return {Promise.<Event>}
46 function EventPromise(
51 wantsUntrusted: false,
52 mozSystemGroup: false,
55 if (!listener || !("addEventListener" in listener)) {
56 throw new TypeError();
58 if (typeof type != "string") {
59 throw new TypeError();
62 ("capture" in options && typeof options.capture != "boolean") ||
63 ("wantsUntrusted" in options &&
64 typeof options.wantsUntrusted != "boolean") ||
65 ("mozSystemGroup" in options && typeof options.mozSystemGroup != "boolean")
67 throw new TypeError();
72 return new Promise(resolve => {
73 listener.addEventListener(
76 Services.tm.dispatchToMainThread(() => resolve(event));
83 function DOMContentLoadedPromise(window, options = { mozSystemGroup: true }) {
85 window.document.readyState == "complete" ||
86 window.document.readyState == "interactive"
88 return Promise.resolve();
90 return new EventPromise(window, "DOMContentLoaded", options);
94 * Awaits a single IPC message.
96 * @param {nsIMessageSender} target
97 * @param {string} name
101 * @throws {TypeError}
102 * If target is not an nsIMessageSender.
104 function MessagePromise(target, name) {
105 if (!(target instanceof Ci.nsIMessageSender)) {
106 throw new TypeError();
109 return new Promise(resolve => {
110 const onMessage = (...args) => {
111 target.removeMessageListener(name, onMessage);
114 target.addMessageListener(name, onMessage);