WebDriver

Each WebDriver instance provides automated control over a browser session.

Constructor

new WebDriver(session, executornon-null, onQuitopt)

Parameters:
NameTypeAttributesDescription
session
executorcommand.Executor

The executor to use when sending commands to the browser.

onQuitfunction<optional>

A function to call, if any, when the session is terminated.

Implements

Methods

actions(optionsopt) → (non-null) {input.Actions}

Creates a new action sequence using this driver. The sequence will not be submitted for execution until Actions.perform() is called.

Parameters:
NameTypeAttributesDescription
optionsObject<optional>

Configuration options for the action sequence (see Actions documentation for details).

Returns:

A new action sequence for this instance.

Type: 
input.Actions

(async) addCredential(credential)

Injects a credential into the authenticator.

Parameters:
NameTypeDescription
credential

Credential to be added

(async) addVirtualAuthenticator(options)

Adds a virtual authenticator with the given options.

Parameters:
NameTypeDescription
options

VirtualAuthenticatorOptions object to set authenticator options.

close() → (non-null) {Promise.<void>}

Closes the current window.

Returns:

A promise that will be resolved when this command has completed.

Type: 
Promise.<void>

(async) createCDPConnection() → (non-null) {Promise.<resolved>}

Creates a new WebSocket connection.

Returns:

A new CDP instance.

Type: 
Promise.<resolved>

(async) execute(commandnon-null) → (non-null) {Promise.<T>}

Executes the provided command.Command using this driver's command.Executor.

Parameters:
NameTypeDescription
commandcommand.Command

The command to schedule.

Returns:

A promise that will be resolved with the command result.

Type: 
Promise.<T>

executeAsyncScript(scriptnon-null, …args) → (non-null) {IThenable.<T>}

Executes a snippet of asynchronous JavaScript in the context of the currently selected frame or window. The script fragment will be executed as the body of an anonymous function. If the script is provided as a function object, that function will be converted to a string for injection into the target window.

Any arguments provided in addition to the script will be included as script arguments and may be referenced using the arguments object. Arguments may be a boolean, number, string, or WebElement. Arrays and objects may also be used as script arguments as long as each item adheres to the types previously mentioned.

Unlike executing synchronous JavaScript with #executeScript, scripts executed with this function must explicitly signal they are finished by invoking the provided callback. This callback will always be injected into the executed function as the last argument, and thus may be referenced with arguments[arguments.length - 1]. The following steps will be taken for resolving this functions return value against the first argument to the script's callback function:

  • For a HTML element, the value will resolve to a WebElement
  • Null and undefined return values will resolve to null
  • Booleans, numbers, and strings will resolve as is
  • Functions will resolve to their string representation
  • For arrays and objects, each member item will be converted according to the rules above

Example #1: Performing a sleep that is synchronized with the currently selected window:

var start = new Date().getTime();
driver.executeAsyncScript(
    'window.setTimeout(arguments[arguments.length - 1], 500);').
    then(function() {
      console.log(
          'Elapsed time: ' + (new Date().getTime() - start) + ' ms');
    });

Example #2: Synchronizing a test with an AJAX application:

var button = driver.findElement(By.id('compose-button'));
button.click();
driver.executeAsyncScript(
    'var callback = arguments[arguments.length - 1];' +
    'mailClient.getComposeWindowWidget().onload(callback);');
driver.switchTo().frame('composeWidget');
driver.findElement(By.id('to')).sendKeys('dog@example.com');

Example #3: Injecting a XMLHttpRequest and waiting for the result. In this example, the inject script is specified with a function literal. When using this format, the function is converted to a string for injection, so it should not reference any symbols not defined in the scope of the page under test.

driver.executeAsyncScript(function() {
  var callback = arguments[arguments.length - 1];
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "/resource/data.json", true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      callback(xhr.responseText);
    }
  };
  xhr.send('');
}).then(function(str) {
  console.log(JSON.parse(str)['food']);
});
Parameters:
NameTypeAttributesDescription
scriptstring | function

The script to execute.

args*<repeatable>

The arguments to pass to the script.

Returns:

A promise that will resolve to the scripts return value.

Type: 
IThenable.<T>

executeScript(scriptnon-null, …args) → (non-null) {IThenable.<T>}

Executes a snippet of JavaScript in the context of the currently selected frame or window. The script fragment will be executed as the body of an anonymous function. If the script is provided as a function object, that function will be converted to a string for injection into the target window.

Any arguments provided in addition to the script will be included as script arguments and may be referenced using the arguments object. Arguments may be a boolean, number, string, or WebElement. Arrays and objects may also be used as script arguments as long as each item adheres to the types previously mentioned.

The script may refer to any variables accessible from the current window. Furthermore, the script will execute in the window's context, thus document may be used to refer to the current document. Any local variables will not be available once the script has finished executing, though global variables will persist.

If the script has a return value (i.e. if the script contains a return statement), then the following steps will be taken for resolving this functions return value:

  • For a HTML element, the value will resolve to a WebElement
  • Null and undefined return values will resolve to null
  • Booleans, numbers, and strings will resolve as is
  • Functions will resolve to their string representation
  • For arrays and objects, each member item will be converted according to the rules above
Parameters:
NameTypeAttributesDescription
scriptstring | function

The script to execute.

args*<repeatable>

The arguments to pass to the script.

Returns:

A promise that will resolve to the scripts return value.

Type: 
IThenable.<T>

findElement(locatornon-null) → (non-null) {WebElementPromise}

Locates an element on the page. If the element cannot be found, a error.NoSuchElementError will be returned by the driver.

This function should not be used to test whether an element is present on the page. Rather, you should use #findElements:

driver.findElements(By.id('foo'))
    .then(found => console.log('Element found? %s', !!found.length));

The search criteria for an element may be defined using one of the factories in the webdriver.By namespace, or as a short-hand webdriver.By.Hash object. For example, the following two statements are equivalent:

var e1 = driver.findElement(By.id('foo'));
var e2 = driver.findElement({id:'foo'});

You may also provide a custom locator function, which takes as input this instance and returns a WebElement, or a promise that will resolve to a WebElement. If the returned promise resolves to an array of WebElements, WebDriver will use the first element. For example, to find the first visible link on a page, you could write:

var link = driver.findElement(firstVisibleLink);

function firstVisibleLink(driver) {
  var links = driver.findElements(By.tagName('a'));
  return promise.filter(links, function(link) {
    return link.isDisplayed();
  });
}
Parameters:
NameTypeDescription
locatorby.By | function

The locator to use.

Returns:

A WebElement that can be used to issue commands against the located element. If the element is not found, the element will be invalidated and all scheduled commands aborted.

Type: 
WebElementPromise

(async) findElements(locatornon-null) → (non-null) {Promise.<!Array.<!WebElement>>}

Search for multiple elements on the page. Refer to the documentation on #findElement(by) for information on element locator strategies.

Parameters:
NameTypeDescription
locatorby.By | function

The locator to use.

Returns:

A promise that will resolve to an array of WebElements.

Type: 
Promise.<!Array.<!WebElement>>

get(url) → (non-null) {Promise.<void>}

Navigates to the given URL.

Parameters:
NameTypeDescription
urlstring

The fully qualified URL to open.

Implements
Returns:

A promise that will be resolved when the document has finished loading.

Type: 
Promise.<void>

getAllWindowHandles() → (non-null) {Promise.<!Array.<string>>}

Retrieves a list of all available window handles.

Returns:

A promise that will be resolved with an array of window handles.

Type: 
Promise.<!Array.<string>>

(async) getBidi() → {BIDI}

Initiates bidi connection using 'webSocketUrl'

Returns:
Type: 
BIDI

getCapabilities() → (non-null) {Promise.<!Capabilities>}

Returns:

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

Type: 
Promise.<!Capabilities>

(async) getCredentials()

Returns:

The list of credentials owned by the authenticator.

getCurrentUrl() → (non-null) {Promise.<string>}

Retrieves the URL for the current page.

Returns:

A promise that will be resolved with the current URL.

Type: 
Promise.<string>

getExecutor() → (non-null) {command.Executor}

Returns:

The command executor used by this instance.

Type: 
command.Executor

getPageSource() → (non-null) {Promise.<string>}

Retrieves the current page's source. The returned source is a representation of the underlying DOM: do not expect it to be formatted or escaped in the same way as the raw response sent from the web server.

Returns:

A promise that will be resolved with the current page source.

Type: 
Promise.<string>

getSession() → (non-null) {Promise.<!Session>}

Returns:

A promise for this client's session.

Type: 
Promise.<!Session>

getTitle() → (non-null) {Promise.<string>}

Retrieves the current page title.

Returns:

A promise that will be resolved with the current page's title.

Type: 
Promise.<string>

getWindowHandle() → (non-null) {Promise.<string>}

Retrieves the current window handle.

Returns:

A promise that will be resolved with the current window handle.

Type: 
Promise.<string>

(async) getWsUrl(debuggerAddress, target, caps) → {string}

Retrieves 'webSocketDebuggerUrl' by sending a http request using debugger address

Parameters:
NameTypeDescription
debuggerAddressstring
target
caps
Returns:

Returns parsed webSocketDebuggerUrl obtained from the http request

Type: 
string

(async) logMutationEvents(connection, callback) → {Promise.<void>}

Parameters:
NameTypeDescription
connection
callback
Returns:
Type: 
Promise.<void>

manage() → (non-null) {Options}

Returns:

The options interface for this instance.

Type: 
Options
Returns:

The navigation interface for this instance.

Type: 
Navigation

(async) normalize_(webElementPromisenon-null) → (non-null) {Promise.<!WebElement>}

Parameters:
NameTypeDescription
webElementPromisefunction

The webElement in unresolved state

Returns:

First single WebElement from array of resolved promises

Type: 
Promise.<!WebElement>

(async) onIntercept(connection, httpResponse, callback)

Handle Network interception requests

Parameters:
NameTypeDescription
connection

WebSocket connection to the browser

httpResponse

Object representing what we are intercepting as well as what should be returned.

callback

callback called when we intercept requests.

(async) onLogEvent(connection, callback) → {Promise.<void>}

Parameters:
NameTypeDescription
connection
callback
Returns:
Type: 
Promise.<void>

(async) onLogException(connection, callback) → {Promise.<void>}

Parameters:
NameTypeDescription
connection
callback
Returns:
Type: 
Promise.<void>

printPage(options)

Takes a PDF of the current page. The driver makes a best effort to return a PDF based on the provided parameters.

Parameters:
NameTypeDescription
optionsObject

quit() → (non-null) {Promise.<void>}

Terminates the browser session. After calling quit, this instance will be invalidated and may no longer be used to issue commands against the browser.

Implements
Returns:

A promise that will be resolved when the command has completed.

Type: 
Promise.<void>

(async) register(username, password, connection)

Sets a listener for Fetch.authRequired event from CDP If event is triggered, it enters username and password and allows the test to move forward

Parameters:
NameTypeDescription
usernamestring
passwordstring
connection

CDP Connection

(async) removeAllCredentials()

Removes all the credentials from the authenticator.

(async) removeCredential(credential_id)

Removes a credential from the authenticator.

Parameters:
NameTypeDescription
credential_id

The ID of the credential to be removed.

(async) removeVirtualAuthenticator()

Removes a previously added virtual authenticator. The authenticator is no longer valid after removal, so no methods may be called.

setFileDetector(detector)

Sets the file detector that should be used with this instance.

Parameters:
NameTypeDescription
detectorinput.FileDetector

The detector to use or null.

(async) setUserVerified(verified)

Sets whether the authenticator will simulate success or fail on user verification.

Parameters:
NameTypeDescription
verified

true if the authenticator will pass user verification, false otherwise.

sleep(ms) → (non-null) {Promise.<void>}

Makes the driver sleep for the given amount of time.

Parameters:
NameTypeDescription
msnumber

The amount of time, in milliseconds, to sleep.

Returns:

A promise that will be resolved when the sleep has finished.

Type: 
Promise.<void>

switchTo() → (non-null) {TargetLocator}

Returns:

The target locator interface for this instance.

Type: 
TargetLocator

takeScreenshot() → (non-null) {Promise.<string>}

Takes a screenshot of the current page. The driver makes the best effort to return a screenshot of the following, in order of preference:

  1. Entire page
  2. Current window
  3. Visible portion of the current frame
  4. The entire display containing the browser
Returns:

A promise that will be resolved to the screenshot as a base-64 encoded PNG.

Type: 
Promise.<string>

virtualAuthenticatorId()

Returns:

The value of authenticator ID added

wait(conditionnon-null, timeoutopt, messageopt, pollTimeoutopt) → (non-null) {IThenable.<T>|WebElementPromise}

Waits for a condition to evaluate to a "truthy" value. The condition may be specified by a Condition, as a custom function, or as any promise-like thenable.

For a Condition or function, the wait will repeatedly evaluate the condition until it returns a truthy value. If any errors occur while evaluating the condition, they will be allowed to propagate. In the event a condition returns a Promise, the polling loop will wait for it to be resolved and use the resolved value for whether the condition has been satisfied. The resolution time for a promise is always factored into whether a wait has timed out.

If the provided condition is a WebElementCondition, then the wait will return a WebElementPromise that will resolve to the element that satisfied the condition.

Example: waiting up to 10 seconds for an element to be present on the page.

async function example() {
  let button =
      await driver.wait(until.elementLocated(By.id('foo')), 10000);
  await button.click();
}
Parameters:
NameTypeAttributesDescription
conditionIThenable.<T> | Condition.<T> | function

The condition to wait on, defined as a promise, condition object, or a function to evaluate as a condition.

timeoutnumber<optional>

The duration in milliseconds, how long to wait for the condition to be true.

messagestring | function<optional>

An optional message to use if the wait times out.

pollTimeoutnumber<optional>

The duration in milliseconds, how long to wait between polling the condition.

Implements
Throws:

if the provided condition is not a valid type.

Type
TypeError
Returns:

A promise that will be resolved with the first truthy value returned by the condition function, or rejected if the condition times out. If the input condition is an instance of a WebElementCondition, the returned value will be a WebElementPromise.

Type: 
IThenable.<T> | WebElementPromise

(static) createSession(executornon-null, capabilitiesnon-null, onQuitopt) → (non-null) {WebDriver}

Creates a new WebDriver session.

This function will always return a WebDriver instance. If there is an error creating the session, such as the aforementioned SessionNotCreatedError, the driver will have a rejected session promise. This rejection will propagate through any subsequent commands scheduled on the returned WebDriver instance.

let required = Capabilities.firefox();
let driver = WebDriver.createSession(executor, {required});

// If the createSession operation failed, then this command will also
// also fail, propagating the creation failure.
driver.get('http://www.google.com').catch(e => console.log(e));
Parameters:
NameTypeAttributesDescription
executorcommand.Executor

The executor to create the new session with.

capabilitiesCapabilities

The desired capabilities for the new session.

onQuitfunction<optional>

A callback to invoke when the newly created session is terminated. This should be used to clean up any resources associated with the session.

Returns:

The driver for the newly created session.

Type: 
WebDriver