Appearance
UI.execute()
Executes JavaScript in the browser’s context.
The script is executed inside the browser — not in the test runner. This means it can access variables available on the page, such as window, document, and libraries loaded by the page (for example, jQuery).
The script does not have access to variables in the test runner’s context. To pass values from the test to the browser, you must provide them as arguments.
Usage
typescript
UI.execute(script: string, args?: any[])
UI.execute(script: function, args?: any[])Parameters
| Parameter | Type | Description |
|---|---|---|
script | string | function | JavaScript code to execute in the browser. |
args | any[] | Optional. Values to pass to the script. |
Returns
Returns the value produced by the executed script.
If the script does not explicitly return a value, undefined is returned.
Examples
Executing JavaScript as string
js
UI.execute(`document.location.reload()`)In the example above, the test executes document.location.reload() in the browser, which reloads the page.
js
var title = UI.execute(`return document.title`)In the example above, the test executes return document.title in the browser, and stores the returned value in the variable title.
Executing JavaScript as function
js
var nRows = UI.execute(function () {
let tr = document.querySelectorAll("table tr")
return tr.length
});In the example above, the test executes the function in the browser and returns the number of table tr elements on the page.
Passing arguments
js
var nRows = UI.execute(function (tableSelector, rowSelector) {
let table = document.querySelector(tableSelector)
if(!table){
return 0
}
let rows = table.querySelectorAll(rowSelector)
return rows.length
}, [".employee-table", "tr"]);In the example above, the test passes .employee-table and tr as arguments to the function executed in the browser.