summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/test/mochitest/test_ext_scripting_insertCSS.html
blob: 3e2cef87214d28d29bf9c8b639d15cfd37152fe3 (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
<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">
  <title>Tests scripting.insertCSS()</title>
  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
  <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
  <script type="text/javascript" src="head.js"></script>
  <link rel="stylesheet" href="/tests/SimpleTest/test.css"/>
</head>
<body>

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

const MOCHITEST_HOST_PERMISSIONS = [
  "*://mochi.test/",
  "*://mochi.xorigin-test/",
  "*://test1.example.com/",
];

const makeExtension = ({ manifest: manifestProps, ...otherProps }) => {
  return ExtensionTestUtils.loadExtension({
    manifest: {
      manifest_version: 3,
      permissions: ["scripting"],
      host_permissions: [
        ...MOCHITEST_HOST_PERMISSIONS,
        // Used in `file_contains_iframe.html`
        "https://example.org/",
      ],
      granted_host_permissions: true,
      ...manifestProps,
    },
    useAddonManager: "temporary",
    ...otherProps,
  });
};

add_task(async function setup() {
  await SpecialPowers.pushPrefEnv({
    set: [["extensions.manifestV3.enabled", true]],
  });
});

add_task(async function test_insertCSS_and_removeCSS_params_validation() {
  let extension = makeExtension({
    async background() {
      const tabs = await browser.tabs.query({ active: true });

      const TEST_CASES = [
        {
          title: "no files and no css",
          cssParams: {},
          expectedError: "Exactly one of files and css must be specified.",
        },
        {
          title: "both files and css are passed",
          cssParams: {
            files: ["styles.css"],
            css: "* { background: rgb(1, 1, 1) }",
          },
          expectedError: "Exactly one of files and css must be specified.",
        },
        {
          title: "both allFrames and frameIds are passed",
          cssParams: {
            target: {
              tabId: tabs[0].id,
              allFrames: true,
              frameIds: [1, 2, 3],
            },
            files: ["styles.css"],
          },
          expectedError: "Cannot specify both 'allFrames' and 'frameIds'.",
        },
        {
          title: "empty css string with a file",
          cssParams: {
            css: "",
            files: ["styles.css"],
          },
          expectedError: "Exactly one of files and css must be specified.",
        },
      ];

      for (const { title, cssParams, expectedError } of TEST_CASES) {
        await browser.test.assertRejects(
          browser.scripting.insertCSS({
            target: { tabId: tabs[0].id },
            ...cssParams,
          }),
          expectedError,
          `${title} - expected error for insertCSS()`
        );

        await browser.test.assertRejects(
          browser.scripting.removeCSS({
            target: { tabId: tabs[0].id },
            ...cssParams,
          }),
          expectedError,
          `${title} - expected error for removeCSS()`
        );
      }

      browser.test.notifyPass("checks-done");
    },
  });

  await extension.startup();
  await extension.awaitFinish("checks-done");
  await extension.unload();
});

add_task(async function test_insertCSS_with_invalid_tabId() {
  let extension = makeExtension({
    async background() {
      // This tab ID should not exist.
      const tabId = 123456789;

      await browser.test.assertRejects(
        browser.scripting.insertCSS({
          target: { tabId },
          css: "* { background: rgb(1, 1, 1) }",
        }),
        `Invalid tab ID: ${tabId}`
      );

      browser.test.notifyPass("insert-css");
    },
  });

  await extension.startup();
  await extension.awaitFinish("insert-css");
  await extension.unload();
});

add_task(async function test_insertCSS_with_wrong_host_permissions() {
  let extension = makeExtension({
    manifest: {
      host_permissions: [],
    },
    async background() {
      const tabs = await browser.tabs.query({ active: true });

      browser.test.assertEq(1, tabs.length, "expected 1 tab");

      browser.test.assertRejects(
        browser.scripting.insertCSS({
          target: { tabId: tabs[0].id },
          css: "* { background: rgb(1, 1, 1) }",
        }),
        /Missing host permission for the tab/,
        "expected host permission error"
      );

      browser.test.notifyPass("insert-css");
    },
  });

  await extension.startup();
  await extension.awaitFinish("insert-css");
  await extension.unload();
});

add_task(async function test_insertCSS_and_removeCSS() {
  let extension = makeExtension({
    manifest: {
      permissions: ["scripting", "webNavigation"],
    },
    async background() {
      const tabs = await browser.tabs.query({ active: true });
      browser.test.assertEq(1, tabs.length, "expected 1 tab");

      const tabId = tabs[0].id;

      const frames = await browser.webNavigation.getAllFrames({ tabId });
      // 1. Top-level frame that loads `file_contains_iframe.html`
      // 2. Frame that loads `file_contains_img.html`
      browser.test.assertEq(2, frames.length, "expected 2 frames");
      const frameIds = frames.map(frame => frame.frameId);

      const cssColor1 = "rgb(1, 1, 1)";
      const cssColor2 = "rgb(2, 2, 2)";
      const cssColorInFile1 = "rgb(3, 3, 3)";
      const defaultColor = "rgba(0, 0, 0, 0)";

      const TEST_CASES = [
        {
          title: "with css prop",
          elementId: "div-1",
          cssParams: [
            {
              target: { tabId },
              css: `#div-1 { background: ${cssColor1} }`,
            },
          ],
          expectedResults: [cssColor1, defaultColor],
        },
        {
          title: "with a file",
          elementId: "div-2",
          cssParams: [
            {
              target: { tabId },
              files: ["file1.css"],
            },
          ],
          expectedResults: [cssColorInFile1, defaultColor],
        },
        {
          title: "css prop in a single frame",
          elementId: "div-3",
          cssParams: [
            {
              target: { tabId, frameIds: [frameIds[0]] },
              css: `#div-3 { background: ${cssColor2} }`,
            },
          ],
          expectedResults: [cssColor2, defaultColor],
        },
        {
          title: "css prop in multiple frames",
          elementId: "div-4",
          cssParams: [
            {
              target: { tabId, frameIds },
              css: `#div-4 { background: ${cssColor1} }`,
            },
          ],
          expectedResults: [cssColor1, cssColor1],
        },
        {
          title: "allFrames is true",
          elementId: "div-5",
          cssParams: [
            {
              target: { tabId, allFrames: true },
              css: `#div-5 { background: ${defaultColor} }`,
            },
          ],
          expectedResults: [defaultColor, defaultColor],
        },
        {
          title: "origin: 'AUTHOR'",
          elementId: "div-6",
          cssParams: [
            {
              target: { tabId },
              css: `#div-6 { background: ${cssColor1} }`,
              origin: "AUTHOR",
            },
            {
              target: { tabId },
              css: `#div-6 { background: ${cssColor2} }`,
              origin: "AUTHOR",
            },
          ],
          expectedResults: [cssColor2, defaultColor],
        },
        {
          title: "origin: 'USER'",
          elementId: "div-7",
          cssParams: [
            {
              target: { tabId },
              css: `#div-7 { background: ${cssColor1} !important }`,
              origin: "USER",
            },
            {
              target: { tabId },
              css: `#div-7 { background: ${cssColor2} !important }`,
              origin: "AUTHOR",
            },
          ],
          // User has higher importance.
          expectedResults: [cssColor1, defaultColor],
        },
        {
          title: "empty css string",
          elementId: "div-8",
          cssParams: [
            {
              target: { tabId },
              css: "",
            },
          ],
          expectedResults: [defaultColor, defaultColor],
        },
        {
          title: "allFrames is false",
          elementId: "div-9",
          cssParams: [
            {
              target: { tabId, allFrames: false },
              css: `#div-9 { background: ${cssColor1} }`,
            },
          ],
          expectedResults: [cssColor1, defaultColor],
        },
      ];

      const getBackgroundColor = elementId => {
        return window.getComputedStyle(document.getElementById(elementId))
          .backgroundColor;
      };

      for (const {
        title,
        elementId,
        cssParams,
        expectedResults,
      } of TEST_CASES) {
        // Create a unique element for the current test case.
        await browser.scripting.executeScript({
          target: { tabId, allFrames: true },
          func: elementId => {
            const element = document.createElement("div");
            element.setAttribute("id", elementId);
            document.body.appendChild(element);
          },
          args: [elementId],
        });

        for (const params of cssParams) {
          const result = await browser.scripting.insertCSS(params);
          // `insertCSS()` should not resolve to a value.
          browser.test.assertEq(undefined, result, "got expected empty result");
        }

        let results = await browser.scripting.executeScript({
          target: { tabId, allFrames: true },
          func: getBackgroundColor,
          args: [elementId],
        });
        results.sort((a, b) => a.frameId - b.frameId);

        browser.test.assertEq(
          expectedResults.length,
          results.length,
          `${title} - got the expected number of results`
        );
        results.forEach((result, index) => {
          browser.test.assertEq(
            expectedResults[index],
            result.result,
            `${title} - got expected result (index=${index}): ${title}`
          );
        });

        results = await Promise.all(
          cssParams.map(params => browser.scripting.removeCSS(params))
        );
        // `removeCSS()` should not resolve to a value.
        results.forEach(result => {
          browser.test.assertEq(undefined, result, "got expected empty result");
        });

        results = await browser.scripting.executeScript({
          target: { tabId, allFrames: true },
          func: getBackgroundColor,
          args: [elementId],
        });

        browser.test.assertTrue(
          results.every(({ result }) => result === defaultColor),
          "got expected default color in all frames"
        );
      }

      browser.test.notifyPass("insert-and-remove-css");
    },
    files: {
      "file1.css": "#div-2 { background: rgb(3, 3, 3) }",
    },
  });

  let tab = await AppTestDelegate.openNewForegroundTab(
    window,
    "https://test1.example.com/tests/toolkit/components/extensions/test/mochitest/file_contains_iframe.html",
    true
  );

  await extension.startup();
  await extension.awaitFinish("insert-and-remove-css");
  await extension.unload();

  await AppTestDelegate.removeTab(window, tab);
});

</script>

</body>
</html>