summaryrefslogtreecommitdiffstats
path: root/browser/components/extensions/test/browser/browser_ext_devtools_inspectedWindow_reload.js
blob: d09dc6e3e3f0516e8a3a55db7d0bbf6815749d87 (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
/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set sts=2 sw=2 et tw=80: */
"use strict";

// Like most of the mochitest-browser devtools test,
// on debug test machine, it takes about 50s to run the test.
requestLongerTimeout(4);

loadTestSubscript("head_devtools.js");

// Allow rejections related to closing the devtools toolbox too soon after the test
// has already verified the details that were relevant for that test case
// (e.g. this was triggering an intermittent failure in shippable optimized
// builds, tracked Bug 1707644).
PromiseTestUtils.allowMatchingRejectionsGlobally(
  /Connection closed, pending request to/
);

const TEST_ORIGIN = "http://mochi.test:8888";
const TEST_BASE = getRootDirectory(gTestPath).replace(
  "chrome://mochitests/content",
  ""
);
const TEST_PATH = `${TEST_BASE}file_inspectedwindow_reload_target.sjs`;

// Small helper which provides the common steps to the following reload test cases.
async function runReloadTestCase({
  urlParams,
  background,
  devtoolsPage,
  testCase,
  closeToolbox = true,
}) {
  const TEST_TARGET_URL = `${TEST_ORIGIN}/${TEST_PATH}?${urlParams}`;
  let tab = await BrowserTestUtils.openNewForegroundTab(
    gBrowser,
    TEST_TARGET_URL
  );

  let extension = ExtensionTestUtils.loadExtension({
    background,
    manifest: {
      devtools_page: "devtools_page.html",
      permissions: ["webNavigation", "<all_urls>"],
    },
    files: {
      "devtools_page.html": `<!DOCTYPE html>
      <html>
       <head>
         <meta charset="utf-8">
         <script type="text/javascript" src="devtools_page.js"></script>
       </head>
       <body>
       </body>
      </html>`,
      "devtools_page.js": devtoolsPage,
    },
  });

  await extension.startup();

  const toolbox = await openToolboxForTab(tab);

  // Wait the test extension to be ready.
  await extension.awaitMessage("devtools_inspected_window_reload.ready");

  info("devtools page ready");

  // Run the test case.
  await testCase(extension, tab, toolbox);

  if (closeToolbox) {
    await closeToolboxForTab(tab);
  }

  BrowserTestUtils.removeTab(tab);

  await extension.unload();
}

add_task(async function test_devtools_inspectedWindow_reload_ignore_cache() {
  function background() {
    // Wait until the devtools page is ready to run the test.
    browser.runtime.onMessage.addListener(async msg => {
      if (msg !== "devtools_page.ready") {
        browser.test.fail(`Unexpected message received: ${msg}`);
        return;
      }

      const tabs = await browser.tabs.query({ active: true });
      const activeTabId = tabs[0].id;
      let reloads = 0;

      browser.webNavigation.onCompleted.addListener(async details => {
        if (details.tabId == activeTabId && details.frameId == 0) {
          reloads++;

          // This test expects two `devtools.inspectedWindow.reload` calls:
          // the first one without any options and the second one with
          // `ignoreCache=true`.
          let expectedContent;
          let enabled;

          switch (reloads) {
            case 1:
              enabled = false;
              expectedContent = "empty cache headers";
              break;
            case 2:
              enabled = true;
              expectedContent = "no-cache:no-cache";
              break;
          }

          if (!expectedContent) {
            browser.test.fail(`Unexpected number of tab reloads: ${reloads}`);
          } else {
            try {
              const code = `document.body.textContent`;
              const [text] = await browser.tabs.executeScript(activeTabId, {
                code,
              });

              browser.test.assertEq(
                text,
                expectedContent,
                `Got the expected cache headers with ignoreCache=${enabled}`
              );
            } catch (err) {
              browser.test.fail(`Error: ${err.message} - ${err.stack}`);
            }
          }

          browser.test.sendMessage(
            "devtools_inspectedWindow_reload_checkIgnoreCache.done"
          );
        }
      });

      browser.test.sendMessage("devtools_inspected_window_reload.ready");
    });
  }

  async function devtoolsPage() {
    browser.test.onMessage.addListener(msg => {
      switch (msg) {
        case "no-ignore-cache":
          browser.devtools.inspectedWindow.reload();
          break;
        case "ignore-cache":
          browser.devtools.inspectedWindow.reload({ ignoreCache: true });
          break;
        default:
          browser.test.fail(`Unexpected test message received: ${msg}`);
      }
    });

    browser.runtime.sendMessage("devtools_page.ready");
  }

  await runReloadTestCase({
    urlParams: "test=cache",
    background,
    devtoolsPage,
    testCase: async function (extension) {
      for (const testMessage of ["no-ignore-cache", "ignore-cache"]) {
        extension.sendMessage(testMessage);
        await extension.awaitMessage(
          "devtools_inspectedWindow_reload_checkIgnoreCache.done"
        );
      }
    },
  });
});

add_task(
  async function test_devtools_inspectedWindow_reload_custom_user_agent() {
    const CUSTOM_USER_AGENT = "CustomizedUserAgent";

    function background() {
      browser.runtime.onMessage.addListener(async msg => {
        if (msg !== "devtools_page.ready") {
          browser.test.fail(`Unexpected message received: ${msg}`);
          return;
        }

        browser.test.sendMessage("devtools_inspected_window_reload.ready");
      });
    }

    function devtoolsPage() {
      browser.test.onMessage.addListener(async msg => {
        switch (msg) {
          case "no-custom-user-agent":
            await browser.devtools.inspectedWindow.reload({});
            break;
          case "custom-user-agent":
            await browser.devtools.inspectedWindow.reload({
              userAgent: "CustomizedUserAgent",
            });
            break;
          default:
            browser.test.fail(`Unexpected test message received: ${msg}`);
        }
      });

      browser.runtime.sendMessage("devtools_page.ready");
    }

    async function checkUserAgent(expectedUA) {
      const contexts =
        gBrowser.selectedBrowser.browsingContext.getAllBrowsingContextsInSubtree();

      const uniqueRemoteTypes = new Set();
      for (const context of contexts) {
        uniqueRemoteTypes.add(context.currentRemoteType);
      }

      info(
        `Got ${contexts.length} with remoteTypes: ${Array.from(
          uniqueRemoteTypes
        )}`
      );
      ok(contexts.length >= 2, "There should be at least 2 browsing contexts");

      if (Services.appinfo.fissionAutostart) {
        ok(
          uniqueRemoteTypes.size >= 2,
          "Expect at least one cross origin sub frame"
        );
      }

      for (const context of contexts) {
        const url = context.currentURI?.spec?.replace(
          context.currentURI?.query,
          "…"
        );
        info(
          `Checking user agent on ${url} (remoteType: ${context.currentRemoteType})`
        );
        await SpecialPowers.spawn(context, [expectedUA], async _expectedUA => {
          is(
            content.navigator.userAgent,
            _expectedUA,
            `expected navigator.userAgent value`
          );
          is(
            content.wrappedJSObject.initialUserAgent,
            _expectedUA,
            `expected navigator.userAgent value at startup`
          );
          if (content.wrappedJSObject.userAgentHeader) {
            is(
              content.wrappedJSObject.userAgentHeader,
              _expectedUA,
              `user agent header has expected value`
            );
          }
        });
      }
    }

    await runReloadTestCase({
      urlParams: "test=user-agent",
      background,
      devtoolsPage,
      closeToolbox: false,
      testCase: async function (extension, tab, toolbox) {
        info("Get the initial user agent");
        const initialUserAgent = await SpecialPowers.spawn(
          gBrowser.selectedBrowser,
          [],
          () => {
            return content.navigator.userAgent;
          }
        );

        info(
          "Check that calling inspectedWindow.reload without userAgent does not change the user agent of the page"
        );
        let onPageLoaded = BrowserTestUtils.browserLoaded(
          gBrowser.selectedBrowser,
          true
        );
        extension.sendMessage("no-custom-user-agent");
        await onPageLoaded;

        await checkUserAgent(initialUserAgent);

        info(
          "Check that calling inspectedWindow.reload with userAgent does change the user agent of the page"
        );
        onPageLoaded = BrowserTestUtils.browserLoaded(
          gBrowser.selectedBrowser,
          true
        );
        extension.sendMessage("custom-user-agent");
        await onPageLoaded;

        await checkUserAgent(CUSTOM_USER_AGENT);

        info("Check that the user agent persists after a reload");
        await BrowserTestUtils.reloadTab(tab, /* includeSubFrames */ true);
        await checkUserAgent(CUSTOM_USER_AGENT);

        info(
          "Check that the user agent persists after navigating to a new browsing context"
        );
        const previousBrowsingContextId =
          gBrowser.selectedBrowser.browsingContext.id;

        // Navigate to a different origin
        await navigateToWithDevToolsOpen(
          tab,
          `https://example.com/${TEST_PATH}?test=user-agent&crossOriginIsolated=true`
        );

        isnot(
          gBrowser.selectedBrowser.browsingContext.id,
          previousBrowsingContextId,
          "A new browsing context was created"
        );

        await checkUserAgent(CUSTOM_USER_AGENT);

        info(
          "Check that closing DevTools resets the user agent of the page to its initial value"
        );

        await closeToolboxForTab(tab);

        // XXX: This is needed at the moment since Navigator.cpp retrieves the UserAgent from the
        // headers (when there's no custom user agent). And here, since we reloaded the page once
        // we set the custom user agent, the header was set accordingly and still holds the custom
        // user agent value. This should be fixed by Bug 1705326.
        is(
          gBrowser.selectedBrowser.browsingContext.customUserAgent,
          "",
          "The flag on the browsing context was reset"
        );
        await checkUserAgent(CUSTOM_USER_AGENT);
        await BrowserTestUtils.reloadTab(tab, /* includeSubFrames */ true);
        await checkUserAgent(initialUserAgent);
      },
    });
  }
);

add_task(async function test_devtools_inspectedWindow_reload_injected_script() {
  function background() {
    function getIframesTextContent() {
      let docs = [];
      for (
        let iframe, doc = document;
        doc;
        doc = iframe && iframe.contentDocument
      ) {
        docs.push(doc);
        iframe = doc.querySelector("iframe");
      }

      return docs.map(doc => doc.querySelector("pre").textContent);
    }

    browser.runtime.onMessage.addListener(async msg => {
      if (msg !== "devtools_page.ready") {
        browser.test.fail(`Unexpected message received: ${msg}`);
        return;
      }

      const tabs = await browser.tabs.query({ active: true });
      const activeTabId = tabs[0].id;
      let reloads = 0;

      browser.webNavigation.onCompleted.addListener(async details => {
        if (details.tabId == activeTabId && details.frameId == 0) {
          reloads++;

          let expectedContent;
          let enabled;

          switch (reloads) {
            case 1:
              enabled = false;
              expectedContent = "injected script NOT executed";
              break;
            case 2:
              enabled = true;
              expectedContent = "injected script executed first";
              break;
            default:
              browser.test.fail(`Unexpected number of tab reloads: ${reloads}`);
          }

          if (!expectedContent) {
            browser.test.fail(`Unexpected number of tab reloads: ${reloads}`);
          } else {
            let expectedResults = new Array(4).fill(expectedContent);
            let code = `(${getIframesTextContent})()`;

            try {
              let [results] = await browser.tabs.executeScript(activeTabId, {
                code,
              });

              browser.test.assertEq(
                JSON.stringify(expectedResults),
                JSON.stringify(results),
                `Got the expected result with injectScript=${enabled}`
              );
            } catch (err) {
              browser.test.fail(`Error: ${err.message} - ${err.stack}`);
            }
          }

          browser.test.sendMessage(
            `devtools_inspectedWindow_reload_injectedScript.done`
          );
        }
      });

      browser.test.sendMessage("devtools_inspected_window_reload.ready");
    });
  }

  function devtoolsPage() {
    function injectedScript() {
      if (!window.pageScriptExecutedFirst) {
        window.addEventListener(
          "DOMContentLoaded",
          function listener() {
            document.querySelector("pre").textContent =
              "injected script executed first";
          },
          { once: true }
        );
      }
    }

    browser.test.onMessage.addListener(msg => {
      switch (msg) {
        case "no-injected-script":
          browser.devtools.inspectedWindow.reload({});
          break;
        case "injected-script":
          browser.devtools.inspectedWindow.reload({
            injectedScript: `new ${injectedScript}`,
          });
          break;
        default:
          browser.test.fail(`Unexpected test message received: ${msg}`);
      }
    });

    browser.runtime.sendMessage("devtools_page.ready");
  }

  await runReloadTestCase({
    urlParams: "test=injected-script&frames=3",
    background,
    devtoolsPage,
    testCase: async function (extension) {
      extension.sendMessage("no-injected-script");

      await extension.awaitMessage(
        "devtools_inspectedWindow_reload_injectedScript.done"
      );

      extension.sendMessage("injected-script");

      await extension.awaitMessage(
        "devtools_inspectedWindow_reload_injectedScript.done"
      );
    },
  });
});