File: test_ext_contentscript_about_blank.html

package info (click to toggle)
firefox 142.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,591,884 kB
  • sloc: cpp: 7,451,570; javascript: 6,392,463; ansic: 3,712,584; python: 1,388,569; xml: 629,223; asm: 426,919; java: 184,857; sh: 63,439; makefile: 19,150; objc: 13,059; perl: 12,983; yacc: 4,583; cs: 3,846; pascal: 3,352; lex: 1,720; ruby: 1,003; exp: 762; php: 436; lisp: 258; awk: 247; sql: 66; sed: 53; csh: 10
file content (360 lines) | stat: -rw-r--r-- 12,204 bytes parent folder | download | duplicates (4)
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
<!doctype html>
<html>
<head>
  <title>Test content script match_about_blank option</title>
  <script src="/tests/SimpleTest/SimpleTest.js"></script>
  <script src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
  <script src="head.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
</head>
<body>

<script type="text/javascript">
"use strict";

// Tests that match_about_blank matches at the expected URLs:
// - about:blank and about:srcdoc (as documented)
// - javascript:-URL (loaded in about:blank document)
// - blob: (not documented, not supported by Chrome, legacy behavior)
add_task(async function test_contentscript_about_blank() {
  const manifest = {
    content_scripts: [
      {
        match_about_blank: true,
        matches: [
          "*://mochi.test/*/file_with_about_blank.html",
          "https://example.com/*/file_with_about_blank.html",
        ],
        all_frames: true,
        css: ["all.css"],
        js: ["all.js"],
      }, {
        matches: ["*://mochi.test/*/file_with_about_blank.html"],
        css: ["mochi_without.css"],
        js: ["mochi_without.js"],
        all_frames: true,
      }, {
        match_about_blank: true,
        matches: ["*://mochi.test/*/file_with_about_blank.html"],
        css: ["mochi_with.css"],
        js: ["mochi_with.js"],
        all_frames: true,
      },
    ],
  };

  const files = {
    "all.js": function() {
      browser.runtime.sendMessage("all");
    },
    "all.css": `
      body { color: red; }
    `,
    "mochi_without.js": function() {
      browser.runtime.sendMessage("mochi_without");
    },
    "mochi_without.css": `
      body { background: yellow; }
    `,
    "mochi_with.js": function() {
      browser.runtime.sendMessage("mochi_with");
    },
    "mochi_with.css": `
      body { text-align: right; }
    `,
  };

  function background() {
    browser.runtime.onMessage.addListener((script, {url}) => {
      // In this test, we only load http(s):-URLs at the top level.
      const kind = url.startsWith("http") ? "top" : url;
      browser.test.sendMessage("script", [script, kind, url]);
      browser.test.sendMessage(`${script}:${kind}`);
    });
  }

  const PATH = "tests/toolkit/components/extensions/test/mochitest/file_with_about_blank.html";
  const extension = ExtensionTestUtils.loadExtension({manifest, files, background});
  await extension.startup();

  let count = 0;
  extension.onMessage("script", script => {
    info(`script ran: ${script}`);
    count++;
  });

  let win = window.open("https://example.com/" + PATH);
  await Promise.all([
    extension.awaitMessage("all:top"),
    extension.awaitMessage("all:about:blank"),
    extension.awaitMessage("all:about:srcdoc"),
  ]);
  is(count, 3, "exactly 3 scripts ran");
  win.close();

  win = window.open("http://mochi.test:8888/" + PATH);
  await Promise.all([
    extension.awaitMessage("all:top"),
    extension.awaitMessage("all:about:blank"),
    extension.awaitMessage("all:about:srcdoc"),
    extension.awaitMessage("mochi_without:top"),
    extension.awaitMessage("mochi_with:top"),
    extension.awaitMessage("mochi_with:about:blank"),
    extension.awaitMessage("mochi_with:about:srcdoc"),
  ]);

  let style = win.getComputedStyle(win.document.body);
  is(style.color, "rgb(255, 0, 0)", "top window text color is red");
  is(style.backgroundColor, "rgb(255, 255, 0)", "top window background is yellow");
  is(style.textAlign, "right", "top window text is right-aligned");

  let a_b = win.document.getElementById("a_b");
  style = a_b.contentWindow.getComputedStyle(a_b.contentDocument.body);
  is(style.color, "rgb(255, 0, 0)", "about:blank iframe text color is red");
  is(style.backgroundColor, "rgba(0, 0, 0, 0)", "about:blank iframe background is transparent");
  is(style.textAlign, "right", "about:blank text is right-aligned");

  is(count, 10, "exactly 7 more scripts ran");
  count = 0;
  // win.close(); not called because we want to create a blob:-URL associated
  // with that document's principal, and also test other loads associated with
  // that principal.
  const winDocumentURL = win.document.URL;
  const htmlCode = win.document.documentElement.outerHTML;

  {
    info(`Testing about:blank toplevel popup from ${winDocumentURL}`);
    let blankWin = win.window.open("about:blank");
    await Promise.all([
      extension.awaitMessage("all:about:blank"),
      extension.awaitMessage("mochi_with:about:blank"),
    ]);
    blankWin.close();
    is(count, 2, "exactly 2 more scripts ran for toplevel about:blank");
    count = 0;
  }

  {
    info(`Testing javascript:-toplevel popup from ${winDocumentURL}`);
    let jsWin = win.window.open(`javascript:'<iframe srcdoc="x"></iframe>'`);
    await Promise.all([
      // javascript:-URLs are loaded in an about:blank document.
      extension.awaitMessage("all:about:blank"),
      extension.awaitMessage("mochi_with:about:blank"),
      extension.awaitMessage("all:about:srcdoc"),
      extension.awaitMessage("mochi_with:about:srcdoc"),
    ]);
    jsWin.close();
    is(count, 4, "exactly 4 more scripts ran for javascript:-URL with frame");
    count = 0;
  }

  const blob = new Blob([ htmlCode ], { type: "text/html" });
  const blobUrl = win.URL.createObjectURL(blob);
  info(`Opening blob:-URL: ${blobUrl} from ${win.document.URL}`);

  let blobWin = window.open(blobUrl);
  // blob:-URLs should not have content scripts because
  // match_origin_as_fallback is not set.
  await Promise.all([
    extension.awaitMessage("all:about:blank"),
    extension.awaitMessage("all:about:srcdoc"),
    extension.awaitMessage("mochi_with:about:blank"),
    extension.awaitMessage("mochi_with:about:srcdoc"),
  ]);
  is(count, 4, "exactly 4 more scripts ran for blob:-URL");
  count = 0;

  // Test coverage for execution on blob:-URLs is at
  // toolkit/components/extensions/test/mochitest/test_ext_contentscript_blob.html

  blobWin.close();
  win.close();

  await extension.unload();
});

async function top_level_about_blank({
  run_at = "document_end",
} = {}) {
  const content_scripts = [
    {
      match_about_blank: true,
      matches: ["*://*/*"],
      js: ["1.matches_any_url_and_blank.js"],
      run_at,
    },
    {
      // Note: interestingly, if one only wants to match top-level about:blank
      // in Firefox, this would be a way to do so:
      match_about_blank: true,
      matches: ["*://*/*"],
      exclude_matches: ["<all_urls>"],
      exclude_globs: ["*"],
      js: ["2.does_not_care_about_exclude_matches_globs.js"],
      run_at,
    },
    {
      match_about_blank: true,
      matches: ["*://*/*"],
      include_globs: ["*"],
      js: ["3.should_not_run_because_include_globs_is_set.js"],
      run_at,
    },
    {
      matches: ["*://*/*"],
      js: ["4.should_not_run_because_no_matchAboutBlank.js"],
      run_at,
    },
    {
      match_about_blank: true,
      matches: ["*://non.matching.example/*"],
      js: ["5.should_not_run_because_matches_does_not_match_all_urls.js"],
      run_at,
    },
  ];
  const files = {
    "get_seenScripts.js": () => {
      globalThis.seenScripts ??= [];
      globalThis.seenScripts.push("get_seenScripts.js");
      return globalThis.seenScripts;
    },
  };
  function makeJsFile(filename) {
    files[filename] = `
      dump("Running ${filename} at " + location + ", origin " + origin + "\\n");
      globalThis.seenScripts ??= [];
      globalThis.seenScripts.push("${filename}");
    `;

    if (filename === "2.does_not_care_about_exclude_matches_globs.js") {
      files[filename] += `
        // In an initial document, readyState = "uninitialized".
        dump("${filename} ran at readyState " + document.readyState + "\\n");
        browser.test.sendMessage("seen_content_script");
      `;
    }
  }
  for (let { js } of content_scripts) {
    for (let filename of js) {
      makeJsFile(filename);
    }
  }

  // Send an explicit test message in the last script which is expected to only
  // be injected if the legacy behavior pref is set to true, if this is sent
  // when running the test for the new expected behavior then hitting this message
  // will trigger an additional explicit test failure due to the non handled
  // "legacy-matching-script:executed" test message, on the contrary when
  // the test is executed for the legacy matchAboutBlank behavior the test
  // will await for that message explicitly to avoid intermittent failures.
  files["5.should_not_run_because_matches_does_not_match_all_urls.js"] += `
    browser.test.sendMessage("legacy-matching-script:executed");
  `;

  function background() {
    let tabId;
    browser.test.onMessage.addListener(async (msg, expected, description) => {
      if (msg === "openAboutBlankTab") {
        const tab = await browser.tabs.create({ url: "about:blank" });
        tabId = tab.id;
        browser.test.sendMessage("openAboutBlankTab_done");
        return;
      }
      if (msg === "closeAboutBlankTab") {
        await browser.tabs.remove(tabId);
        browser.test.sendMessage("closeAboutBlankTab_done");
        return;
      }
      browser.test.assertEq("seenScripts_check", msg, "Checking seenScripts");
      try {
        browser.test.log("Checking seen content scripts");
        let [ seenScripts ] = await browser.tabs.executeScript(
          tabId,
          {
            matchAboutBlank: true,
            file: "get_seenScripts.js",
          }
        );
        browser.test.assertDeepEq(expected, seenScripts.sort(), description);
      } catch (e) {
        browser.test.assertDeepEq(expected, { error: e.message }, description);
      }
      browser.test.sendMessage("seenScripts_check_done");
    });
    browser.browserAction.onClicked.addListener(tab => {
      browser.test.assertTrue(tab.active, "Active tab should be clicked");
      browser.test.assertEq(tabId, tab.id, "tabId should match");
      // Upon click, activeTab should be granted, so just return control.
      browser.test.sendMessage("got_activeTab");
    });
  }

  let extension = ExtensionTestUtils.loadExtension({
    manifest: {
      content_scripts,
      browser_action: {},
      permissions: ["activeTab"],
    },
    files,
    background,
  });

  async function openAboutBlankTab() {
    extension.sendMessage("openAboutBlankTab");
    await extension.awaitMessage("openAboutBlankTab_done");
  }
  async function closeAboutBlankTab() {
    extension.sendMessage("closeAboutBlankTab");
    await extension.awaitMessage("closeAboutBlankTab_done");
  }
  async function checkSeenScripts(expected, description) {
    extension.sendMessage("seenScripts_check", expected, description);
    await extension.awaitMessage("seenScripts_check_done");
  }

  await extension.startup();
  await openAboutBlankTab();

  info("Testing tabs.executeScript without activeTab/host permissions");
  await checkSeenScripts(
    { error: "Missing host permission for the tab" },
    "tabs.executeScript without activeTab shouldn't match top-level about:blank"
  );

  info("Unlocking activeTab permission");
  await AppTestDelegate.clickBrowserAction(window, extension);
  await extension.awaitMessage("got_activeTab");

  info("Retrieving result with tabs.executeScript with activeTab");
  await checkSeenScripts(
    [
      "1.matches_any_url_and_blank.js",
      "2.does_not_care_about_exclude_matches_globs.js",
      "get_seenScripts.js",
    ],
    "Only content content scripts that match all URLs and matchAboutBlank should run"
  );

  // We should receive only one such message; if we get more, odds are that we
  // unexpectedly executed in the initial about:blank that preceeds the final
  // about:blank (which is not supported - bug 1415539), or that we executed
  // in an unrelated about:blank document (as seen in bug 1901894).
  await extension.awaitMessage("seen_content_script");

  await closeAboutBlankTab();
  await extension.unload();
}

add_task(async function test_toplevel_aboutblank_at_document_start() {
  await top_level_about_blank({ run_at: "document_start" });
});

add_task(async function test_toplevel_aboutblank_match_with_permissions() {
  await top_level_about_blank();
});

</script>

</body>
</html>