class WebDriver

Alias for webdriver.WebDriver

Creates a new WebDriver client, which provides control over a browser.

Every WebDriver command returns a webdriver.promise.Promise that represents the result of that command. Callbacks may be registered on this object to manipulate the command result or catch an expected error. Any commands scheduled with a callback are considered sub-commands and will execute before the next command in the current frame. For example:

var message = [];
driver.call(message.push, message, 'a').then(function() {
  driver.call(message.push, message, 'b');
});
driver.call(message.push, message, 'c');
driver.call(function() {
  alert('message is abc? ' + (message.join('') == 'abc'));
});

new WebDriver(session, executor, opt_flow)

Parameters
session(webdriver.Session|webdriver.promise.Promise)

Either a known session or a promise that will be resolved to a session.

executorwebdriver.CommandExecutor

The executor to use when sending commands to the browser.

opt_flow?webdriver.promise.ControlFlow=

The flow to schedule commands through. Defaults to the active flow object.

Instance Methods

actions()code »

Creates a new action sequence using this driver. The sequence will not be scheduled for execution until webdriver.ActionSequence#perform is called. Example:

driver.actions().
    mouseDown(element1).
    mouseMove(element2).
    mouseUp().
    perform();
Returns
webdriver.ActionSequence

A new action sequence for this instance.


<T> call(fn, opt_scope, var_args)code »

Schedules a command to execute a custom function.

Parameters
fnfunction(...?): (T|webdriver.promise.Promise<T>)

The function to execute.

opt_scope?Object=

The object in whose scope to execute the function.

var_args...*

Any arguments to pass to the function.

Returns
webdriver.promise.Promise<T>

A promise that will be resolved' with the function's result.


close()code »

Schedules a command to close the current window.

Returns
webdriver.promise.Promise<undefined>

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


controlFlow()code »

Returns
webdriver.promise.ControlFlow

The control flow used by this instance.


<T> executeAsyncScript(script, var_args)code »

Schedules a command to execute 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 webdriver.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 webdriver.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
script(string|Function)

The script to execute.

var_args...*

The arguments to pass to the script.

Returns
webdriver.promise.Promise<T>

A promise that will resolve to the scripts return value.


<T> executeScript(script, var_args)code »

Schedules a command to execute 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 webdriver.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 webdriver.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
script(string|Function)

The script to execute.

var_args...*

The arguments to pass to the script.

Returns
webdriver.promise.Promise<T>

A promise that will resolve to the scripts return value.


findElement(locator)code »

Schedule a command to find an element on the page. If the element cannot be found, a bot.ErrorCode.NO_SUCH_ELEMENT result will be returned by the driver. Unlike other commands, this error cannot be suppressed. In other words, scheduling a command to find an element doubles as an assert that the element is present on the page. To test whether an element is present on the page, use #isElementPresent instead.

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 WebDriver instance and returns a webdriver.WebElement, or a promise that will resolve to a WebElement. 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 webdriver.promise.filter(links, function(link) {
    return links.isDisplayed();
  }).then(function(visibleLinks) {
    return visibleLinks[0];
  });
}

When running in the browser, a WebDriver cannot manipulate DOM elements directly; it may do so only through a webdriver.WebElement reference. This function may be used to generate a WebElement from a DOM element. A reference to the DOM element will be stored in a known location and this driver will attempt to retrieve it through #executeScript. If the element cannot be found (eg, it belongs to a different document than the one this instance is currently focused on), a bot.ErrorCode.NO_SUCH_ELEMENT error will be returned.

Parameters
locator(webdriver.Locator|{className: string}|{css: string}|{id: string}|{js: string}|{linkText: string}|{name: string}|{partialLinkText: string}|{tagName: string}|{xpath: string})

The locator to use.

Returns
webdriver.WebElement

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.


findElements(locator)code »

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

Parameters
locator(webdriver.Locator|{className: string}|{css: string}|{id: string}|{js: string}|{linkText: string}|{name: string}|{partialLinkText: string}|{tagName: string}|{xpath: string})

The locator strategy to use when searching for the element.

Returns
webdriver.promise.Promise<Array<webdriver.WebElement>>

A promise that will resolve to an array of WebElements.


get(url)code »

Schedules a command to navigate to the given URL.

Parameters
urlstring

The fully qualified URL to open.

Returns
webdriver.promise.Promise<undefined>

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


getAllWindowHandles()code »

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

Returns
webdriver.promise.Promise<Array<string>>

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


getCapabilities()code »

Returns
webdriver.promise.Promise<webdriver.Capabilities>

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


getCurrentUrl()code »

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

Returns
webdriver.promise.Promise<string>

A promise that will be resolved with the current URL.


getPageSource()code »

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.

Returns
webdriver.promise.Promise<string>

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


getSession()code »

Returns
webdriver.promise.Promise<webdriver.Session>

A promise for this client's session.


getTitle()code »

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

Returns
webdriver.promise.Promise<string>

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


getWindowHandle()code »

Schedules a command to retrieve they current window handle.

Returns
webdriver.promise.Promise<string>

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


isElementPresent(locatorOrElement)code »

Schedules a command to test if an element is present on the page.

If given a DOM element, this function will check if it belongs to the document the driver is currently focused on. Otherwise, the function will test if at least one element can be found with the given search criteria.

Parameters
locatorOrElement(webdriver.Locator|{className: string}|{css: string}|{id: string}|{js: string}|{linkText: string}|{name: string}|{partialLinkText: string}|{tagName: string}|{xpath: string})

The locator to use, or the actual DOM element to be located by the server.

Returns
webdriver.promise.Promise<boolean>

A promise that will resolve with whether the element is present on the page.


manage()code »

Returns
webdriver.WebDriver.Options

The options interface for this instance.



quit()code »

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

Returns
webdriver.promise.Promise<undefined>

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


<T> schedule(command, description)code »

Schedules a webdriver.Command to be executed by this driver's webdriver.CommandExecutor.

Parameters
commandwebdriver.Command

The command to schedule.

descriptionstring

A description of the command for debugging.

Returns
webdriver.promise.Promise<T>

A promise that will be resolved with the command result.


setFileDetector(detector)code »

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

Parameters
detectorwebdriver.FileDetector

The detector to use or null.


sleep(ms)code »

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

Parameters
msnumber

The amount of time, in milliseconds, to sleep.

Returns
webdriver.promise.Promise<undefined>

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


switchTo()code »

Returns
webdriver.WebDriver.TargetLocator

The target locator interface for this instance.


takeScreenshot()code »

Schedule a command to take a screenshot. The driver makes a 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 screenshot of the entire display containing the browser
Returns
webdriver.promise.Promise<string>

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


touchActions()code »

Creates a new touch sequence using this driver. The sequence will not be scheduled for execution until webdriver.TouchSequence#perform is called. Example:

driver.touchActions().
    tap(element1).
    doubleTap(element2).
    perform();
Returns
webdriver.TouchSequence

A new touch sequence for this instance.


<T> wait(condition, opt_timeout, opt_message)code »

Schedules a command to wait for a condition to hold. The condition may be specified by a webdriver.until.Condition, as a custom function, or as a webdriver.promise.Promise.

For a webdriver.until.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 satisified. Note the resolution time for a promise is factored into whether a wait has timed out.

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

var button = driver.wait(until.elementLocated(By.id('foo')), 10000);
button.click();

This function may also be used to block the command flow on the resolution of a promise. When given a promise, the command will simply wait for its resolution before completing. A timeout may be provided to fail the command if the promise does not resolve before the timeout expires.

Example: Suppose you have a function, startTestServer, that returns a promise for when a server is ready for requests. You can block a WebDriver client on this promise with:

var started = startTestServer();
driver.wait(started, 5 * 1000, 'Server should start within 5 seconds');
driver.get(getServerUrl());
Parameters
condition(webdriver.promise.Promise<T>|webdriver.until.Condition<T>|function(webdriver.WebDriver): T)

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

opt_timeoutnumber=

How long to wait for the condition to be true.

opt_messagestring=

An optional message to use if the wait times out.

Returns
webdriver.promise.Promise<T>

A promise that will be fulfilled with the first truthy value returned by the condition function, or rejected if the condition times out.

Static Functions

WebDriver.attachToSession(executor, sessionId, opt_flow)code »

Creates a new WebDriver client for an existing session.

Parameters
executorwebdriver.CommandExecutor

Command executor to use when querying for session details.

sessionIdstring

ID of the session to attach to.

opt_flow?webdriver.promise.ControlFlow=

The control flow all driver commands should execute under. Defaults to the currently active control flow.

Returns
webdriver.WebDriver

A new client for the specified session.


WebDriver.createSession(executor, desiredCapabilities, opt_flow)code »

Creates a new WebDriver session.

Parameters
executorwebdriver.CommandExecutor

The executor to create the new session with.

desiredCapabilitieswebdriver.Capabilities

The desired capabilities for the new session.

opt_flow?webdriver.promise.ControlFlow=

The control flow all driver commands should execute under, including the initial session creation. Defaults to the currently active control flow.

Returns
webdriver.WebDriver

The driver for the newly created session.

Types

WebDriver.Logs

Interface for managing WebDriver log records.

WebDriver.Navigation

Interface for navigating back and forth in the browser history.

WebDriver.Options

Provides methods for managing browser and driver state.

WebDriver.TargetLocator

An interface for changing the focus of the driver to another frame or window.

WebDriver.Timeouts

An interface for managing timeout behavior for WebDriver instances.

WebDriver.Window

An interface for managing the current window.