summaryrefslogtreecommitdiffstats
path: root/dom/tests/mochitest/bugs/utils_bug260264.js
blob: dfb0eb45a04421031320e0ecdc03b92fb82567de (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
const ALLOW_ACTION = SpecialPowers.Ci.nsIPermissionManager.ALLOW_ACTION;
const DENY_ACTION = SpecialPowers.Ci.nsIPermissionManager.DENY_ACTION;
const UNKNOWN_ACTION = SpecialPowers.Ci.nsIPermissionManager.UNKNOWN_ACTION;
const PROMPT_ACTION = SpecialPowers.Ci.nsIPermissionManager.PROMPT_ACTION;

/**
 * Dispatches |handler| to |element|, as if fired in response to |event|.
 */
function send(element, event, handler) {
  function unique_handler() {
    return handler.apply(this, arguments);
  }
  element.addEventListener(event, unique_handler);
  try {
    sendMouseEvent({ type: event }, element.id);
  } finally {
    element.removeEventListener(event, unique_handler);
  }
}

/**
 * Because it's not nice to leave popup windows open after the tests are
 * finished, we need a foolproof way to close some/all window.opened windows.
 */
(function (originalOpen) {
  var wins = [];
  (window.open = function () {
    var win = originalOpen.apply(window, arguments);
    if (win) {
      wins[wins.length] = win;
    }
    return win;
  }).close = function (n) {
    var promises = [];
    if (arguments.length < 1) {
      n = wins.length;
    }
    while (n-- > 0) {
      var win = wins.pop();
      if (win) {
        let openedBrowsingContextID = SpecialPowers.getBrowsingContextID(win);
        promises.push(
          (function (openedWindow) {
            return new Promise(function (resolve) {
              let observer = {
                observe(subject) {
                  if (subject.id == openedBrowsingContextID) {
                    SpecialPowers.removeObserver(
                      observer,
                      "browsing-context-discarded"
                    );
                    SimpleTest.executeSoon(resolve);
                  }
                },
              };

              SpecialPowers.addObserver(observer, "browsing-context-discarded");
            });
          })(win)
        );
        win.close();
      } else {
        promises.push(Promise.resolve());
        break;
      }
    }
    return Promise.all(promises);
  };
})(window.open);