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(listener, type, options = {
48 wantsUntrusted: false,
49 mozSystemGroup: false,
51 if (!listener || !("addEventListener" in listener)) {
52 throw new TypeError();
54 if (typeof type != "string") {
55 throw new TypeError();
57 if (("capture" in options && typeof options.capture != "boolean") ||
58 ("wantsUntrusted" in options && typeof options.wantsUntrusted != "boolean") ||
59 ("mozSystemGroup" in options && typeof options.mozSystemGroup != "boolean")) {
60 throw new TypeError();
65 return new Promise(resolve => {
66 listener.addEventListener(type, event => {
67 Services.tm.dispatchToMainThread(() => resolve(event));
72 function DOMContentLoadedPromise(window, options = {mozSystemGroup: true}) {
73 if (window.document.readyState == "complete" || window.document.readyState == "interactive") {
74 return Promise.resolve();
76 return new EventPromise(window, "DOMContentLoaded", options);
80 * Awaits a single IPC message.
82 * @param {nsIMessageSender} target
83 * @param {string} name
88 * If target is not an nsIMessageSender.
90 function MessagePromise(target, name) {
91 if (!(target instanceof Ci.nsIMessageSender)) {
92 throw new TypeError();
95 return new Promise(resolve => {
96 const onMessage = (...args) => {
97 target.removeMessageListener(name, onMessage);
100 target.addMessageListener(name, onMessage);