summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/test/xpcshell/test_ext_contentscript_dynamic_registration.js
blob: 20f6ece95a0162512fb724f5dce387a91f12a970 (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
"use strict";

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

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

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

// Do not use preallocated processes.
Services.prefs.setBoolPref("dom.ipc.processPrelaunch.enabled", false);
// This is needed for Android.
Services.prefs.setIntPref("dom.ipc.keepProcessesAlive.web", 0);

const makeExtension = ({ background, manifest }) => {
  return ExtensionTestUtils.loadExtension({
    manifest: {
      ...manifest,
      permissions:
        manifest.manifest_version === 3 ? ["scripting"] : ["http://*/*/*.html"],
    },
    temporarilyInstalled: true,
    background,
    files: {
      "script.js": () => {
        browser.test.sendMessage(
          `script-ran: ${location.pathname.split("/").pop()}`
        );
      },
      "inject_browser.js": () => {
        browser.userScripts.onBeforeScript.addListener(script => {
          // Inject `browser.test.sendMessage()` so that it can be used in the
          // `script.js` defined above when using "user scripts".
          script.defineGlobals({
            browser: {
              test: {
                sendMessage(msg) {
                  browser.test.sendMessage(msg);
                },
              },
            },
          });
        });
      },
    },
  });
};

const verifyRegistrationWithNewProcess = async extension => {
  // We override the `broadcast()` method to reliably verify Bug 1756495: when
  // a new process is spawned while we register a content script, the script
  // should be correctly registered and executed in this new process. Below,
  // when we receive the `Extension:RegisterContentScripts`, we open a new tab
  // (which is the "new process") and then we invoke the original "broadcast
  // logic". The expected result is that the content script registered by the
  // extension will run.
  const originalBroadcast = Extension.prototype.broadcast;

  let broadcastCalledCount = 0;
  let secondContentPage;

  extension.extension.broadcast = async function broadcast(msg, data) {
    if (msg !== "Extension:RegisterContentScripts") {
      return originalBroadcast.call(this, msg, data);
    }

    broadcastCalledCount++;
    Assert.equal(
      1,
      broadcastCalledCount,
      "broadcast override should be called once"
    );

    await originalBroadcast.call(this, msg, data);

    Assert.equal(extension.id, data.id, "got expected extension ID");
    Assert.equal(1, data.scripts.length, "expected 1 script to register");
    Assert.ok(
      data.scripts[0].options.jsPaths[0].endsWith("script.js"),
      "got expected js file"
    );

    const newPids = [];
    const topic = "ipc:content-created";

    let obs = (subject, topic, data) => {
      newPids.push(parseInt(data, 10));
    };
    Services.obs.addObserver(obs, topic);

    secondContentPage = await ExtensionTestUtils.loadContentPage(
      `${BASE_URL}/dummy_page.html`
    );

    const { childID } =
      secondContentPage.browsingContext.currentWindowGlobal.domProcess;

    Services.obs.removeObserver(obs, topic);

    // We expect to have a new process created for `secondContentPage`.
    Assert.ok(
      newPids.includes(childID),
      `expected PID ${childID} to be in [${newPids.join(", ")}])`
    );
  };

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

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

  await Promise.all([
    extension.awaitMessage("script-ran: file_sample.html"),
    extension.awaitMessage("script-ran: dummy_page.html"),
  ]);

  // Unload extension first to avoid an issue on Windows platforms.
  await extension.unload();
  await contentPage.close();
  await secondContentPage.close();
};

add_task(
  {
    pref_set: [["extensions.manifestV3.enabled", true]],
  },
  async function test_scripting_registerContentScripts() {
    let extension = makeExtension({
      manifest: {
        manifest_version: 3,
        host_permissions: ["<all_urls>"],
        granted_host_permissions: true,
      },
      async background() {
        const script = {
          id: "a-script",
          js: ["script.js"],
          matches: ["http://*/*/*.html"],
          persistAcrossSessions: false,
        };

        await browser.scripting.registerContentScripts([script]);

        browser.test.sendMessage("background-done");
      },
    });

    await verifyRegistrationWithNewProcess(extension);
  }
);

add_task(
  {
    // We don't have WebIDL bindings for `browser.contentScripts`.
    skip_if: () => ExtensionTestUtils.isInBackgroundServiceWorkerTests(),
  },
  async function test_contentScripts_register() {
    let extension = makeExtension({
      manifest: {
        manifest_version: 2,
      },
      async background() {
        await browser.contentScripts.register({
          js: [{ file: "script.js" }],
          matches: ["http://*/*/*.html"],
        });

        browser.test.sendMessage("background-done");
      },
    });

    await verifyRegistrationWithNewProcess(extension);
  }
);

add_task(
  {
    // We don't have WebIDL bindings for `browser.userScripts`.
    skip_if: () => ExtensionTestUtils.isInBackgroundServiceWorkerTests(),
  },
  async function test_userScripts_register() {
    let extension = makeExtension({
      manifest: {
        manifest_version: 2,
        user_scripts: {
          api_script: "inject_browser.js",
        },
      },
      async background() {
        await browser.userScripts.register({
          js: [{ file: "script.js" }],
          matches: ["http://*/*/*.html"],
        });

        browser.test.sendMessage("background-done");
      },
    });

    await verifyRegistrationWithNewProcess(extension);
  }
);