summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/test/xpcshell/test_ext_scripting_contentScripts.js
blob: a06f34a1b46e97e2ab6d9fe3a526fd7ad4d39994 (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
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
"use strict";

const server = createHttpServer();
server.registerDirectory("/data/", do_get_file("data"));

const BASE_URL = `http://localhost:${server.identity.primaryPort}/data`;

// ExtensionContent.jsm needs to know when it's running from xpcshell, to use
// the right timeout for content scripts executed at document_idle.
ExtensionTestUtils.mockAppInfo();

Services.prefs.setBoolPref("extensions.manifestV3.enabled", true);

const makeExtension = ({ manifest: manifestProps, ...otherProps }) => {
  return ExtensionTestUtils.loadExtension({
    manifest: {
      manifest_version: 3,
      permissions: ["scripting"],
      host_permissions: ["http://localhost/*"],
      granted_host_permissions: true,
      ...manifestProps,
    },
    temporarilyInstalled: true,
    ...otherProps,
  });
};

add_task(async function test_registerContentScripts_runAt() {
  let extension = makeExtension({
    async background() {
      const TEST_CASES = [
        {
          title: "runAt: document_idle",
          params: [
            {
              id: "script-idle",
              js: ["script-idle.js"],
              matches: ["http://*/*/file_sample.html"],
              runAt: "document_idle",
              persistAcrossSessions: false,
            },
          ],
        },
        {
          title: "no runAt specified",
          params: [
            {
              id: "script-idle-default",
              js: ["script-idle-default.js"],
              matches: ["http://*/*/file_sample.html"],
              // `runAt` defaults to `document_idle`.
              persistAcrossSessions: false,
            },
          ],
        },
        {
          title: "runAt: document_end",
          params: [
            {
              id: "script-end",
              js: ["script-end.js"],
              matches: ["http://*/*/file_sample.html"],
              runAt: "document_end",
              persistAcrossSessions: false,
            },
          ],
        },
        {
          title: "runAt: document_start",
          params: [
            {
              id: "script-start",
              js: ["script-start.js"],
              matches: ["http://*/*/file_sample.html"],
              runAt: "document_start",
              persistAcrossSessions: false,
            },
          ],
        },
      ];

      let scripts = await browser.scripting.getRegisteredContentScripts();
      browser.test.assertEq(0, scripts.length, "expected no registered script");

      for (const { title, params } of TEST_CASES) {
        const res = await browser.scripting.registerContentScripts(params);
        browser.test.assertEq(undefined, res, `${title} - expected no result`);
      }

      scripts = await browser.scripting.getRegisteredContentScripts();
      browser.test.assertEq(
        TEST_CASES.length,
        scripts.length,
        `expected ${TEST_CASES.length} registered scripts`
      );
      browser.test.assertEq(
        JSON.stringify([
          {
            id: "script-idle",
            allFrames: false,
            matches: ["http://*/*/file_sample.html"],
            runAt: "document_idle",
            persistAcrossSessions: false,
            js: ["script-idle.js"],
          },
          {
            id: "script-idle-default",
            allFrames: false,
            matches: ["http://*/*/file_sample.html"],
            runAt: "document_idle",
            persistAcrossSessions: false,
            js: ["script-idle-default.js"],
          },
          {
            id: "script-end",
            allFrames: false,
            matches: ["http://*/*/file_sample.html"],
            runAt: "document_end",
            persistAcrossSessions: false,
            js: ["script-end.js"],
          },
          {
            id: "script-start",
            allFrames: false,
            matches: ["http://*/*/file_sample.html"],
            runAt: "document_start",
            persistAcrossSessions: false,
            js: ["script-start.js"],
          },
        ]),
        JSON.stringify(scripts),
        "got expected scripts"
      );

      browser.test.sendMessage("background-ready");
    },
    files: {
      "script-start.js": () => {
        browser.test.assertEq(
          "loading",
          document.readyState,
          "expected state 'loading' at document_start"
        );
        browser.test.sendMessage("script-ran", "script-start.js");
      },
      "script-end.js": () => {
        browser.test.assertTrue(
          ["interactive", "complete"].includes(document.readyState),
          `expected state 'interactive' or 'complete' at document_end, got: ${document.readyState}`
        );
        browser.test.sendMessage("script-ran", "script-end.js");
      },
      "script-idle.js": () => {
        browser.test.assertEq(
          "complete",
          document.readyState,
          "expected state 'complete' at document_idle"
        );
        browser.test.sendMessage("script-ran", "script-idle.js");
      },
      "script-idle-default.js": () => {
        browser.test.assertEq(
          "complete",
          document.readyState,
          "expected state 'complete' at document_idle"
        );
        browser.test.sendMessage("script-ran", "script-idle-default.js");
      },
    },
  });

  let scriptsRan = [];
  let completePromise = new Promise(resolve => {
    extension.onMessage("script-ran", result => {
      scriptsRan.push(result);

      // The value below should be updated when TEST_CASES above is changed.
      if (scriptsRan.length === 4) {
        resolve();
      }
    });
  });

  await extension.startup();
  await extension.awaitMessage("background-ready");

  let contentPage = await ExtensionTestUtils.loadContentPage(
    `${BASE_URL}/file_sample.html`
  );

  await completePromise;

  Assert.deepEqual(
    [
      "script-start.js",
      "script-end.js",
      "script-idle.js",
      "script-idle-default.js",
    ],
    scriptsRan,
    "got expected executed scripts"
  );

  await contentPage.close();
  await extension.unload();
});

add_task(async function test_register_and_unregister() {
  let extension = makeExtension({
    async background() {
      const script = {
        id: "a-script",
        js: ["script.js"],
        matches: ["http://*/*/file_sample.html"],
        persistAcrossSessions: false,
      };

      let results = await Promise.allSettled([
        browser.scripting.registerContentScripts([script]),
        browser.scripting.unregisterContentScripts(),
      ]);

      browser.test.assertEq(
        2,
        results.filter(result => result.status === "fulfilled").length,
        "got expected number of fulfilled promises"
      );

      let scripts = await browser.scripting.getRegisteredContentScripts();
      browser.test.assertEq(0, scripts.length, "expected no registered script");

      browser.test.sendMessage("background-done");
    },
    files: {
      "script.js": "",
    },
  });

  await extension.startup();
  await extension.awaitMessage("background-done");

  // Verify that the registered content scripts on the extension are correct.
  let contentScripts = Array.from(
    extension.extension.registeredContentScripts.values()
  );
  Assert.equal(0, contentScripts.length, "expected no registered scripts");

  await extension.unload();
});

add_task(async function test_register_and_unregister_multiple_times() {
  let extension = makeExtension({
    async background() {
      // We use the same script `id` on purpose in this test.
      let results = await Promise.allSettled([
        browser.scripting.registerContentScripts([
          {
            id: "a-script",
            js: ["script-1.js"],
            matches: ["http://*/*/file_sample.html"],
            persistAcrossSessions: false,
          },
        ]),
        browser.scripting.unregisterContentScripts(),
        browser.scripting.registerContentScripts([
          {
            id: "a-script",
            js: ["script-2.js"],
            matches: ["http://*/*/file_sample.html"],
            persistAcrossSessions: false,
          },
        ]),
        browser.scripting.unregisterContentScripts(),
        browser.scripting.registerContentScripts([
          {
            id: "a-script",
            js: ["script-3.js"],
            matches: ["http://*/*/file_sample.html"],
            persistAcrossSessions: false,
          },
        ]),
      ]);

      browser.test.assertEq(
        5,
        results.filter(result => result.status === "fulfilled").length,
        "got expected number of fulfilled promises"
      );

      let scripts = await browser.scripting.getRegisteredContentScripts();
      browser.test.assertEq(1, scripts.length, "expected 1 registered script");

      browser.test.sendMessage("background-done");
    },
    files: {
      "script-1.js": "",
      "script-2.js": "",
      "script-3.js": "",
    },
  });

  await extension.startup();
  await extension.awaitMessage("background-done");

  // Verify that the registered content scripts on the extension are correct.
  let contentScripts = Array.from(
    extension.extension.registeredContentScripts.values()
  );
  Assert.equal(1, contentScripts.length, "expected 1 registered script");
  Assert.ok(
    contentScripts[0].jsPaths[0].endsWith("script-3.js"),
    "got expected js file"
  );

  await extension.unload();
});

add_task(async function test_register_update_and_unregister() {
  let extension = makeExtension({
    async background() {
      const script = {
        id: "a-script",
        js: ["script-1.js"],
        matches: ["http://*/*/file_sample.html"],
        persistAcrossSessions: false,
      };
      const updatedScript1 = { ...script, js: ["script-2.js"] };
      const updatedScript2 = { ...script, js: ["script-3.js"] };

      let results = await Promise.allSettled([
        browser.scripting.registerContentScripts([script]),
        browser.scripting.updateContentScripts([updatedScript1]),
        browser.scripting.updateContentScripts([updatedScript2]),
        browser.scripting.getRegisteredContentScripts(),
        browser.scripting.unregisterContentScripts(),
        browser.scripting.updateContentScripts([script]),
      ]);

      browser.test.assertEq(6, results.length, "expected 6 results");
      browser.test.assertEq(
        "fulfilled",
        results[0].status,
        "expected fulfilled promise (registeredContentScripts)"
      );
      browser.test.assertEq(
        "fulfilled",
        results[1].status,
        "expected fulfilled promise (updateContentScripts)"
      );
      browser.test.assertEq(
        "fulfilled",
        results[2].status,
        "expected fulfilled promise (updateContentScripts)"
      );
      browser.test.assertEq(
        "fulfilled",
        results[3].status,
        "expected fulfilled promise (getRegisteredContentScripts)"
      );
      browser.test.assertEq(
        JSON.stringify([
          {
            id: "a-script",
            allFrames: false,
            matches: ["http://*/*/file_sample.html"],
            runAt: "document_idle",
            persistAcrossSessions: false,
            js: ["script-3.js"],
          },
        ]),
        JSON.stringify(results[3].value),
        "expected updated content script"
      );
      browser.test.assertEq(
        "fulfilled",
        results[4].status,
        "expected fulfilled promise (unregisterContentScripts)"
      );
      browser.test.assertEq(
        "rejected",
        results[5].status,
        "expected rejected promise because script should have been unregistered"
      );
      browser.test.assertEq(
        `Content script with id "${script.id}" does not exist.`,
        results[5].reason.message,
        "expected error message about script not found"
      );

      let scripts = await browser.scripting.getRegisteredContentScripts();
      browser.test.assertEq(0, scripts.length, "expected no registered script");

      browser.test.sendMessage("background-done");
    },
    files: {
      "script-1.js": "",
      "script-2.js": "",
      "script-3.js": "",
    },
  });

  await extension.startup();
  await extension.awaitMessage("background-done");

  // Verify that the registered content scripts on the extension are correct.
  let contentScripts = Array.from(
    extension.extension.registeredContentScripts.values()
  );
  Assert.equal(0, contentScripts.length, "expected no registered scripts");

  await extension.unload();
});

// The following test case is a regression test for Bug 1851173.
add_task(
  {
    // contentScripts API not exposed to background service workers and
    // Bug 1851173 can't be hit.
    skip_if: () => ExtensionTestUtils.isInBackgroundServiceWorkerTests(),
  },
  async function test_contentScriptsAPI_vs_scriptingGetRegistered() {
    let extension = ExtensionTestUtils.loadExtension({
      manifest: {
        manifest_version: 2,
        permissions: ["scripting", "<all_urls>"],
      },
      async background() {
        await browser.contentScripts.register({
          runAt: "document_start",
          js: [{ file: "testcs.js" }],
          matches: ["<all_urls>"],
        });

        const scriptingScripts =
          await browser.scripting.getRegisteredContentScripts();
        browser.test.assertDeepEq(
          [],
          scriptingScripts,
          "Expect an empty array"
        );
        browser.test.sendMessage("background-done");
      },
      files: {
        "testcs.js": "",
      },
    });

    await extension.startup();
    await extension.awaitMessage("background-done");
    await extension.unload();
  }
);

async function test_matchAboutBlank_registerContentScripts_default({
  extId,
  expectedMatchAboutBlankValue,
}) {
  let extension = ExtensionTestUtils.loadExtension({
    manifest: {
      manifest_version: 2,
      permissions: ["scripting", "<all_urls>"],
      browser_specific_settings: {
        gecko: { id: extId },
      },
    },
    async background() {
      await browser.scripting.registerContentScripts([
        {
          id: "test-content-script",
          matches: ["http://example.com/*"],
          js: ["cs.js"],
        },
      ]);
      browser.test.sendMessage("background-done");
    },
    file: {
      "cs.js": "",
    },
  });

  await extension.startup();
  await extension.awaitMessage("background-done");

  equal(
    extension.extension.registeredContentScripts.size,
    1,
    "Got the expected number of registered content scripts"
  );
  const [{ id, matchAboutBlank }] = Array.from(
    extension.extension.registeredContentScripts.values()
  );

  equal(id, "test-content-script", "Got the expected content script id");
  equal(
    matchAboutBlank,
    expectedMatchAboutBlankValue,
    "Expect matchAboutBlank to be false"
  );

  await extension.unload();
}

// The following test cases are regressions test for Bug 1853412, and it is
// currently making sure that content scripts registered dynamically
// by the webcompat built-in have matchAboutBlank set to false.
add_task(async function test_webcompat_matchAboutBlank_default() {
  await test_matchAboutBlank_registerContentScripts_default({
    // This test extension has to have the same id that we expect
    // the webcompat built-in to have.
    extId: "webcompat@mozilla.org",
    expectedMatchAboutBlankValue: false,
  });
});

// The following test task asserts that for any extension matchAboutBlank
// is still set by default to true
// TODO(Bug 1853411): should change this to default to false for all extensions
// and this test should be adjusted accordingly.
add_task(async function test_matchAboutBlank_default() {
  await test_matchAboutBlank_registerContentScripts_default({
    extId: "some-unknown-extension-id@test.extension",
    expectedMatchAboutBlankValue: true,
  });
});

// The following test task asserts that when the hidden pref
// "extensions.scripting.matchAboutBlankDefaultFalse" is set
// to true, then matchAboutBlank gets forcefully set to false
// TODO(Bug 1853411): may remove the hidden pref and this test along with it.
add_task(
  {
    pref_set: [["extensions.scripting.matchAboutBlankDefaultFalse", true]],
  },
  async function test_matchAboutBlank_defaultChange_by_hiddenPref() {
    await test_matchAboutBlank_registerContentScripts_default({
      extId: "some-unknown-extension-id@test.extension",
      expectedMatchAboutBlankValue: false,
    });
  }
);