summaryrefslogtreecommitdiffstats
path: root/dom/browser-element/BrowserElementChildPreload.js
blob: 4ded6ce02abdc4869cd1396419cb3080f32846d2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

/* eslint-env mozilla/frame-script */

function debug(msg) {
  // dump("BrowserElementChildPreload - " + msg + "\n");
}

debug("loaded");

var BrowserElementIsReady;

var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { BrowserElementPromptService } = ChromeUtils.import(
  "resource://gre/modules/BrowserElementPromptService.jsm"
);

function sendAsyncMsg(msg, data) {
  // Ensure that we don't send any messages before BrowserElementChild.js
  // finishes loading.
  if (!BrowserElementIsReady) {
    return;
  }

  if (!data) {
    data = {};
  }

  data.msg_name = msg;
  sendAsyncMessage("browser-element-api:call", data);
}

var LISTENED_EVENTS = [
  // This listens to unload events from our message manager, but /not/ from
  // the |content| window.  That's because the window's unload event doesn't
  // bubble, and we're not using a capturing listener.  If we'd used
  // useCapture == true, we /would/ hear unload events from the window, which
  // is not what we want!
  { type: "unload", useCapture: false, wantsUntrusted: false },
];

/**
 * The BrowserElementChild implements one half of <iframe mozbrowser>.
 * (The other half is, unsurprisingly, BrowserElementParent.)
 *
 * This script is injected into an <iframe mozbrowser> via
 * nsIMessageManager::LoadFrameScript().
 *
 * Our job here is to listen for events within this frame and bubble them up to
 * the parent process.
 */

var global = this;

function BrowserElementChild() {
  // Maps outer window id --> weak ref to window.  Used by modal dialog code.
  this._windowIDDict = {};

  this._init();
}

BrowserElementChild.prototype = {
  _init() {
    debug("Starting up.");

    BrowserElementPromptService.mapWindowToBrowserElementChild(content, this);

    this._shuttingDown = false;

    LISTENED_EVENTS.forEach(event => {
      addEventListener(
        event.type,
        this,
        event.useCapture,
        event.wantsUntrusted
      );
    });

    addMessageListener("browser-element-api:call", this);
  },

  /**
   * Shut down the frame's side of the browser API.  This is called when:
   *   - our BrowserChildGlobal starts to die
   *   - the content is moved to frame without the browser API
   * This is not called when the page inside |content| unloads.
   */
  destroy() {
    debug("Destroying");
    this._shuttingDown = true;

    BrowserElementPromptService.unmapWindowToBrowserElementChild(content);

    LISTENED_EVENTS.forEach(event => {
      removeEventListener(
        event.type,
        this,
        event.useCapture,
        event.wantsUntrusted
      );
    });

    removeMessageListener("browser-element-api:call", this);
  },

  handleEvent(event) {
    switch (event.type) {
      case "unload":
        this.destroy(event);
        break;
    }
  },

  receiveMessage(message) {
    let self = this;

    let mmCalls = {
      "unblock-modal-prompt": this._recvStopWaiting,
    };

    if (message.data.msg_name in mmCalls) {
      return mmCalls[message.data.msg_name].apply(self, arguments);
    }
    return undefined;
  },

  get _windowUtils() {
    return content.document.defaultView.windowUtils;
  },

  _tryGetInnerWindowID(win) {
    try {
      return win.windowGlobalChild.innerWindowId;
    } catch (e) {
      return null;
    }
  },

  /**
   * Show a modal prompt.  Called by BrowserElementPromptService.
   */
  showModalPrompt(win, args) {
    args.windowID = {
      outer: win.docShell.outerWindowID,
      inner: this._tryGetInnerWindowID(win),
    };
    sendAsyncMsg("showmodalprompt", args);

    let returnValue = this._waitForResult(win);

    if (
      args.promptType == "prompt" ||
      args.promptType == "confirm" ||
      args.promptType == "custom-prompt"
    ) {
      return returnValue;
    }
    return undefined;
  },

  /**
   * Spin in a nested event loop until we receive a unblock-modal-prompt message for
   * this window.
   */
  _waitForResult(win) {
    debug("_waitForResult(" + win + ")");
    let utils = win.windowUtils;

    let outerWindowID = win.docShell.outerWindowID;
    let innerWindowID = this._tryGetInnerWindowID(win);
    if (innerWindowID === null) {
      // I have no idea what waiting for a result means when there's no inner
      // window, so let's just bail.
      debug("_waitForResult: No inner window. Bailing.");
      return undefined;
    }

    this._windowIDDict[outerWindowID] = Cu.getWeakReference(win);

    debug(
      "Entering modal state (outerWindowID=" +
        outerWindowID +
        ", " +
        "innerWindowID=" +
        innerWindowID +
        ")"
    );

    utils.enterModalState();

    // We'll decrement win.modalDepth when we receive a unblock-modal-prompt message
    // for the window.
    if (!win.modalDepth) {
      win.modalDepth = 0;
    }
    win.modalDepth++;
    let origModalDepth = win.modalDepth;

    debug("Nested event loop - begin");
    Services.tm.spinEventLoopUntil(() => {
      // Bail out of the loop if the inner window changed; that means the
      // window navigated.  Bail out when we're shutting down because otherwise
      // we'll leak our window.
      if (this._tryGetInnerWindowID(win) !== innerWindowID) {
        debug(
          "_waitForResult: Inner window ID changed " +
            "while in nested event loop."
        );
        return true;
      }

      return win.modalDepth !== origModalDepth || this._shuttingDown;
    });
    debug("Nested event loop - finish");

    if (win.modalDepth == 0) {
      delete this._windowIDDict[outerWindowID];
    }

    // If we exited the loop because the inner window changed, then bail on the
    // modal prompt.
    if (innerWindowID !== this._tryGetInnerWindowID(win)) {
      throw Components.Exception(
        "Modal state aborted by navigation",
        Cr.NS_ERROR_NOT_AVAILABLE
      );
    }

    let returnValue = win.modalReturnValue;
    delete win.modalReturnValue;

    if (!this._shuttingDown) {
      utils.leaveModalState();
    }

    debug(
      "Leaving modal state (outerID=" +
        outerWindowID +
        ", " +
        "innerID=" +
        innerWindowID +
        ")"
    );
    return returnValue;
  },

  _recvStopWaiting(msg) {
    let outerID = msg.json.windowID.outer;
    let innerID = msg.json.windowID.inner;
    let returnValue = msg.json.returnValue;
    debug(
      "recvStopWaiting(outer=" +
        outerID +
        ", inner=" +
        innerID +
        ", returnValue=" +
        returnValue +
        ")"
    );

    if (!this._windowIDDict[outerID]) {
      debug("recvStopWaiting: No record of outer window ID " + outerID);
      return;
    }

    let win = this._windowIDDict[outerID].get();

    if (!win) {
      debug("recvStopWaiting, but window is gone\n");
      return;
    }

    if (innerID !== this._tryGetInnerWindowID(win)) {
      debug("recvStopWaiting, but inner ID has changed\n");
      return;
    }

    debug("recvStopWaiting " + win);
    win.modalReturnValue = returnValue;
    win.modalDepth--;
  },
};

var api = new BrowserElementChild();