script.callFunction 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.callFunction command of the script module calls the specified function with the given arguments in a realm and returns the function's result.
Syntax
/* With required parameters */
{
"method": "script.callFunction",
"params": {
"awaitPromise": false,
"functionDeclaration": "() => document.title",
"target": {
"context": "93ee5bd6-d256-4608-a002-9a8995cc0e5f"
}
}
}
/* With required and optional parameters */
{
"method": "script.callFunction",
"params": {
"arguments": [
{
"type": "number",
"value": 3
}
],
"awaitPromise": false,
"functionDeclaration": "function (quantity) { return this.price * quantity; }",
"resultOwnership": "root",
"serializationOptions": {
"includeShadowTree": "open",
"maxDomDepth": 1,
"maxObjectDepth": 2
},
"target": {
"context": "93ee5bd6-d256-4608-a002-9a8995cc0e5f",
"sandbox": "myAutomationSandbox"
},
"this": {
"type": "object",
"value": [
[
"price",
{
"type": "number",
"value": 5
}
]
]
},
"userActivation": true
}
}
Parameters
The params field contains:
argumentsOptional-
An array of objects that represents the values to pass to the function as arguments, in the order they appear in the array. The browser converts each object into a JavaScript value before calling the function. If omitted, the function is called without arguments.
To describe a primitive or structured JavaScript value or configure a channel for sending messages to the client, the object uses a combination of
typeand the optionalvaluefields. Thevaluefield's format depends on thetypefield. To refer to an existing JavaScript object or a DOM node, the object uses thehandleorsharedIdfield instead.type-
A string that specifies the type of value to pass to the function. It can take one of the following values:
- For a primitive JavaScript value: One of
"bigint","boolean","null","number","string", or"undefined". - For a structured JavaScript value: One of
"array","date","map","object","regexp", or"set". - For a browser-created function that sends messages to the client:
"channel". The browser passes this function as an argument to the called function. Each call to the browser-created function sends ascript.messageevent to a subscribed client. The browser-created function accepts a single argument. To send several values in one message, pass an object or an array.
- For a primitive JavaScript value: One of
valueOptional-
An array, boolean, number, object, or string, depending on
type, that specifies the value to pass. This field is not available whentypeis"null"or"undefined". It is required for all othertypevalues.-
When
typeis"array",valueis an array of objects. Each object describes an array item using the same fields as an object in theargumentsparameter:typeand the optionalvalue, orhandleorsharedId. -
When
typeis"bigint",valueis a string that represents the integer. -
When
typeis"boolean",valueistrueorfalse. -
When
typeis"channel",valueis an object that configures the channel. This is the same channel configuration used in theargumentsparameter ofscript.addPreloadScript. It contains the following fields:channel-
A string that identifies the channel in the resulting
script.messageevents. ownershipOptional-
A string that specifies whether the browser keeps a reference to the object sent in each message. It takes the same values and has the same default as the
resultOwnershipparameter. serializationOptionsOptional-
An object that controls the amount of detail to include in each message. It has the same fields and defaults as the
serializationOptionsparameter.
-
When
typeis"date",valueis a string in the date time string format. -
When
typeis"map",valueis an array that describes the entries of a JavaScriptMap. Each item in the array is another array containing exactly two items: a key followed by its value. The key is a string or an object that represents a JavaScript value. The value is an object that represents a JavaScript value.Objects used as keys or values use the same fields as an object in the
argumentsparameter:typeand the optionalvalue, orhandleorsharedId. -
When
typeis"number",valueis a number or the string"-0","-Infinity","Infinity", or"NaN". -
When
typeis"object",valueis an array that describes the properties of a JavaScript object. Each item in the array is another array containing exactly two items: a key followed by its value. The key is a string or an object that represents a JavaScript value. The value is an object that represents a JavaScript value.Objects used as keys or values use the same fields as an object in the
argumentsparameter:typeand the optionalvalue, orhandleorsharedId. -
When
typeis"regexp",valueis an object with the following fields:flagsOptional-
A string that specifies the regular expression flags.
pattern-
A string that contains the regular expression pattern.
-
When
typeis"set",valueis an array of objects. Each object describes a set item using the same fields as an object in theargumentsparameter:typeand the optionalvalue, orhandleorsharedId. -
When
typeis"string",valueis a string.
-
handle-
A string that contains an ID for referencing an existing JavaScript object to pass to the function. Use this field instead of the
argumentsparameter'stypeandvaluefields. If bothhandleandsharedIdare specified,handleis ignored. A handle can be used only in the realm in which it is created.Handles for objects are returned by commands such as
script.evaluateor a previousscript.callFunctioncommand whenresultOwnershipis set to"root". -
A string that contains an ID for referencing an existing DOM node to pass to the function. Use this field instead of the
argumentsparameter'stypeandvaluefields. This ID can be used across realms, including sandbox realms, that can access the same node.Shared IDs are returned by commands such as
browsingContext.locateNodes.
awaitPromise-
A boolean that indicates how a promise returned by a function is handled.
true: If the function returns 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 function returns a promise, the browser returns the promise object without waiting for the promise to settle.
functionDeclaration-
A string that contains the JavaScript source code for the function to call. The browser evaluates the string and calls the resulting function with the values specified in the
argumentsparameter. 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 function returns 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 call the function. 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 call the function. Context IDs are returned by commands such as
browsingContext.getTree. realm-
A string that contains the ID of the realm in which to call the function. Realm IDs are returned by the
script.getRealmscommand. sandboxOptional-
A string that contains the name of the sandbox realm in which to call the function. 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 function is called in the realm of the active document instead. This field is available only when thetargetobject contains acontextfield.
thisOptional-
An object that describes the value to use as
thiswhen calling the function. It uses the same fields as an object in theargumentsparameter. If omitted, the browser usesnullforthis. For a non-strict function, JavaScript replacesnullwith the realm's global object. For an arrow function, this field does not affect the value ofthisinside the function. userActivationOptional-
A boolean that indicates whether the browser simulates user interaction by providing transient activation before calling the function. This lets the function 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 calling the function. 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 function is called.
resultOptional-
An object that represents the return value of the function 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 returned by the function, such as
"array","function","map","node","number","object","set", or"string". valueOptional-
An array, boolean, number, object, or string that represents the returned value, depending on the
typefield in thisresultobject.For example,
"bigint"values are represented as strings,"boolean"values astrueorfalse, and"string"values as strings. For"array","htmlcollection","nodelist", and"set",valueis an array of objects representing the collection items. For"object",valueis an array of key-value pairs.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 ID of the context associated with the window.
- When
type-
A string that indicates how the function call completed. It has one of the following values:
"exception": EvaluatingfunctionDeclarationor calling the function threw an exception, or the promise returned by the function was rejected whenawaitPromisewastrue. TheexceptionDetailsfield describes the exception."success": The function returned normally. Theresultfield describes the return value of the function.
Errors
invalid argument-
Thrown in any of the following cases:
- A required parameter is missing, or a parameter has an invalid type.
- The
functionDeclarationparameter evaluates to a value that isn't a function. - An object in the
argumentsorthisparameter, including a nested object, has an unrecognizedtypeor an invalidvaluefor that type. For example, whentypeis"map"or"object", an item in itsvaluearray doesn't contain exactly two items.
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.
no such handle-
Thrown if a
handlevalue in theargumentsorthisparameter is not found in the target realm. no such node-
Thrown when a
sharedIdis specified in theargumentsorthisparameter and any of the following applies:- No node with the specified
sharedIdis found. - The realm specified by
targetis not associated with a document. - The node's document and the target realm do not satisfy the same-origin-domain check.
- No node with the specified
Description
The script.callFunction command accepts a function declaration and arguments to pass to the function.
Passing arguments separately from the function's source code lets you supply values, including references to existing JavaScript objects or DOM nodes, without inserting them into the source string.
Using the serializationOptions parameter, you can limit the depth of DOM descendants and nested JavaScript objects included in the response.
See Controlling the returned detail on the script.evaluate page for how these limits work.
The response can also include handle, internalId, and sharedId identifiers.
To understand how they differ and where you can use them, see Object identifiers in the response on the script.evaluate page.
When inspecting the response, check the type field inside result to distinguish a successful function call from an exception.
JavaScript exceptions are reported in the command's result, rather than as protocol errors.
Examples
>Calling a function with node and text arguments
Assume you have a WebDriver BiDi connection and an active session.
Suppose the page in a tab contains the heading "Welcome" and you want to change its text to "Welcome back".
You use browsingContext.getTree to obtain the tab's context ID and browsingContext.locateNodes to find the heading and obtain its sharedId.
To make the change, you'll define a function that accepts an element and a string as arguments.
The function will assign the string to the element's textContent property and return the updated text.
Send the following message to call the function with the heading element and "Welcome back" as its arguments:
{
"id": 1,
"method": "script.callFunction",
"params": {
"arguments": [
{
"sharedId": "a1b2c3d4-e5f6-4708-9a1b-2c3d4e5f6071"
},
{
"type": "string",
"value": "Welcome back"
}
],
"awaitPromise": false,
"functionDeclaration": "(element, text) => { element.textContent = text; return element.textContent; }",
"target": {
"context": "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 updated text "Welcome back":
{
"id": 1,
"type": "success",
"result": {
"realm": "7c37f4c0-abcd-1234-ef56-789012345678",
"result": {
"type": "string",
"value": "Welcome back"
},
"type": "success"
}
}
Calling a function with an object as this
Suppose you want to increase the value stored in an object's count property.
In an earlier script.evaluate command, you evaluated the expression ({ count: 2 }) with resultOwnership set to "root".
You used the context ID of the tab from the previous example to evaluate the expression in the page's default realm.
The browser kept the resulting object alive and returned its handle.
To increase count by three, you'll define a function that accepts an increment parameter, adds it to this.count, and returns the updated value.
Using the same connection and session as in the previous example and without navigating or reloading the page after the earlier script.evaluate command, send the following message to call the function.
In target, use the context ID from the earlier script.evaluate command.
Set this to a reference containing the object's handle and arguments to an array containing a description of the number 3:
{
"id": 2,
"method": "script.callFunction",
"params": {
"arguments": [
{
"type": "number",
"value": 3
}
],
"awaitPromise": false,
"functionDeclaration": "function (increment) { this.count += increment; return this.count; }",
"target": {
"context": "93ee5bd6-d256-4608-a002-9a8995cc0e5f"
},
"this": {
"handle": "f1e2d3c4-b5a6-4978-8b9c-0d1e2f3a4b5c"
}
}
}
The browser responds as follows, where the nested result object contains the updated count 5:
{
"id": 2,
"type": "success",
"result": {
"realm": "7c37f4c0-abcd-1234-ef56-789012345678",
"result": {
"type": "number",
"value": 5
},
"type": "success"
}
}
Specifications
| Specification |
|---|
| WebDriver BiDi> # command-script-callFunction> |
Browser compatibility
See also
script.evaluatecommandscript.disowncommandscript.addPreloadScriptcommandbrowsingContext.locateNodescommandscript.messageevent