• /
  • EnglishEspañol日本語한국어Português
  • Log inStart now

Synthetic scripted browser reference (Chrome and Firefox)

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 the selenium-webdriver module (for example, ActionSequence, Button, By, or WebElement). This maps to $driver usage in older runtimes.
  • $webDriver is a synthetic monitoring instance of selenium-webdriver.WebDriver(). It exposes the main basic WebDriver APIs like get() and findElement(), 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

$webDriver.actions()

Creates a new action sequence using this driver. For a list of available actions, see ActionSequence.

Return value: void

$headers.add(headerKey: string, headerValue: string)

Adds header headerKey with value headerValue to the runtime.

Return value: void

$headers.addMultiple(headers: {key:value...})

Adds multiple headers to the runtime.

Return value: void

$headers.get(headerKey: string)

Returns a map of currently configured headers.

Return value: promise

$headers.getAll()

Returns a map of currently configured headers.

Return value: map

$headers.getKeys()

Returns an array of currently configured header keys.

Return value: array

$headers.has(headerKey: string)

Returns a bool indicating if this header exists.

Return value: bool

$headers.remove(header: string)

Deletes a specific header from the runtime.

Return value: void

$headers.removeMmultiple(headers: {key:value...})

Deletes all headers in the argument from runtime.

Return value: void

$headers.clear()

Deletes all headers from runtime.

Return value: void

$urlFilter.addToDenyList(hostnameArr: [string])

Adds all hostnames in an array of arguments to your deny list. Allows using wildcards.

Return value: promise

$urlFilter.addToAllowList(hostnameArr: [string])

Adds all hostnames in an array of arguments to your allow list. Allows using wildcards.

Return value: promise

$urlFilter.removeFromDenyList(hostnameArr: [string])

Removes all hostnames in the argument from your deny list.

Return value: promise

$urlFilter.removeFromAllowList(hostnameArr: [string])

Removes all hostnames in the argument from your allow list.

Return value: promise

$webDriver.executeAsyncScript(script: ?, var_args: ?)

Schedules a command to execute asynchronous JavaScript in the context of the currently selected frame or window.

Return value: promise

$webDriver.executeScript(script: ?, var_args: ?)

Schedules a command to execute JavaScript in the context of the currently selected frame or window.

Return value: promise

$webDriver.findElement(locator: $selenium.Locator)

Schedule a command to find an element on the page. If not found, synthetic monitoring returns an error.

Return value: WebElementPromise

$webDriver.findElements(locator: $selenium.Locator)

Schedule a command to search for multiple elements on the page.

Return value: promise

$webDriver.get(url: string)

Loads a webpage in a synthetic browser.

Return value: promise

$webDriver.getAllWindowHandles()

Schedules a command to retrieve the current list of available window handles.

Return value: promise

$webDriver.getCapabilities()

A promise that will resolve with the instance's capabilities.

Return value: promise

$webDriver.getCurrentUrl()

Schedules a command to retrieve the URL of the current page.

Return value: promise

$webDriver.getPageSource()

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

$webDriver.getSession()

A promise for this client's session.

Return value: promise

$webDriver.getTitle()

Schedules a command to retrieve the current page's title.

Return value: promise

$webDriver.getWindowHandle()

Schedules a command to retrieve the current window handle.

Return value: promise

$webDriver.manage()

The options interface for this instance. You can manage cookies, timeouts, and other window options.

Return value: void

$webDriver.navigate()

The navigation interface (history of browser functions) for this instance.

Return value: void

$webDriver.sleep()

Schedules a command to make the driver sleep for the given amount of time.

Return value: promise

$webDriver.switchTo()

The target locator interface for this instance.

Return value: void

$webDriver.takeScreenshot()

Schedules a command to take a screenshot.

Return value: promise

$webDriver.wait(fn: $driver.Condition, timeout: number, opt_message: string)

Schedules a command to wait for a condition to hold, as defined by your supplied function.

Return value: WebElement

$browser.waitForPendingRequests(timeout: number)

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

$urlFilter.addToDenyList(['*.com']);

a.com

$urlFilter.addToDenyList([*.*.com']);

a.b.com

$urlFilter.addToDenyList([*.*.*.com']);

a.b.c.com

$urlFilter.addToDenyList([www.*.com']);

www.a.com

$urlFilter.addToDenyList([www.*.*.com']);

www.a.b.com

$urlFilter.addToDenyList(['www.*.*.*.com']);

www.a.b.c.com

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

$webDriver.manage().addCookie(spec: object)

Schedules a command to add a cookie.

spec is a record object describing a browser cookie. For more information, see the WebDriver documentation.

Return value: promise

$webDriver.manage().deleteAllCookies()

Schedules a command to delete all cookies visible to the current page.

Return value: promise

$webDriver.manage().deleteCookie(name: string)

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

$webDriver.manage().getCookie(name: string)

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

$webDriver.manage().getCookies()

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

$webDriver.manage().getTimeouts()

Returns the current script, pageLoad, and implicit timeouts.

Return value: promise

$webDriver.manage().setTimeouts({implicit: numberMS})

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 0 disables implicit waiting.

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

$webDriver.manage().setTimeouts({pageLoad: numberMS})

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

$webDriver.manage().setTimeouts({script: numberMS})

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

$webDriver.manage().window().getRect()

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

$webDriver.manage().window().maximize()

Maximizes the current window.

Return value: promise

$webDriver.manage().window().setRect({x: number|undefined, y: number|undefined, width: number|undefined, height: number|undefined})

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

$selenium.By.className(className: string)

Locates an element that has a specific class name. The returned locator is equivalent to searching for elements with the CSS selector .class.

Return value: locator

$selenium.By.css(cssName: string)

Locates an element using a CSS selector.

Return value: locator

$selenium.By.id(id: string)

Locates an element by its ID.

Return value: locator

$selenium.By.linkText(linkText: string)

Locates link elements whose visible text matches the given string.

Return value: locator

$selenium.By.js(js: string)

Locates an element by evaluating a JavaScript expression.

Return value: locator

$selenium.By.name(name: string)

Locates elements whose name attribute has the given value.

Return value: locator

$selenium.By.partialLinkText(partialLinkText: string)

Locates link elements whose getText visible contains the given substring.

Return value: locator

$selenium.By.tagName(tagName: string)

Locates elements with a given tag name. The returned locator is equivalent to using the getElementsByTagName DOM function.

Return value: locator

$selenium.By.xpath(xpath: string)

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

click()

Clicks on this element.

Return value: self reference

sendKeys(var_args: ?)

Schedules a command to type a sequence on the DOM element represented by this instance.

Return value: WebElement

getTagName()

Schedules a command to query for the tag/node name of this element.

Return value: WebElement

getCssValue(name: string)

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, #00ff00 instead of rgb(0, 255, 0)).

Return value: promise

getAttribute(name: string)

Schedules a command to query for the value of the given attribute of the element.

Return value: promise

getText()

Get the visible (not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing white space.

Return value: promise

isEnabled()

Schedules a command to query whether the DOM element represented by this instance is enabled, as dictated by the disabled attribute.

Return value: promise

isSelected()

Schedules a command to query whether this element is selected.

Return value: promise

submit()

Schedules a command to submit the form containing this element (or this element if it is a FORM element). This command is a no-op if the element is not contained in a form.

Return value: promise

clear()

Schedules a command to clear the value of this element.

Return value: promise

isDisplayed()

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

click(opt_elementOrButton: ?, opt_button: ?)

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 WebElement.click().

Return value: actionsequence

doubleClick(opt_elementOrButton: ?, opt_button: ?)

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

dragAndDrop(element: ?, location: ?)

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 x and y: {x: x_offset, y: y_offset}.

Return value: actionsequence

keyDown(key: ?)

Performs a modifier key press. Must be one of ALT, CONTROL, SHIFT, COMMAND, or META. The modifier key is not released until keyUp() or sendKeys() is called. The key press will be targeted at the currently focused element.

Return value: actionsequence

keyUp(key: ?)

Performs a modifier key release. The release is targeted at the currently focused element.

Return value: actionsequence

press(opt_elementOrButton: ?, opt_button: ?)

Presses a mouse button. The mouse button will not be released until release is called, regardless of whether that call is made in this sequence or another. The behavior for out-of-order events (such as calling press() or click() when the button is already held down) is undefined.

Return value: actionsequence

release(opt_elementOrButton: ?, opt_button: ?)

Releases a mouse button. Behavior is undefined for calling this function without a previous call to press().

Return value: actionsequence

move(location: ?, offset: ?)

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

perform()

Executes this action sequence.

Return value: promise

sendKeys(args: ?)

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

isPending()

Whether this promise's value is still being computed.

Return value: boolean

then(opt_callback: fn(T: ?), opt_errback: fn())

Registers listeners for when this instance is resolved. This is the basic function used to link synchronous actions in your script.

Return value: promise

finally(callback: fn())

Registers a listener to invoke when this promise is resolved, regardless of whether the promise's value was successfully computed.

Return value: promise

catch(callback: fn())

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

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

ableToSwitchToFrame(frame: ?)

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:

  • A numeric index into window.frames for the current frame

  • A webdriver.WebElement, which must reference a FRAME or IFRAME element on the current page

  • A locator which may be used to first locate a FRAME or IFRAME on the current page before attempting to switch to it

    Upon successful resolution of this condition, the driver will be left focused on the new frame.

    Return value: condition

alertIsPresent()

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

elementIsDisabled(element: $selenium.WebElement)

Creates a condition that will wait for the given element to be disabled.

Return value: condition

elementIsEnabled(element: $selenium.WebElement)

Creates a condition that will wait for the given element to be enabled.

Return value: condition

elementIsNotVisible(element: $selenium.WebElement)

Creates a condition that will wait for the given element to be in the DOM, yet not visible to the user.

Return value: condition

elementIsVisible(element: $selenium.WebElement)

Creates a condition that will wait for the given element to become visible.

Return value: condition

elementIsSelected(element: $selenium.WebElement)

Creates a condition that will wait for the given element to be selected.

Return value: condition

elementLocated(element: $selenium.Locator)

Creates a condition that will loop until an element is found with the given locator.

Return value: condition

elementsLocated(element: $selenium.Locator)

Creates a condition that will loop until at least one element is found with the given locator.

Return value: condition

n

elementTextContains(element: $selenium.WebElement, substr: string)

Creates a condition that will wait for the given element's visible text to contain the given substring.

Return value: condition

elementTextIs(element: $selenium.WebElement, text: string)

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

elementTextMatches(element: $selenium.WebElement, regex: string)

Creates a condition that will wait for the given element's visible text to match a regular expression.

Return value: condition

stalenessOf(element: $selenium.WebElement)

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

titleContains(substr: string)

Creates a condition that will wait for the current page's title to contain the given substring.

Return value: condition

titleIs(title: string)

Creates a condition that will wait for the current page's title to match the given value.

Return value: condition

titleMatches(regex: string)

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
*/
// -------------------- CONSTANTS
const SCRIPT_NAME = "Best Practices - Chrome 100" // name to record in script log
const IMPLICIT_TIMEOUT = 3000 // default implicit timeout is 10 seconds
const PAGE_LOAD_TIMEOUT = 60000 // default page load timeout is 60 seconds, fail early to prevent long duration timeouts
const SCRIPT_TIMEOUT = 20000 // default script timeout is 30 seconds
const USER_AGENT = "default" // set the user agent for Chrome
const PROTOCOL = "https://" // set the protocol
const USERNAME = "" // username:
const PASSWORD = "" // password@
const DOMAIN = "docs.newrelic.com" // your domain
const PATH = "/docs/new-relic-solutions/get-started/intro-new-relic/" // path to main page
const CHECK = "Get started with New Relic" // text to match on page
const AUTH = USERNAME + PASSWORD // could be stored as secure credentials
const MAIN_URL = PROTOCOL + AUTH + DOMAIN + PATH
// -------------------- DEPENDENCIES
const assert = require("assert")
// -------------------- CONFIGURATION
await $webDriver.manage().setTimeouts({
implicit: IMPLICIT_TIMEOUT, // sets element load timeout
pageLoad: PAGE_LOAD_TIMEOUT, // sets page load timeout
script: SCRIPT_TIMEOUT // sets script timeout
})
// -------------------- ELEMENTS
const By = $selenium.By
const 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 runtimes
async 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 logging
const start_time = new Date()
console.log("Starting synthetics script: " + SCRIPT_NAME)
// confirm timeouts are set
const {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 returned
console.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 logging
const end_time = new Date()
// Calculate the duration
const script_duration = (end_time - start_time) / 1000
// Log the times
console.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().

  1. Use findElement or a similar top-level function to find the shadow host. This is the element that the shadow-root is mounted to.
  2. Use the getShadowRoot() method on the element found in step 1 to get the shadow root.
  3. 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 host
let myShadowHost = await $webDriver.findElement($selenium.By.id('exampleShadowHost'));
// Get the shadow root
let myShadowRoot = await myShadowHost.getShadowRoot();
// Interact with an element inside the shadow root
let el = await myShadowRoot.findElement($selenium.By.id('myButton'));
await el.click();
Copyright © 2024 New Relic Inc.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.