summaryrefslogtreecommitdiffstats
path: root/netwerk/test/mochitests/file_testcommon.js
blob: c010f84aebe29889f11e5dd0e5965fb1c05c1810 (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
/* eslint-env mozilla/frame-script */

"use strict";

const SCRIPT_URL = SimpleTest.getTestFileURL("file_chromecommon.js");

var gExpectedCookies;
var gExpectedLoads;

var gPopup;

var gScript;

var gLoads = 0;

function setupTest(uri, cookies, loads) {
  SimpleTest.waitForExplicitFinish();

  var prefSet = new Promise(resolve => {
    SpecialPowers.pushPrefEnv(
      {
        set: [
          ["network.cookie.cookieBehavior", 1],
          // cookieBehavior 1 allows cookies from chrome script if we enable
          // exceptions.
          ["network.cookie.rejectForeignWithExceptions.enabled", false],
        ],
      },
      resolve
    );
  });

  gScript = SpecialPowers.loadChromeScript(SCRIPT_URL);
  gExpectedCookies = cookies;
  gExpectedLoads = loads;

  // Listen for MessageEvents.
  window.addEventListener("message", messageReceiver);

  prefSet.then(() => {
    // load a window which contains an iframe; each will attempt to set
    // cookies from their respective domains.
    gPopup = window.open(uri, "hai", "width=100,height=100");
  });
}

function finishTest() {
  gScript.destroy();
  SimpleTest.finish();
}

/** Receives MessageEvents to this window. */
// Count and check loads.
function messageReceiver(evt) {
  is(evt.data, "message", "message data received from popup");
  if (evt.data != "message") {
    gPopup.close();
    window.removeEventListener("message", messageReceiver);

    finishTest();
    return;
  }

  // only run the test when all our children are done loading & setting cookies
  if (++gLoads == gExpectedLoads) {
    gPopup.close();
    window.removeEventListener("message", messageReceiver);

    runTest();
  }
}

// runTest() is run by messageReceiver().
// Count and check cookies.
function runTest() {
  // set a cookie from a domain of "localhost"
  document.cookie = "oh=hai";

  gScript.addMessageListener("getCookieCountAndClear:return", ({ count }) => {
    is(count, gExpectedCookies, "total number of cookies");
    finishTest();
  });
  gScript.sendAsyncMessage("getCookieCountAndClear");
}