To execute your scripted browser monitors using Selenium Webdriver 4.1 APIs, make sure your script's syntax uses the variables $selenium
and $webDriver
. To access Selenium Webdriver APIs 3.6.0, use the variables $driver
and $browser
as described in the 0.5.0+ browser reference documentation.
In particular:
$selenium
provides all the exports from theselenium-webdriver
module (for example,ActionSequence
,Button
,By
, orWebElement
). This maps to$driver
usage in older runtimes.$webDriver
is a synthetic monitoring instance ofselenium-webdriver.WebDriver()
. It exposes the main basicWebDriver
APIs likeget()
andfindElement()
, as well as some synthetic custom APIs. This maps to$browser
usage in older runtimes.$headers
provides the ability to modify request headers. This capability was available in older runtimes in multiple$browser
methods$urlFilter
provides the ability to create allow and deny lists to limit requests to certain domains. This capability was available in older runtimes in multiple$browser
methods
If you're using an older monitor version, see the monitor version 0.5.0 and 0.6.0 documentation or the monitor version 0.4.0 and lower documentation.
For more on monitor versions and runtime differences, see Runtime environments.
Important
Selenium WebDriver promise manager / control flow allowed some functions to execute in order, without manually managing promises/async functions. This was removed in Selenium WebDriver 4.0 and is no longer available in the runtime. All async functions and promises need to be managed with await
or with .then
promise chains. This will ensure script functions execute in the expected order.
For some common usage examples, see Introduction to scripted browser monitors.
Top-level functions: Build your script
New Relic calls top-level functions directly from your $webDriver
instance. These provide a wide range of functionality that covers many basic scriptable actions.
The waitForAndFindElement(locator, timeout)
and waitForPendingRequests(timeout)
methods have been removed from the runtime and are not available via $webDriver
. Backwards compatibility is available, but they're considered deprecated and may be removed from future runtimes. Use the following code snippets to replace their functionality:
Function | Description |
---|---|
| Creates a new action sequence using this driver. For a list of available actions, see ActionSequence. Return value: void |
| Adds header Return value: void |
| Adds multiple headers to the runtime. Return value: void |
| Returns a map of currently configured headers. Return value: promise |
| Returns a map of currently configured headers. Return value: map |
| Returns an array of currently configured header keys. Return value: array |
| Returns a bool indicating if this header exists. Return value: bool |
| Deletes a specific header from the runtime. Return value: void |
| Deletes all headers in the argument from runtime. Return value: void |
| Deletes all headers from runtime. Return value: void |
| Adds all hostnames in an array of arguments to your deny list. Allows using wildcards. Return value: promise |
| Adds all hostnames in an array of arguments to your allow list. Allows using wildcards. Return value: promise |
| Removes all hostnames in the argument from your deny list. Return value: promise |
| Removes all hostnames in the argument from your allow list. Return value: promise |
| Schedules a command to execute asynchronous JavaScript in the context of the currently selected frame or window. Return value: promise |
| Schedules a command to execute JavaScript in the context of the currently selected frame or window. Return value: promise |
| Schedule a command to find an element on the page. If not found, synthetic monitoring returns an error. Return value: WebElementPromise |
| Schedule a command to search for multiple elements on the page. Return value: promise |
| Loads a webpage in a synthetic browser. Return value: promise |
| Schedules a command to retrieve the current list of available window handles. Return value: promise |
| A promise that will resolve with the instance's capabilities. Return value: promise |
| Schedules a command to retrieve the URL of the current page. Return value: promise |
| Schedules a command to retrieve the current page's source. The page source returned is a representation of the underlying DOM. Do not expect it to be formatted or escaped in the same way as the response sent from the web server. Return value: promise |
| A promise for this client's session. Return value: promise |
| Schedules a command to retrieve the current page's title. Return value: promise |
| Schedules a command to retrieve the current window handle. Return value: promise |
| The options interface for this instance. You can manage cookies, timeouts, and other window options. Return value: void |
| The navigation interface (history of browser functions) for this instance. Return value: void |
| Schedules a command to make the driver sleep for the given amount of time. Return value: promise |
| The target locator interface for this instance. Return value: void |
| Schedules a command to take a screenshot. Return value: promise |
| Schedules a command to wait for a condition to hold, as defined by your supplied function. Return value: WebElement |
| Causes the script to wait for requests that have been initiated to return, up to the timeout. Useful for tracking non-blocking resources. Return value: promise |
Deny list: Wildcard use
If you want to add domains to the deny list for your browser instance, the wildcards must match the URL syntax of the URL to be blocked.
An overall .com
deny list must contain these functions:
Function | Blocking action |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
Options: Manage the browser instance
These functions manage options for your browser instance, such as cookies, timeouts, and window size. Access these options through the $webDriver.manage()
function.
Function | Description |
---|---|
| Schedules a command to add a cookie.
Return value: promise |
| Schedules a command to delete all cookies visible to the current page. Return value: promise |
| Schedules a command to delete the cookie with the given name. This command is a no-op if there is no cookie with the given name visible to the current page. Return value: promise |
| Schedules a command to retrieve the cookie with the given name. Returns null if there is no such cookie. The cookie will be returned as a JSON object as described by the WebDriver wire protocol. Return value: promise |
| Schedules a command to retrieve all cookies visible to the current page. New Relic Syntheticcs returns each cookie as a JSON object as described by the WebDriver wire protocol. Return value: promise |
| Returns the current script, pageLoad, and implicit timeouts. Return value: promise |
| Specifies the amount of time the driver should wait when searching for an element if it is not immediately present. Setting the wait timeout to Be careful increasing the wait timeout, as it will increase test run time, especially with slower location strategies like XPath. Default is 10 seconds. Return value: promise |
| Sets the amount of time to wait for a page load to complete before returning an error. If the timeout is negative, page loads may last up to 180 seconds. Default is 60 seconds. Return value: promise |
| Sets the amount of time to wait, in milliseconds, for an asynchronous script to finish execution before returning an error. Default is 30 seconds. Return value: promise |
| Retrieves the window's current position (as x and y), relative to the top left corner of the screen and the window's size (as width and height). Return value: promise |
| Maximizes the current window. Return value: promise |
| Set the window's current position (as x and y), relative to the top left corner of the screen and the window's size (as width and height). Return value: promise |
Locators: Find page elements
Locators are a collection of factory functions for creating locator
instances. Locators find DOM elements, which can be passed to functions such as $webDriver.findElement
. Call them through $selenium.By
.
Function | Description |
---|---|
| Locates an element that has a specific class name. The returned locator is equivalent to searching for elements with the CSS selector Return value: locator |
| Locates an element using a CSS selector. Return value: locator |
| Locates an element by its ID. Return value: locator |
| Locates link elements whose visible text matches the given string. Return value: locator |
| Locates an element by evaluating a JavaScript expression. Return value: locator |
| Locates elements whose name attribute has the given value. Return value: locator |
| Locates link elements whose getText visible contains the given substring. Return value: locator |
| Locates elements with a given tag name. The returned locator is equivalent to using the Return value: locator |
| Locates elements matching a XPath selector. Return value: locator |
WebElement: Interact with page elements
When a function such as $webDriver.findElement
returns a WebElement reference, these functions can be used to interact with that element. For example, you can click on buttons, sent text to form inputs, and get attributes of elements to test.
Function | Description |
---|---|
| Clicks on this element. Return value: self reference |
| Schedules a command to type a sequence on the DOM element represented by this instance. Return value: WebElement |
| Schedules a command to query for the tag/node name of this element. Return value: WebElement |
| Schedules a command to query for the computed style of the element represented by this instance. If the element inherits the named style from its parent, the parent will be queried for its value. Where possible, color values will be converted to their hex representation (for example, Return value: promise |
| Schedules a command to query for the value of the given attribute of the element. Return value: promise |
| Get the visible (not hidden by CSS) Return value: promise |
| Schedules a command to query whether the DOM element represented by this instance is enabled, as dictated by the disabled attribute. Return value: promise |
| Schedules a command to query whether this element is selected. Return value: promise |
| Schedules a command to submit the form containing this element (or this element if it is a Return value: promise |
| Schedules a command to clear the value of this element. Return value: promise |
| Schedules a command to test whether this element is currently displayed. Return value: promise |
ActionSequence: Link multiple actions
Action sequences can create complex user interactions with your website.
- To create a new action sequence, use
$webDriver.actions()
. - To link multiple actions together into a sequence, include
perform()
after each. This executes and then terminates individual sequences, including single-action sequences.
The following table contains a list of available actions. For more information, see the WebDriver ActionSequence documentation on GitHub.
Function | Description |
---|---|
| Clicks a mouse button. If an element is provided, the mouse will first be moved to the center of that element. This is equivalent to Return value: actionsequence |
| Double-clicks a mouse button. If an element is provided, the mouse will first be moved to the center of that element. Return value: actionsequence |
| Convenience function for performing a drag and drop maneuver. The target element may be moved to the location of another element, or by an offset (in pixels). The location is an object with two properties Return value: actionsequence |
| Performs a modifier key press. Must be one of Return value: actionsequence |
| Performs a modifier key release. The release is targeted at the currently focused element. Return value: actionsequence |
| Presses a mouse button. The mouse button will not be released until Return value: actionsequence |
| Releases a mouse button. Behavior is undefined for calling this function without a previous call to Return value: actionsequence |
| Moves the mouse. The location to move to may be specified in terms of the mouse's current location, an offset relative to the top-left corner of an element, or an element (in which case the middle of the element is used). Return value: actionsequence |
| Executes this action sequence. Return value: promise |
| Simulates typing multiple keys. Each modifier key encountered in the sequence will not be released until it is encountered again. All key events will be targeted at the currently focused element. For a full list of supported non-alphanumeric keys, see the WebDriver enum key documentation on GitHub. Return value: actionsequence |
Promises: Link actions into sequences
You can also execute functions directly on promises. Synthetic monitoring is a native Node.js environment and uses standard Node.js promises.
These functions evaluate the status of promises, cancel them, and more. In particular, you can create sequences of actions with the then()
function and its siblings, finally()
and catch()
. For more information, see Sequence actions.
Tip
In addition to supporting promise chaining using .then syntax, this runtime also supports async-await syntax.
Function | Description |
---|---|
| Whether this promise's value is still being computed. Return value: boolean |
| Registers listeners for when this instance is resolved. This is the basic function used to link synchronous actions in your script. Return value: promise |
| Registers a listener to invoke when this promise is resolved, regardless of whether the promise's value was successfully computed. Return value: promise |
| Registers a listener for when this promise is rejected. Return value: promise |
Navigate: Move through browser history
The $webDriver.navigate()
function exposes a number of functions that allow you to move backwards and forwards through your browser history, refresh your page and navigate to new pages.
Function | Description |
---|---|
| Move back by one step in the browser's history. Return value: void |
| Move forward by one step in the browser's history. Return value: void |
| Refresh the current page. Return value: void |
| Load a new webpage in the current browser window. Return value: void |
Conditions: Pause and wait for conditions
Tip
You can learn more about waits in Selenium in their official documentation.
Used with $webDriver.wait
, until
pauses your script execution until the condition is matched. For more information, see Selenium's WebDriver until
documentation.
The following are available functions for $selenium.until.Condition
:
Function | Description |
---|---|
| Creates a condition that will wait until the input driver is able to switch to the designated frame. The target frame may be specified as:
|
| Creates a condition that waits for an alert to be opened. Upon success, the returned promise will be fulfilled with the handle for the opened alert. Return value: condition |
| Creates a condition that will wait for the given element to be disabled. Return value: condition |
| Creates a condition that will wait for the given element to be enabled. Return value: condition |
| Creates a condition that will wait for the given element to be in the DOM, yet not visible to the user. Return value: condition |
| Creates a condition that will wait for the given element to become visible. Return value: condition |
| Creates a condition that will wait for the given element to be selected. Return value: condition |
| Creates a condition that will loop until an element is found with the given locator. Return value: condition |
| Creates a condition that will loop until at least one element is found with the given locator. Return value: condition n |
| Creates a condition that will wait for the given element's visible text to contain the given substring. Return value: condition |
| Case sensitive. Creates a condition that will wait for the given element's visible text to match the given text exactly. Return value: condition n |
| Creates a condition that will wait for the given element's visible text to match a regular expression. Return value: condition |
| Creates a condition that will wait for the given element to become stale. An element is considered stale once it is removed from the DOM or a new page has loaded. Return value: condition |
| Creates a condition that will wait for the current page's title to contain the given substring. Return value: condition |
| Creates a condition that will wait for the current page's title to match the given value. Return value: condition |
| Creates a condition that will wait for the current page's title to match the given regular expression. Return value: condition |
Advanced example
The following example separates the code into functional sections: Constants, dependencies, configuration, page elements, functions, and start of script. It demonstrates how you can:
- Configure timeouts to minimize failure durations for better performance.
- Locate elements by CSS or ID.
- Define
waitForAndFindElement
. - Use
console.log()
to organize the script log and pin down issues with assert failures or timeouts. - Handle errors with a try/catch block that throws a useful error message identifying the failure step.
- Allows use of top level
await
because we run the entire script inside an async function behind the scenes.
/** * Script Name: Advanced Example * Author: New Relic * Version: 1.6 */
// -------------------- CONSTANTSconst SCRIPT_NAME = "Best Practices - Chrome 100" // name to record in script logconst IMPLICIT_TIMEOUT = 3000 // default implicit timeout is 10 secondsconst PAGE_LOAD_TIMEOUT = 60000 // default page load timeout is 60 seconds, fail early to prevent long duration timeoutsconst SCRIPT_TIMEOUT = 20000 // default script timeout is 30 secondsconst USER_AGENT = "default" // set the user agent for Chromeconst PROTOCOL = "https://" // set the protocolconst USERNAME = "" // username:const PASSWORD = "" // password@const DOMAIN = "docs.newrelic.com" // your domainconst PATH = "/docs/new-relic-solutions/get-started/intro-new-relic/" // path to main pageconst CHECK = "Get started with New Relic" // text to match on pageconst AUTH = USERNAME + PASSWORD // could be stored as secure credentialsconst MAIN_URL = PROTOCOL + AUTH + DOMAIN + PATH
// -------------------- DEPENDENCIESconst assert = require("assert")
// -------------------- CONFIGURATIONawait $webDriver.manage().setTimeouts({ implicit: IMPLICIT_TIMEOUT, // sets element load timeout pageLoad: PAGE_LOAD_TIMEOUT, // sets page load timeout script: SCRIPT_TIMEOUT // sets script timeout})
// -------------------- ELEMENTSconst By = $selenium.Byconst loc = { title: By.css("#gatsby-focus-wrapper > div.css-1uz5ayg > div > main > div > h1"), start: [ { step: 'signup', selector: By.id("sign-up-for-new-relic-if-you-havent-already") }, { step: 'add', selector: By.id("add-your-data") }, { step: 'explore', selector: By.id("explore-your-data") }, { step: 'query', selector: By.id("query-your-data") }, { step: 'dashboard', selector: By.id("set-up-a-dashboard") }, { step: 'alerts', selector: By.id("configure-alerts") } ]}
// -------------------- FUNCTIONS// for backwards compatibility with legacy runtimesasync function waitForAndFindElement(locator, timeout) { const element = await $webDriver.wait( $selenium.until.elementLocated(locator), timeout, "Timed-out waiting for element to be located using: " + locator ) await $webDriver.wait( $selenium.until.elementIsVisible(element), timeout, "Timed-out waiting for element to be visible using ${element}" ) return await $webDriver.findElement(locator)}
// -------------------- START OF SCRIPT// Start loggingconst start_time = new Date()console.log("Starting synthetics script: " + SCRIPT_NAME)
// confirm timeouts are setconst {implicit, pageLoad, script} = await $webDriver.manage().getTimeouts()console.log("Timeouts are set to:")console.log(" IMPLICIT: " + implicit / 1000 + "s")console.log(" PAGE LOAD: " + pageLoad / 1000 + "s")console.log(" SCRIPT: " + script / 1000 + "s")
// Setting User Agent is not then-able, so we do this first (if defined and not default)if (USER_AGENT && 0 !== USER_AGENT.trim().length && USER_AGENT != "default") { $headers.add("User-Agent", USER_AGENT) console.log("Setting User-Agent to " + USER_AGENT)}
// if an error happens at any step, script execution is halted and a failed result is returnedconsole.log("1. get: " + MAIN_URL)await $webDriver.get(MAIN_URL)
console.log("2. waitForAndFindElement: " + loc.title)const textBlock = await waitForAndFindElement(loc.title, IMPLICIT_TIMEOUT)
console.log("3. getText: " + CHECK)const text1 = await textBlock.getText()
console.log("4. assert.equal: " + text1)assert.equal(text1, CHECK, "title validation text not found")
console.log("5. takeScreenshot")await $webDriver.takeScreenshot()
console.log("6. findElement")loc.start.forEach(async function (nr, i) { let n = i + 1 try{ // verify each asset has loaded console.log(" " + n + ". " + nr.step + ": " + nr.selector) await $webDriver.findElement(nr.selector) }catch(exception){ console.error("Failure in Step 6." + n) throw exception }})
// End loggingconst end_time = new Date()
// Calculate the durationconst script_duration = (end_time - start_time) / 1000
// Log the timesconsole.log("Start time: " + start_time)console.log("End time: " + end_time)console.log("Duration: " + script_duration + "s")
Shadow DOM: Finding elements
The runtime also supports accessing shadow DOM elements using the new Selenium WebDriver method getShadowRoot()
.
- Use
findElement
or a similar top-level function to find the shadow host. This is the element that the shadow-root is mounted to. - Use the
getShadowRoot()
method on the element found in step 1 to get the shadow root. - Using the shadow root, you can now use findElement or similar functions to find elements inside of the shadow root. If multiple levels of shadow DOM are used, these steps will need to be repeated until you access the shadow root object that contains the element you need to interact with.
Tip
Chrome doesn't support using XPath locators inside of a shadow root object. Use a different locator option to find elements inside of a shadow root object.
Example:
// Find the shadow hostlet myShadowHost = await $webDriver.findElement($selenium.By.id('exampleShadowHost'));// Get the shadow rootlet myShadowRoot = await myShadowHost.getShadowRoot();// Interact with an element inside the shadow rootlet el = await myShadowRoot.findElement($selenium.By.id('myButton'));await el.click();