script.evaluate command
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
Want more browser support for this feature? Tell us why.
The script.evaluate command of the script module evaluates a JavaScript expression in a realm and returns the value of the expression.
For expressions that evaluate to a promise, you can wait for the promise to settle and get the resolved value instead.
Syntax
/* With required parameters */
{
"method": "script.evaluate",
"params": {
"awaitPromise": false,
"expression": "document.title",
"target": {
"realm": "7c37f4c0-abcd-1234-ef56-789012345678"
}
}
}
/* With required and optional parameters */
{
"method": "script.evaluate",
"params": {
"awaitPromise": true,
"expression": "document.querySelector('button')",
"resultOwnership": "root",
"serializationOptions": {
"includeShadowTree": "open",
"maxDomDepth": 1,
"maxObjectDepth": 2
},
"target": {
"context": "93ee5bd6-d256-4608-a002-9a8995cc0e5f",
"sandbox": "myAutomationSandbox"
},
"userActivation": true
}
}
Parameters
The params field contains:
awaitPromise-
A boolean that indicates how a promise returned by an expression is handled.
true: If the expression evaluates to a promise, the browser waits for the promise to settle and returns the resolved value. If the promise is rejected, the rejection reason is reported as an exception.false: If the expression evaluates to a promise, the browser returns the promise object without waiting for the promise to settle.
expression-
A string that contains the JavaScript expression to evaluate.
resultOwnershipOptional-
A string that specifies whether the browser keeps a reference to the returned object so you can interact with it later. It can take one of the following values:
"none": The browser does not keep a reference to the returned object, so the response contains nohandlefield. This is the default."root": The browser keeps the returned object alive and includes ahandlefield in the response. You can pass thehandleto otherscriptmodule commands and release it when you no longer need it by usingscript.disown. The browser also releases handles when the realm is destroyed.
serializationOptionsOptional-
An object that controls the amount of detail to include in the response when the expression evaluates to an object. It can contain the following fields:
includeShadowTreeOptional-
A string that specifies whether descendants of shadow roots are included in the response when the returned value is a DOM node. It can take one of the following values:
"none": Descendants of shadow roots are not included. This is the default."all": Descendants of both open shadow roots (accessible from JavaScript outside the root) and closed shadow roots (not accessible from JavaScript outside the root) are included."open": Descendants of only open shadow roots are included.
maxDomDepthOptional-
A non-negative integer, or
nullfor unlimited, that specifies the number of levels of descendant nodes included in the response. The default is0, which excludes descendants. This limit also applies to descendants of shadow roots included byincludeShadowTree. maxObjectDepthOptional-
A non-negative integer, or
nullfor unlimited, that specifies the number of levels of nested objects included in the response. The default isnull.
target-
An object that specifies the realm in which to evaluate the expression. The object must contain either a
contextfield or arealmfield:context-
A string that contains the ID of the context whose active document provides the realm in which to evaluate the expression. Context IDs are returned by commands such as
browsingContext.getTree. realm-
A string that contains the ID of the realm in which to evaluate the expression. Realm IDs are returned by the
script.getRealmscommand. sandboxOptional-
A string that contains the name of the sandbox realm in which to evaluate the expression. For a non-empty name, the browser creates a sandbox realm with that name in the specified context if one doesn't already exist. For an empty name (
""), the expression is evaluated in the realm of the active document instead. This field is available only when thetargetobject contains acontextfield.
userActivationOptional-
A boolean that indicates whether the browser simulates user interaction by providing transient activation before evaluating the expression. This lets the expression use APIs that require transient activation, such as
Element.requestFullscreen().false: The browser does not simulate user interaction or reset existing transient activation. APIs that require transient activation may fail if the page does not already have transient activation. This is the default.true: The browser simulates user interaction before evaluating the expression. This does not guarantee the success of an API call; for example, the call can fail if a required permission has not been granted.
Return value
The following fields are available in the result object in the response, depending on the value of its type field:
exceptionDetailsOptional-
An object that describes the thrown exception and is present only when the
resultobject in the response contains"type": "exception". It contains the following fields:columnNumber-
A non-negative integer that contains the zero-based column number where the exception was thrown, or
0if the stack trace is empty. exception-
An object that represents the thrown JavaScript value in the response. The thrown value can be an
Errorobject or another JavaScript value. It can contain the following fields:handleOptional-
A string that contains an ID for referencing the thrown object in subsequent
scriptmodule commands. This handle can be used only in the realm in which it is created. The browser includes this field when theresultOwnershipparameter is specified as"root"and the thrown value supports a handle. This field is omitted when thetypefield in thisexceptionobject is"bigint","boolean","null","number","string", or"undefined". internalIdOptional-
A string that uniquely identifies an object within the response. This field is present only when the same object appears more than once in the response. This ID cannot be used to reference the object in subsequent commands.
-
A string that contains an ID for referencing the thrown DOM node in subsequent commands that accept a node reference, such as in the
startNodesparameter ofbrowsingContext.locateNodes. This field is present only when thetypefield in thisexceptionobject is"node". This ID can be used across realms that can access the same node. type-
A string that identifies the type of the thrown value, such as
"error","object", or"string". valueOptional-
An array, boolean, number, object, or string that represents the thrown value, depending on the
typefield in theexceptionobject. This field is omitted when that type is"error". See thevaluefield of the successfulresultfor details about how each type is represented. For thrown values, the browser uses the default values for the fields of theserializationOptionsparameter, regardless of the values specified in the command.
lineNumber-
A non-negative integer that contains the zero-based line number where the exception was thrown, or
0if the stack trace is empty. stackTrace-
An object that represents the JavaScript stack at the point where the exception was thrown. It contains the following field:
callFrames-
An array of zero or more stack-frame objects. Each object contains the following fields:
columnNumber-
A non-negative integer that contains the zero-based column number of the executed code.
functionName-
A string that contains the name of the executing function.
lineNumber-
A non-negative integer that contains the zero-based line number of the executed code.
url-
A string that contains the URL of the script.
text-
A string that contains a textual description of the exception. The exact format is browser-dependent, so don't rely on this value for assertions in tests.
realm-
A string that contains the ID of the realm in which the expression is evaluated.
resultOptional-
An object that represents the value of the evaluated expression and is present only when the
resultobject in the response contains"type": "success". It can contain the following fields:handleOptional-
A string that contains an ID for referencing the returned object in subsequent
scriptmodule commands. This handle can be used only in the realm in which it is created. The browser includes this field when theresultOwnershipparameter is specified as"root"and the returned value supports a handle. This field is omitted when thetypefield in thisresultobject is"bigint","boolean","null","number","string", or"undefined". internalIdOptional-
A string that uniquely identifies an object within the response. This field is present only when the same object appears more than once in the response. This ID cannot be used to reference the object in subsequent commands. This field is omitted when the
typefield in thisresultobject is"bigint","boolean","null","number","string", or"undefined". -
A string that contains an ID for referencing the returned node in subsequent commands that accept a node reference, such as in the
startNodesparameter ofbrowsingContext.locateNodes. This field is present only when thetypefield in thisresultobject is"node". This ID can be used across realms that can access the same node. type-
A string that identifies the type of value produced by evaluating the expression, such as
"array","function","map","node","number","object","set", or"string". valueOptional-
An array, boolean, number, object, or string that represents the evaluated value, depending on the
typefield in thisresultobject.For example,
"string"values are represented as strings,"boolean"values astrueorfalse, and"bigint"values as strings. For"array","set","nodelist", and"htmlcollection",valueis an array of objects representing the collection items.This field is not present for every type. For objects, this field can be omitted when the
maxObjectDepthlimit is reached or when the same object has already been represented in the response.- When
typeis"node",valueis an object that describes properties of the returned node and can contain the following fields:attributesOptional-
An object whose keys are attribute names and values are the corresponding attribute values as strings. This field is present only for element nodes.
childNodeCount-
A non-negative integer that specifies the number of direct child nodes of the returned node. This is the actual count, even if the
childrenfield is missing. childrenOptional-
An array of child node objects, each with fields such as
sharedId,type, andvalue. Descendants are included up to the level specified bymaxDomDepthin theserializationOptionsparameter. localNameOptional-
A string that contains the local name of the node. For an HTML element, this is the tag name in lowercase. This field is present only for element and attribute nodes.
modeOptional-
A string that specifies whether the shadow root is
"open"or"closed". This field is present only for shadow root nodes. namespaceURIOptional-
A string that contains the namespace URI of the node. This field is present only for element and attribute nodes. For HTML elements, the value is always the standard HTML namespace,
"http://www.w3.org/1999/xhtml". nodeType-
A non-negative integer that represents the type of node, such as
1for an element or3for a text node. nodeValueOptional-
A string that contains the value of the node, such as the text of a text node or the data of a comment node. This field is absent for nodes with a
nodeValueofnull, such as element, document, and shadow root nodes. shadowRootOptional-
An object that describes the shadow root attached to the node, with fields such as
sharedId,type, andvalue. This field isnullwhen the returned element has no shadow root.
- When
typeis"window",valueis an object with the following field:context-
A string that contains the browsing context ID.
- When
type-
A string that indicates how the expression evaluation completed. It has one of the following values:
"exception": The expression threw an exception, or the promise it evaluated to was rejected whenawaitPromisewastrue. TheexceptionDetailsfield describes the exception."success": The expression completed normally. Theresultfield describes the value of the expression.
Errors
invalid argument-
Thrown if a required parameter is missing or has an invalid type.
no such frame-
Thrown in any of the following cases:
- No context with the specified context ID is found.
- No realm with the specified realm ID is found.
Description
The script.evaluate command evaluates a JavaScript expression in the realm identified by the target parameter.
For example, you can evaluate document.title to read the page title or document.querySelector("#status").textContent = "Ready" to update an element in the page.
Controlling the returned detail
When evaluating an expression that produces an object, you can specify two limits in the serializationOptions parameter to control the depth of the data returned (as in browsingContext.locateNodes):
maxDomDepthcontrols the number of levels of DOM descendants included in thechildrenfield of each returned node.maxObjectDepthcontrols the number of levels of nested JavaScript object properties included when representing non-node values in the response.
Object identifiers in the response
The script.evaluate response can include handle, internalId, and sharedId identifiers in either the successful result object or the exception object.
They serve different purposes.
To see how these identifiers differ and where you can use them, consider a page with the following status message:
<p id="status">Loading…</p>
You can use script.evaluate to run the following expression to find the status element (<p id="status">) and return an array containing two references to it.
(() => {
const node = document.querySelector("#status");
return [node, node];
})();
In [node, node], both items refer to the same status element.
The successful result, therefore, includes two representations of the same node, one for each array item.
With the resultOwnership parameter set to "root", the returned array includes a handle.
Both node representations within the array share an internalId and a sharedId, but do not include handles.
The following table compares the identifiers returned in this example:
handle |
internalId |
sharedId |
|---|---|---|
The handle value identifies the array. |
The two internalId values are the same. |
The two sharedId values are the same. |
This handle can be used in the arguments parameter of script.callFunction to pass the array to a function that changes its first item's text to "Ready". |
The IDs can be compared to determine that both array items refer to the same node. | This ID can be used in the startNodes parameter of browsingContext.locateNodes to find descendants, such as the status element's text node. |
| This handle can be used only in the realm where it was created. | This ID cannot be used in subsequent commands. | This ID can be used across realms that can access the same node. |
Examples
>Evaluating an expression in a realm
Assume you have a WebDriver BiDi connection and an active session.
Suppose a tab is open at https://example.com and you want to read its page title programmatically.
You obtain the active document's realm ID by using script.getRealms.
Send the following message to evaluate the expression in that realm:
{
"id": 1,
"method": "script.evaluate",
"params": {
"awaitPromise": false,
"expression": "document.title",
"target": {
"realm": "93ee5bd6-d256-4608-a002-9a8995cc0e5f"
}
}
}
The browser responds as follows, where the response's outer result object has "type": "success" and contains a nested result object with the page title, "Example Domain":
{
"id": 1,
"type": "success",
"result": {
"realm": "93ee5bd6-d256-4608-a002-9a8995cc0e5f",
"result": {
"type": "string",
"value": "Example Domain"
},
"type": "success"
}
}
Evaluating an expression that throws
Suppose you try to read the text of an element with the class price on the same page, but no such element exists.
Using the same connection and session as in the previous example, obtain the tab's context ID by using browsingContext.getTree, and send the following message:
{
"id": 2,
"method": "script.evaluate",
"params": {
"awaitPromise": false,
"expression": "document.querySelector(\".price\").textContent",
"target": {
"context": "ceb33cd1-a9a3-46e7-a79d-3c1a3d4d754c"
}
}
}
The element lookup returns null, and reading its textContent property throws a TypeError.
The browser responds as follows, where the response's outer result object has "type": "exception" and contains an exceptionDetails object describing the exception.
The top-level "type": "success" indicates that the command succeeded, even though evaluating the expression threw an exception:
{
"id": 2,
"type": "success",
"result": {
"exceptionDetails": {
"columnNumber": 9,
"exception": {
"type": "error"
},
"lineNumber": 0,
"stackTrace": {
"callFrames": [
{
"columnNumber": 9,
"functionName": "",
"lineNumber": 0,
"url": "https://example.com/"
}
]
},
"text": "TypeError: can't access property \"textContent\", document.querySelector(...) is null"
},
"realm": "93ee5bd6-d256-4608-a002-9a8995cc0e5f",
"type": "exception"
}
}
Specifications
| Specification |
|---|
| WebDriver BiDi> # command-script-evaluate> |
Browser compatibility
See also
script.callFunctioncommandscript.disowncommandscript.addPreloadScriptcommand- Using promises guide