helpers.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. 'use strict';
  5. const { defer } = require('../core/promise');
  6. const events = require('../system/events');
  7. const { open: openWindow, onFocus, getToplevelWindow,
  8. isInteractive, getOuterId } = require('./utils');
  9. const { Ci } = require("chrome");
  10. function open(uri, options) {
  11. return promise(openWindow.apply(null, arguments), 'load');
  12. }
  13. exports.open = open;
  14. function close(window) {
  15. let deferred = defer();
  16. let toplevelWindow = getToplevelWindow(window);
  17. let outerId = getOuterId(toplevelWindow);
  18. events.on("outer-window-destroyed", function onclose({subject}) {
  19. let id = subject.QueryInterface(Ci.nsISupportsPRUint64).data;
  20. if (id == outerId) {
  21. events.off("outer-window-destroyed", onclose);
  22. deferred.resolve();
  23. }
  24. }, true);
  25. window.close();
  26. return deferred.promise;
  27. }
  28. exports.close = close;
  29. function focus(window) {
  30. let p = onFocus(window);
  31. window.focus();
  32. return p;
  33. }
  34. exports.focus = focus;
  35. function ready(window) {
  36. let { promise: result, resolve } = defer();
  37. if (isInteractive(window))
  38. resolve(window);
  39. else
  40. resolve(promise(window, 'DOMContentLoaded'));
  41. return result;
  42. }
  43. exports.ready = ready;
  44. function promise(target, evt, capture) {
  45. let deferred = defer();
  46. capture = !!capture;
  47. target.addEventListener(evt, function eventHandler() {
  48. target.removeEventListener(evt, eventHandler, capture);
  49. deferred.resolve(target);
  50. }, capture);
  51. return deferred.promise;
  52. }
  53. exports.promise = promise;