API

newSession(options)

Before we can send any command to the browser we drive we need to create a WebDriver session. This should be always the first step of interaction through the protocol. After executing this command the browser will be started and ready to receive the commands. As part of session creation we have to provide the url of WebDriver protocol compliant server. This can be a locally running browser driver server (Chromedriver, Geckodriver, etc.), Selenium Server or Grid or cloud provider url (BrowserStack, Sauce Labs, .etc.). Also we can set the browser and operating system parameters we want to interact with.
See also
Parameters
  • options: object
    • capabilities: Capabilities WebDriver capabilities
    • desiredCapabilities?: object Legacy WebDriver capabilities. Can be used to enable the new W3C dialect
    • headers?: HeaderInit Session creation request headers. Can be used for authorization. See example
    • url: string WebDriver server URL
Returns
Promise<Session>
Examples
 

import { newSession } from 'w3c-webdriver';

let session;

(async () => {
  try {
    session = await newSession({
      url: 'http://localhost:4444',
      capabilities: {
        alwaysMatch: {
          browserName: 'Chrome'
        }
      }
    });
  } catch (err) {
    console.log(err.stack);
  } finally {
    session.close();
  }
})();
 

const credentials = Buffer.from(['myusername', 'Password123'].join(':')).toString('base64');
const session = await newSession({
  headers: {
    Authorization: `Basic ${credentials}`
  }
});

status(url)

To be able to verify if the WebDriver server is ready for new session creation sometimes it can be useful to query it's status. This function queries the WebDriver server's current status. The status contains meta information about the WebDriver server and operating system.
See also
Parameters
  • url: string
Returns
Promise<Status>
Examples
 

import { status } from 'w3c-webdriver';

const status = await status('http://localhost:4444');
// status = {
//   build: { version: '1.2.0' },
//   os: { name: 'mac', version: 'unknown', arch: '64bit' }
// }

Session

This object represents a WebDriver session.

session.close()

Close the session.
See also
Returns
Promise<void>
Examples
 

import { newSession } from 'w3c-webdriver';

let session;

(async () => {
  try {
    session = await newSession('http://localhost:4444', {
      desiredCapabilities: {
        browserName: 'Chrome'
      }
    });
  } catch (err) {
    console.log(err.stack);
  } finally {
    session.close();
  }
})();

session.getTimeout()

Gets timeout durations associated with the current session.
See also
Returns
Promise<Timeout>
Examples
 

const timeout = await session.getTimeout();
// timeout = {
//   script: 30000,
//   pageLoad: 60000,
//   implicit: 40000
// }

session.setTimeout(timeout)

Configure the amount of time that a particular type of operation can execute for before they are aborted and a |Timeout| error is returned to the client.
See also
Parameters
Returns
Promise<void>
Examples
 

await session.setTimeout({
  script: 30000,
  pageLoad: 60000,
  implicit: 40000
});

session.navigateTo(targetUrl)

Navigate to a new URL.
See also
Parameters
  • targetUrl: string
Returns
Promise<void>
Examples
 

await session.navigateTo('http://localhost:8080');

session.getCurrentUrl()

Get current page URL
See also
Returns
Promise<string>
Examples
 

const currentUrl = await session.getCurrentUrl();
// currentUrl = 'http://localhost:8080'

session.back()

Navigate to previous url from history
See also
Returns
Promise<void>
Examples
 

await session.back();

session.forward()

Navigate forward to next url from history
See also
Returns
Promise<void>
Examples
 

await session.forward();

session.refresh()

Refresh the current page
See also
Returns
Promise<void>
Examples
 

await session.refresh();

session.getTitle()

Get the current page title.
See also
Returns
Promise<string>
Examples
 

const title = await session.getTitle();
// title = 'web page title'

session.getWindowHandle()

Get handle of current window
See also
Returns
Promise<string>
Examples
 

const handle = await session.getWindowHandle();
// handle = 'CDwindow-7321145136535301DE771CCBD9555CEA'

session.closeWindow()

Close the current window.
See also
Returns
Promise<void>
Examples
 

await session.closeWindow();

session.switchToWindow(handle)

Change focus to another window. The window to change focus to may be specified by it's server assigned window handle.
See also
Parameters
  • handle: string
Returns
Promise<void>
Examples
 

await session.switchToWindow('CDwindow-7321145136535301DE771CCBD9555CEA');

session.getWindowHandles()

Get all window handles
See also
Returns
Promise<string[]>
Examples
 

const handles = await session.getWindowHandles();
// handles = ['CDwindow-7321145136535301DE771CCBD9555CEA']

session.switchToFrame(target)

Change focus to another frame on the page
See also
Parameters
Returns
Promise<void>
Examples
 

const iframe = await session.findElement('css selector', 'iframe');
await session.switchToFrame(iframe);
 

await session.switchToFrame(null);

session.switchToParentFrame()

Change focus to parent frame on the page
See also
Returns
Promise<void>
Examples
 

await session.switchToParentFrame();

session.getWindowRect()

Get the size and position on the screen of the operating system window
See also
Returns
Promise<WindowRect>
Examples
 

await session.getWindowRect();

session.setWindowRect(windowRect)

Set the size and position on the screen of the operating system window
See also
Parameters
Returns
Promise<void>
Examples
 

await session.setWindowRect();

session.maximizeWindow()

Maximizes the current window
See also
Returns
Promise<void>
Examples
 

await session.maximizeWindow();

session.minimizeWindow()

Minimizes the current window
See also
Returns
Promise<void>
Examples
 

await session.minimizeWindow();

session.fullScreenWindow()

This command increases Current window to Full-Screen
See also
Returns
Promise<void>
Examples
 

await session.fullScreenWindow();

session.findElement(strategy, selector)

Search for an element on the page, starting from the document root.
See also
Parameters
Returns
Promise<Element>
Examples
 

const element = await session.findElement('css selector', 'h2');
// element = <webdriver element>

session.findElements(strategy, selector)

Search for multiple elements on the page, starting from the document root. The located elements will be returned as a WebElement JSON objects. The table below lists the locator strategies that each server should support. Elements should be returned in the order located in the DOM.
See also
Parameters
Returns
Promise<Element[]>
Examples
 

const elements = await session.findElements('css selector', 'h2');
// elements = [<webdriver element>]

session.getActiveElement()

Get the element on the page that currently has focus.
See also
Returns
Promise<Element>
Examples
 

const element = await session.getActiveElement();
// element = <webdriver element>

session.getPageSource()

Returns a string serialization of the DOM of the current browsing context active document.
See also
Returns
Promise<string>
Examples
 

const source = await session.getPageSource();
// source = '<!DOCTYPE html><head><title>...'

session.executeScript(script, args)

Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. The executed script is assumed to be synchronous and the result of evaluating the script is returned to the client.
See also
Parameters
  • script: string
  • args: any[]
Returns
Promise<typeParameter>
Examples
 

const script = `
  const [from] = arguments;
  return `Hello from ${from}!`;
`;
const message = await session.executeScript(script, ['WebDriver']);
// message = 'Hello from WebDriver!'

session.executeAsyncScript(script, args)

causes JavaScript to execute as an anonymous function. Unlike the Execute Script command, the result of the function is ignored. Instead an additional argument is provided as the final argument to the function. This is a function that, when called, returns its first argument as the response.
See also
Parameters
  • script: string
  • args: any[]
Returns
Promise<typeParameter>
Examples
 

const script = `
  const [a, b, callback] = arguments;
  setTimeout(() => callback(a * b), 1000);
`;
const message = await session.executeAsyncScript(script, [5, 3]);
// message = 15

session.getAllCookies()

Returns all cookies associated with the address of the current browsing context’s active document.
See also
Returns
Promise<Cookie[]>
Examples
 

const cookies = await session.getAllCookies();
// cookies = [
//   {
//     name: 'cookie name',
//     value: 'cookie value',
//     path: '/',
//     domain: 'localhost',
//     secure: false,
//     httpOnly: true
//   }
// ]
Returns cookie based on the cookie name
See also
Parameters
  • propertyName: string
Returns
Promise<Cookie>
Examples
 

const cookie = await session.getNamedCookie('cookieName');

Adds a single cookie to the cookie store associated with the active document’s address.
See also
Parameters
Returns
Promise<void>
Examples
 

await session.addCookie({ name: 'test cookie', value: 'test value' });
Delete a cookie based on its name
See also
Parameters
  • propertyName: string
Returns
Promise<void>
Examples
 

await session.deleteCookie('cookieName');

session.deleteAllCookies()

Delete all cookies associated with the address of the current browsing context’s active document.
See also
Returns
Promise<void>
Examples
 

await session.deleteAllCookies();

session.performActions(actionSequences)

Sends virtualised device input to the web browser like keyboard or pointer events in a series of actions.
See also
Parameters
Returns
Promise<void>
Examples
 

await session.performActions([
  {
    type: 'none',
    id: 'none_id',
    actions: [{ type: 'pause', duration: 0 }]
  },
  {
    type: 'pointer',
    id: 'click on b field',
    actions: [
      { type: 'pause', duration: 0 },
      { type: 'pointerMove', x: 118, y: 121 },
      { type: 'pointerDown', button: 0 },
      { type: 'pointerUp', button: 0 }
    ]
  }
]);
 

await session.performActions([
  {
    type: 'key',
    id: 'type in 15',
    actions: [
      { type: 'pause', duration: 100 },
      { type: 'keyDown', value: '1' },
      { type: 'keyUp', value: '1' },
      { type: 'keyDown', value: '5' },
      { type: 'keyUp', value: '5' }
    ]
  }
]);
 

await session.performActions([
  {
    type: 'pointer',
    id: 'click on add button',
    actions: [
      { type: 'pointerMove', x: 1, y: 1, origin: await session.findElement('css selector', '#add') },
      { type: 'pointerDown', button: 0 },
      { type: 'pointerUp', button: 0 }
    ],
    parameters: {
      pointerType: 'mouse'
    }
  }
]);
 

await session.performActions([
  {
    type: 'key',
    id: 'key id',
    actions: [
      { type: 'keyDown', value: 'a' },
      { type: 'keyUp', value: 'a' },
      { type: 'keyDown', value: 'b' },
      { type: 'keyUp', value: 'b' },
      { type: 'keyDown', value: Key.LEFT },
      { type: 'keyUp', value: Key.LEFT },
      { type: 'keyDown', value: Key.DELETE },
      { type: 'keyUp', value: Key.DELETE }
    ]
  }
]);

session.releaseActions()

Release all the keys and pointer buttons that are currently depressed
See also
Returns
Promise<void>
Examples
 

await session.performActions([
  {
    type: 'key',
    id: 'key id',
    actions: [{ type: 'keyDown', value: 'a' }]
  }
]);
await session.releaseActions();
// Now 'a' key was pressed

session.dismissAlert()

Dismiss the alert in current page
See also
Returns
Promise<void>
Examples
 

await session.dismissAlert();

session.acceptAlert()

Accept the alert in current page
See also
Returns
Promise<void>
Examples
 

await session.acceptAlert();

session.getAlertText()

Returns the text from an alert
See also
Returns
Promise<string>
Examples
 

const alertText = await session.getAlertText();

session.sendAlertText(propertyName)

Sets the text field of a prompt to the given value.
See also
Parameters
  • propertyName: string
Returns
Promise<void>
Examples
 

await session.sendAlertText('Test');

session.takeScreenshot()

Takes a screenshot of the top-level browsing context’s viewport.
See also
Returns
Promise<Buffer>
Examples
 

const screenshot = await session.takeScreenshot();
// screenshot = Buffer containing PNG

Timeout

WebDriver Timeout configuration object
Properties

Element

This object represents a WebDriver element.

element.getWebElement()

Get WebElement object of current instance
Returns
WebElement

element.findElement(strategy, selector)

Search for an element on the page, starting from the referenced web element.
See also
Parameters
Returns
Promise<Element>
Examples
 

const parent = await session.findElement('css selector', '#parent');
const child = await child.findElement('css selector', '#child');
// child = <webdriver element>

element.findElements(strategy, selector)

Search for multiple elements on the page, starting from the referenced web element. The located elements will be returned as a WebElement JSON objects. The table below lists the locator strategies that each server should support. Elements should be returned in the order located in the DOM.
See also
Parameters
Returns
Promise<Element[]>
Examples
 

const parent = await session.findElement('css selector', '#parent');
const children = await child.findElements('css selector', '#child');
// elements = [<webdriver element>]

element.isSelected()

Determines if the referenced element is selected or not. This operation only makes sense on input elements of the Checkbox- and Radio Button states, or on option elements.
See also
Returns
Promise<boolean>
Examples
 

const checkbox = await session.findElement('css selector', '#checkbox');
const selected = await checkbox.isSelected();
// selected = true

element.getAttribute(propertyName)

Returns the attribute of the referenced web element.
See also
Parameters
  • propertyName: string
Returns
Promise<string>
Examples
 

const button = await session.findElement('css selector', '#red-button');
const backgroundColor = await button.getAttribute('css');

element.getProperty(propertyName)

Returns the property of the referenced web element.
See also
Parameters
  • propertyName: string
Returns
Promise<string>
Examples
 

const button = await session.findElement('css selector', '#red-button');
const backgroundColor = await button.getProperty('class');

element.getCssValue(propertyName)

Returns the computed value of the given CSS property for the element.
See also
Parameters
  • propertyName: string
Returns
Promise<string>
Examples
 

const button = await session.findElement('css selector', '#red-button');
const backgroundColor = await button.getCssValue('background-color');
// backgroundColor = 'rgba(255, 0, 0, 1)'

element.getText()

Returns the visible text for the element.
See also
Returns
Promise<string>
Examples
 

const result = await session.findElement('css selector', '#result');
const text = await result.getText();

element.getTagName()

Returns the tagName of a Element
See also
Returns
Promise<string>
Examples
 

const button = await session.findElement('css selector', '#red-button');
const backgroundColor = await button.getTagName();

element.getRect()

Returns the dimensions and coordinates of the referenced element
See also
Returns
Promise<ElementRect>
Examples
 

const button = await session.findElement('css selector', '#red-button');
const rect = await button.getRect();
// rect = { x: 10, y: 100, width: 300, height: 50 }

element.isEnabled()

Determines if the referenced element is enabled or not.
See also
Returns
Promise<boolean>
Examples
 

const inputField = await session.findElement('css selector', '#disabled');
const isElementEnabled = await inputField.isEnabled();

element.click()

Click on an element.
See also
Returns
Promise<void>
Examples
 

const submitButton = await session.findElement('css selector', 'button[type="submit"]');
await submitButton.click();

element.clear()

Clear content of an element.
See also
Returns
Promise<void>
Examples
 

const fieldA = await session.findElement('css selector', '#a');
await submitButton.clear();

element.sendKeys(text)

Send a sequence of key strokes to an element.
See also
Parameters
  • text: string
Returns
Promise<void>
Examples
 

const input = await session.findElement('css selector', '[name="first-name"]');
await input.sendKeys('Hello World');

element.takeScreenshot()

Takes a screenshot of the visible region encompassed by the bounding rectangle of an element
See also
Returns
Promise<Buffer>
Examples
 

const screenshot = await session.takeScreenshot();
// screenshot = Buffer containing PNG

LocatorStrategy

Strategy for searching element on the page
Possible values

ElementRect

An object defining the Element Rect.
Properties

WindowRect

An object defining the Window Rect.
Properties
An object defining the cookie.
Properties

ActionSequence

Possible values

NullActionSequence

Properties

NullAction

Possible values

PauseAction

Properties

KeyActionSequence

Properties

KeyAction

Possible values

KeyDownAction

Properties

Key

Possible values

KeyUpAction

Properties

PointerActionSequence

Properties

PointerAction

Possible values

PointerMoveAction

Properties

PointerUpAction

Properties

PointerDownAction

Properties

PointerParameters

Properties

Capabilities

Properties

BrowserCapability

Properties

BrowserStackOptions

Properties

ChromeOptions

Properties

FirefoxOptions

Properties

InternetExplorerOptions

Properties

Status

WebDriver status object
Properties

StatusOfWebDriver

Properties

StatusOfOS

Properties
W3C WebDriver
v1.0.0