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.
- : A boolean that indicates how a promise returned by an expression is handled.
expression- : A string that contains the JavaScript expression to evaluate.
resultOwnership- : 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 if the returned value supports a handle. 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.
- : 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:
serializationOptions- : 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:
includeShadowTree- : 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.
- : 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:
maxDomDepth- : 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 viaincludeShadowTree.
- : A non-negative integer, or
maxObjectDepth- : A non-negative integer, or
nullfor unlimited, that specifies the number of levels of nested objects included in the response. The default isnull.
- : A non-negative integer, or
- : 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:
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.
- : 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
realm- : A string that contains the ID of the realm in which to evaluate the expression.
Realm IDs are returned by the
script.getRealmscommand.
- : A string that contains the ID of the realm in which to evaluate the expression.
Realm IDs are returned by the
sandbox- : 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.
- : 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 (
- : An object that specifies the realm in which to evaluate the expression.
The object must contain either a
userActivation- : 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.
- : 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().
Return value
The following fields are available in the result object in the response, depending on the value of its type field:
exceptionDetails- : 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.
- : A non-negative integer that contains the zero-based column number where the exception was thrown, or
exception- : An object that represents the thrown JavaScript value in the response.
The thrown value can be an Error object or another JavaScript value.
It can contain the following fields:
handle- : 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".
- : A string that contains an ID for referencing the thrown object in subsequent
internalId- : 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.
sharedId- : 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.
- : A string that contains an ID for referencing the thrown DOM node in subsequent commands that accept a node reference, such as in the
type- : A string that identifies the type of the thrown value, such as
"error","object", or"string".
- : A string that identifies the type of the thrown value, such as
value- : 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.
- : An array, boolean, number, object, or string that represents the thrown value, depending on the
- : An object that represents the thrown JavaScript value in the response.
The thrown value can be an Error object or another JavaScript value.
It can contain the following fields:
lineNumber- : A non-negative integer that contains the zero-based line number where the exception was thrown, or
0if the stack trace is empty.
- : A non-negative integer that contains the zero-based line number where the exception was thrown, or
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.
- : An array of zero or more stack-frame objects.
Each object contains the following fields:
- : An object that represents the JavaScript stack at the point where the exception was thrown.
It contains the following field:
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.
- : An object that describes the thrown exception and is present only when the
realm- : A string that contains the ID of the realm in which the expression is evaluated.
result- : 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:handle-
: 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 the
resultOwnershipparameter is specified asrootand the result is of atypethat supports a handle.- Types that support handles: Objects (including arrays and DOM nodes) and symbols.
- Types that don't support handles:
bigint,boolean,null,number,string, andundefined. The browser omits this field for these types.
-
internalId- : 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 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
sharedId- : 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.
- : A string that contains an ID for referencing the returned node in subsequent commands that accept a node reference, such as in the
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".
- : A string that identifies the type of value produced by evaluating the expression, such as
value-
: 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:attributes- : 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.
- : A non-negative integer that specifies the number of direct child nodes of the returned node.
This is the actual count, even if the
children- : An array of child node objects, each with fields such as
sharedId,type, andvalue. Descendants are included up to the level specified bymaxDomDepthin theserializationOptionsparameter.
- : An array of child node objects, each with fields such as
localName- : 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.
mode- : A string that specifies whether the shadow root is
"open"or"closed". This field is present only for shadow root nodes.
- : A string that specifies whether the shadow root is
namespaceURI- : 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".
- : 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,
nodeType- : A non-negative integer that represents the type of node, such as
1for an element or3for a text node.
- : A non-negative integer that represents the type of node, such as
nodeValue- : 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.
- : 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
shadowRoot- : 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.
- : An object that describes the shadow root attached to the node, with fields such as
- When
typeis"window",valueis an object with the following field:context- : A string that contains the browsing context ID.
- When
-
- : An object that represents the value of the evaluated expression and is present only when the
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.
- : A string that indicates how the expression evaluation completed.
It has one of the following values:
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.
- : Thrown in any of the following cases:
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.
Arrays support handles, so the browser can retain a reference to the returned array.
With the resultOwnership parameter set to root, the array's representation in the response includes a handle field.
This handle identifies the array itself, not the nodes it contains.
Both node representations within the array share an internalId and a sharedId.
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
Browser compatibility
See also
script.callFunctioncommandscript.disowncommandscript.addPreloadScriptcommand- Using promises guide
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
