addInitScript
Overview
Run a function in new documents of the current tab or window before page scripts execute. Use this to prepare browser-side values before the application reads them. The function also runs in newly attached or navigated child frames within that top-level browsing context.
The script is registered for the tab or window that is current when addInitScript is called. It does not automatically apply to other tabs or windows, including those opened later. To use it there, switch to the target tab or window and register it separately before navigation.
Usage
browser.addInitScript(script, ...args)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
script | Function | Required | A function executed in the browser, without access to Node.js variables. |
args | unknown[] | [] | Arguments serialized as JSON and passed to the function. |
Result
Promise<InitScript>. Call script.on("data", listener) before navigation to receive values sent by the script's final emit argument. Subscribing with on is synchronous; script.remove() returns a promise.
Limitations
Requires WebDriver BiDi (webSocketUrl: true). Register the function before navigation. await script.remove() prevents injection into future documents; it does not undo changes in the current one.
In @testplane/webdriverio 9.6.2, pass a function, not a string. Use ordinary quotes in its source: template literals can break the injected script. Characters outside Latin-1 (such as Cyrillic) in the function source or serialized arguments can prevent registration.
Example
On the example site, /navigation runs window.initialSeed = window.navigationSeed ?? null as it loads. The test checks what the page script saw, both with and without the init script.
const assert = require("node:assert/strict");
it("addInitScript: set a value before page scripts", async ({ browser }) => {
const script = await browser.addInitScript(value => {
window.navigationSeed = value;
}, 42);
try {
await browser.url("/navigation");
assert.equal(await browser.execute(() => window.initialSeed), 42);
} finally {
await script.remove();
}
await browser.url("/navigation");
assert.equal(await browser.execute(() => window.initialSeed), null);
});