Skip to main content

execute

Overview

Use execute to synchronously execute the specified JavaScript code in the context of the currently selected frame.

The command returns the result of the script execution to the client.

The script argument defines the script to be executed as the body of a function. The value returned by this function will be returned to the client. The function will be invoked with the provided array of args, and access to the values can be obtained through the arguments object in the specified order.

Arguments can be any JSON primitives, arrays, or JSON objects. JSON objects that define a reference to a WebElement will be converted to the corresponding DOM element. Similarly, any WebElements in the script result will be returned to the client as WebElement JSON objects.

Usage

await browser.execute(script, arguments);

Command Parameters

NameTypeDescription
scriptString or FunctionThe script to be executed.
argumentsAnyOptional parameter. Arguments for the script.

Usage Examples

it("should inject javascript on the page", async ({ browser }) => {
const result = await browser.execute(
(a, b, c, d) => {
// here we are in the browser context: no access to console or client
return a + b + c + d;
},
1,
2,
3,
4,
);

// here we are in the node.js context: access to console and client is available
console.log(result); // outputs: 10
});

References

We'd like to give credit to the original WebdriverIO docs article, from which we drew some information while writing our version.