Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • WebDriver
    • WebDriver4

Index

Constructors

constructor

  • new WebDriver4(session: Session | Promise<Session>, executor: Executor, opt_flow?: promise.ControlFlow): WebDriver4
  • Parameters

    • session: Session | Promise<Session>

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

    • executor: Executor

      The executor to use when sending commands to the browser.

    • Optional opt_flow: promise.ControlFlow

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

    Returns WebDriver4

Methods

actions

  • actions(options?: undefined | object): ActionSequence
  • Parameters

    • Optional options: undefined | object

    Returns ActionSequence

call

  • call<T>(fn: function, opt_scope?: any, ...var_args: any[]): Promise<T>
  • Schedules a command to execute a custom function.

    template

    T

    Type parameters

    • T

    Parameters

    • fn: function

      The function to execute.

        • (...var_args: any[]): T | Promise<T>
        • Parameters

          • Rest ...var_args: any[]

          Returns T | Promise<T>

    • Optional opt_scope: any

      The object in whose scope to execute the function.

    • Rest ...var_args: any[]

      Any arguments to pass to the function.

    Returns Promise<T>

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

close

  • close(): Promise<void>
  • Schedules a command to close the current window.

    Returns Promise<void>

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

controlFlow

  • controlFlow(): ControlFlow
  • Returns ControlFlow

    The control flow used by this instance.

executeAsyncScript

  • executeAsyncScript<T>(script: string | Function, ...var_args: any[]): Promise<T>
  • 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 {@code arguments} object. Arguments may be a boolean, number, string, or {@code 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 {@link #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 {@code 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 {@link 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']);
    });
    
    template

    T

    Type parameters

    • T

    Parameters

    • script: string | Function

      The script to execute.

    • Rest ...var_args: any[]

      The arguments to pass to the script.

    Returns Promise<T>

    A promise that will resolve to the scripts return value.

executeScript

  • executeScript<T>(script: string | Function, ...var_args: any[]): Promise<T>
  • 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 {@code arguments} object. Arguments may be a boolean, number, string, or {@code 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 {@code 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 {@link 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
    template

    T

    Type parameters

    • T

    Parameters

    • script: string | Function

      The script to execute.

    • Rest ...var_args: any[]

      The arguments to pass to the script.

    Returns Promise<T>

    A promise that will resolve to the scripts return value.

findElement

  • findElement(locator: Locator): WebElementPromise
  • Schedule a command to find an element on the page. If the element cannot be found, a {@link 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 {@link #findElements}.

    The search criteria for an element may be defined using one of the factories in the {@link By} namespace, or as a short-hand {@link 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 {@link 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

    • locator: Locator

      The locator to use.

    Returns WebElementPromise

    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

  • findElements(locator: Locator): Promise<WebElement[]>
  • Schedule a command to search for multiple elements on the page.

    Parameters

    • locator: Locator

      The locator to use.

    Returns Promise<WebElement[]>

    A promise that will resolve to an array of WebElements.

get

  • get(url: string): Promise<void>
  • Schedules a command to navigate to the given URL.

    Parameters

    • url: string

      The fully qualified URL to open.

    Returns Promise<void>

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

getAllWindowHandles

  • getAllWindowHandles(): Promise<string[]>
  • Schedules a command to retrieve the current list of available window handles.

    Returns Promise<string[]>

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

getCapabilities

  • getCapabilities(): Promise<Capabilities>
  • Returns Promise<Capabilities>

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

getCurrentUrl

  • getCurrentUrl(): Promise<string>
  • Schedules a command to retrieve the URL of the current page.

    Returns Promise<string>

    A promise that will be resolved with the current URL.

getPageSource

  • getPageSource(): Promise<string>
  • 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 Promise<string>

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

getSession

  • getSession(): Promise<Session>
  • Returns Promise<Session>

    A promise for this client's session.

getTitle

  • getTitle(): Promise<string>
  • Schedules a command to retrieve the current page's title.

    Returns Promise<string>

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

getWindowHandle

  • getWindowHandle(): Promise<string>
  • Schedules a command to retrieve they current window handle.

    Returns Promise<string>

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

manage

  • manage(): Options
  • Returns Options

    The options interface for this instance.

navigate

  • navigate(): Navigation
  • Returns Navigation

    The navigation interface for this instance.

quit

  • quit(): Promise<void>
  • 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 Promise<void>

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

schedule

  • schedule<T>(command: Command, description: string): Promise<T>
  • Schedules a {@link command.Command} to be executed by this driver's {@link command.Executor}.

    template

    T

    Type parameters

    • T

    Parameters

    • command: Command

      The command to schedule.

    • description: string

      A description of the command for debugging.

    Returns Promise<T>

    A promise that will be resolved with the command result.

setFileDetector

  • setFileDetector(detector: FileDetector): void
  • Sets the {@linkplain input.FileDetector file detector} that should be used with this instance.

    Parameters

    • detector: FileDetector

      The detector to use or {@code null}.

    Returns void

sleep

  • sleep(ms: number): Promise<void>
  • Schedules a command to make the driver sleep for the given amount of time.

    Parameters

    • ms: number

      The amount of time, in milliseconds, to sleep.

    Returns Promise<void>

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

switchTo

  • switchTo(): TargetLocator
  • Returns TargetLocator

    The target locator interface for this instance.

takeScreenshot

  • takeScreenshot(): Promise<string>
  • 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 entire display containing the browser

    Returns Promise<string>

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

touchActions

  • touchActions(): TouchSequence
  • Creates a new touch sequence using this driver. The sequence will not be scheduled for execution until {@link actions.TouchSequence#perform} is called. Example:

    driver.touchActions().
        tap(element1).
        doubleTap(element2).
        perform();
    

    Returns TouchSequence

    A new touch sequence for this instance.

wait

  • wait(condition: WebElementCondition, opt_timeout?: undefined | number, opt_message?: undefined | string): WebElementPromise
  • wait<T>(condition: PromiseLike<T> | Condition<T> | function | Function, opt_timeout?: undefined | number, opt_message?: undefined | string): Promise<T>
  • Schedules a command to wait for a condition to hold. The condition may be specified by a {@link Condition}, as a custom function, or as a {@link promise.Promise}.

    For a {@link 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 {@link promise.Promise 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.

    Note, if the provided condition is a {@link WebElementCondition}, then the wait will return a {@link WebElementPromise} that will resolve to the element that satisified the condition.

    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 {@link promise.Promise 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());
    
    template

    T

    Parameters

    • condition: WebElementCondition

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

    • Optional opt_timeout: undefined | number

      How long to wait for the condition to be true.

    • Optional opt_message: undefined | string

      An optional message to use if the wait times out.

    Returns WebElementPromise

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

  • Schedules a command to wait for a condition to hold. The condition may be specified by a {@link webdriver.Condition}, as a custom function, or as a {@link webdriver.promise.Promise}.

    For a {@link webdriver.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 {@link webdriver.promise.Promise 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.

    Note, if the provided condition is a {@link WebElementCondition}, then the wait will return a {@link WebElementPromise} that will resolve to the element that satisified the condition.

    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 {@link webdriver.promise.Promise 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());
    
    template

    T

    Type parameters

    • T

    Parameters

    • condition: PromiseLike<T> | Condition<T> | function | Function
    • Optional opt_timeout: undefined | number

      How long to wait for the condition to be true.

    • Optional opt_message: undefined | string

      An optional message to use if the wait times out.

    Returns 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 attachToSession

  • attachToSession(executor: Executor, sessionId: string, opt_flow?: promise.ControlFlow): WebDriver
  • Creates a new WebDriver client for an existing session.

    Parameters

    • executor: Executor

      Command executor to use when querying for session details.

    • sessionId: string

      ID of the session to attach to.

    • Optional opt_flow: promise.ControlFlow

      The control flow all driver commands should execute under. Defaults to the {@link promise.controlFlow() currently active} control flow.

    Returns WebDriver

    A new client for the specified session.

Static createSession

  • createSession(...var_args: any[]): WebDriver
  • Creates a new WebDriver session.

    By default, the requested session capabilities are merely "desired" and the remote end will still create a new session even if it cannot satisfy all of the requested capabilities. You can query which capabilities a session actually has using the {@linkplain #getCapabilities() getCapabilities()} method on the returned WebDriver instance.

    To define required capabilities, provide the capabilities as an object literal with required and desired keys. The desired key may be omitted if all capabilities are required, and vice versa. If the server cannot create a session with all of the required capabilities, it will return an {@linkplain error.SessionNotCreatedError}.

    let required = new Capabilities().set('browserName', 'firefox');
    let desired = new Capabilities().set('version', '45');
    let driver = WebDriver.createSession(executor, {required, desired});
    

    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 {@linkplain #getSession session} promise. It is recommended that this promise is left unhandled so it will propagate through the {@linkplain promise.ControlFlow control flow} and cause subsequent commands to fail.

    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

    • Rest ...var_args: any[]

    Returns WebDriver

    The driver for the newly created session.