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: objectcapabilities: CapabilitiesWebDriver capabilitiesdesiredCapabilities?: objectLegacy WebDriver capabilities. Can be used to enable the new W3C dialectheaders?: HeaderInitSession creation request headers. Can be used for authorization. See exampleurl: stringWebDriver 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
timeout: Timeout
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 URLSee also
Returns
Promise<string> Examples
const currentUrl = await session.getCurrentUrl();
// currentUrl = 'http://localhost:8080'
session.back()
Navigate to previous url from historySee also
Returns
Promise<void> Examples
await session.back();
session.forward()
Navigate forward to next url from historySee also
Returns
Promise<void> Examples
await session.forward();
session.refresh()
Refresh the current pageSee 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 windowSee 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 handlesSee also
Returns
Promise<string[]> Examples
const handles = await session.getWindowHandles();
// handles = ['CDwindow-7321145136535301DE771CCBD9555CEA']
session.switchToFrame(target)
Change focus to another frame on the pageSee also
Parameters
target: null | number | Element
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 pageSee also
Returns
Promise<void> Examples
await session.switchToParentFrame();
session.getWindowRect()
Get the size and position on the screen of the operating system windowSee also
Returns
Promise<WindowRect> Examples
await session.getWindowRect();
session.setWindowRect(windowRect)
Set the size and position on the screen of the operating system windowSee also
Parameters
windowRect: WindowRect
Returns
Promise<void> Examples
await session.setWindowRect();
session.maximizeWindow()
Maximizes the current windowSee also
Returns
Promise<void> Examples
await session.maximizeWindow();
session.minimizeWindow()
Minimizes the current windowSee also
Returns
Promise<void> Examples
await session.minimizeWindow();
session.fullScreenWindow()
This command increases Current window to Full-ScreenSee 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
strategy: LocatorStrategyselector: string
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
strategy: LocatorStrategyselector: string
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: stringargs: 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: stringargs: 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
// }
// ]
session.getNamedCookie(propertyName)
Returns cookie based on the cookie nameSee also
Parameters
propertyName: string
Returns
Promise<Cookie> Examples
const cookie = await session.getNamedCookie('cookieName');
session.addCookie(cookie)
Adds a single cookie to the cookie store associated with the active document’s address.See also
Parameters
cookie: Cookie
Returns
Promise<void> Examples
await session.addCookie({ name: 'test cookie', value: 'test value' });
session.deleteCookie(propertyName)
Delete a cookie based on its nameSee 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
actionSequences: ActionSequence[]
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 depressedSee 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 pageSee also
Returns
Promise<void> Examples
await session.dismissAlert();
session.acceptAlert()
Accept the alert in current pageSee also
Returns
Promise<void> Examples
await session.acceptAlert();
session.getAlertText()
Returns the text from an alertSee 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 objectProperties
implicit?: numberSession implicit wait timeout in milliseconds. Gives the timeout of when to abort locating an element.pageLoad?: numberSession page load timeout in milliseconds. Provides the timeout limit used to interrupt navigation of the browsing context.script?: numberSession script timeout in milliseconds. Determines when to interrupt a script that is being evaluated.
Element
This object represents a WebDriver element.element.getWebElement()
Get WebElement object of current instanceReturns
WebElement element.findElement(strategy, selector)
Search for an element on the page, starting from the referenced web element.See also
Parameters
strategy: LocatorStrategyselector: string
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
strategy: LocatorStrategyselector: string
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 ElementSee 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 elementSee 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 elementSee also
Returns
Promise<Buffer> Examples
const screenshot = await session.takeScreenshot();
// screenshot = Buffer containing PNG
LocatorStrategy
Strategy for searching element on the pagePossible values
'css selector''link text''partial link text''tag name''xpath'
ElementRect
An object defining the Element Rect.Properties
height: numberWidth of the web element’s bounding rectangle in CSS pixelswidth: numberHeight of the element’s bounding rectangle in CSS pixelsx: numberX axis position of the top-left corner of the element relative to the current browsing context’s document element in CSS pixelsy: numberY axis position of the top-left corner of the element relative to the current browsing context’s document element in CSS pixels
WindowRect
An object defining the Window Rect.Properties
height: numberThe outerWidth attribute must return the height of the client window. If there is no client window this attribute must return zerowidth: numberThe outerWidth attribute must return the width of the client window. If there is no client window this attribute must return zerox: numberThe screenX and screenLeft attributes must return the x-coordinate, relative to the origin of the Web-exposed screen area, of the left of the client window as number of CSS pixelsy: numberThe screenY and screenTop attributes must return the y-coordinate, relative to the origin of the screen of the Web-exposed screen area, of the top of the client window as number of CSS pixels
Cookie
An object defining the cookie.Properties
domain?: stringThe domain the cookie is visible to. Defaults to the current browsing context’s document’s URL domain if omitted when adding a cookie.expiry?: numberWhen the cookie expires, specified in seconds since Unix Epoch. Defaults to 20 years into the future if omitted when adding a cookie.httpOnly?: booleanWhether the cookie is an HTTP only cookie. Defaults to false if omitted when adding a cookie.name: stringThe name of the cookie.path?: stringThe cookie path. Defaults to "/" if omitted when adding a cookie.secure?: booleanWhether the cookie is a secure cookie. Defaults to false if omitted when adding a cookie.value: stringThe cookie value.
ActionSequence
Possible values
NullActionSequence
Properties
actions: NullAction[]id: stringtype: 'none'
NullAction
Possible values
PauseAction
Properties
duration: numbertype: 'pause'
KeyActionSequence
Properties
actions: KeyAction[]id: stringtype: 'key'
KeyAction
Possible values
KeyDownAction
Properties
type: 'keyDown'value: Key | string
Key
Possible values
- ADD
- ALT
- BACKSPACE
- CANCEL
- CLEAR
- CONTROL
- DECIMAL
- DELETE
- DIVIDE
- DOWN
- END
- ENTER
- EQUALS
- ESCAPE
- F1
- F10
- F11
- F12
- F2
- F3
- F4
- F5
- F6
- F7
- F8
- F9
- HELP
- HOME
- INSERT
- LEFT
- META
- MULTIPLY
- NULL
- NUMPAD0
- NUMPAD1
- NUMPAD2
- NUMPAD3
- NUMPAD4
- NUMPAD5
- NUMPAD6
- NUMPAD7
- NUMPAD8
- NUMPAD9
- PAGE_DOWN
- PAGE_UP
- PAUSE
- RETURN
- RIGHT
- R_ALT
- R_ARROWDOWN
- R_ARROWLEFT
- R_ARROWRIGHT
- R_ARROWUP
- R_CONTROL
- R_DELETE
- R_END
- R_HOME
- R_INSERT
- R_META
- R_PAGEDOWN
- R_PAGEUP
- R_SHIFT
- SEMICOLON
- SEPARATOR
- SHIFT
- SPACE
- SUBTRACT
- TAB
- UP
- ZENKAKUHANKAKU
KeyUpAction
Properties
type: 'keyUp'value: Key | string
PointerActionSequence
Properties
actions: PointerAction[]id: stringparameters?: PointerParameterstype: 'pointer'
PointerAction
Possible values
PointerMoveAction
Properties
duration?: numberorigin?: 'viewport' | 'pointer' | Elementtype: 'pointerMove'x: numbery: number
PointerUpAction
Properties
button: numbertype: 'pointerUp'
PointerDownAction
Properties
button: numbertype: 'pointerDown'
PointerParameters
Properties
pointerType: 'mouse' | 'pen' | 'touch'
Capabilities
Properties
alwaysMatch?: BrowserCapabilityfirstMatch?: BrowserCapability[]
BrowserCapability
Properties
browserName: stringbstack:options?: BrowserStackOptionsgoog:chromeOptions?: ChromeOptionsmoz:firefoxOptions?: FirefoxOptionsse:ieOptions?: InternetExplorerOptions
BrowserStackOptions
Properties
buildName?: stringdebug?: booleanlocal?: booleannetworkLogs?: booleanos?: stringosVersion?: stringprojectName?: stringsafari?: objectsessionName?: string
ChromeOptions
Properties
args?: string[]binary?: stringw3c?: boolean
FirefoxOptions
Properties
args?: string[]log?: object
InternetExplorerOptions
Properties
ie.ensureCleanSession: booleanignoreProtectedModeSettings: booleanignoreZoomSetting: boolean
Status
WebDriver status objectProperties
build: StatusOfWebDrivermessage: stringos: StatusOfOSready: boolean
StatusOfWebDriver
Properties
version: stringVersion of driver
StatusOfOS
Properties
arch: stringOperating system architecturename: stringName of operating systemversion: stringVersion of operating system