@types/selenium-webdriver
- Version 4.1.27
- Published
- 267 kB
- 2 dependencies
- MIT license
Install
npm i @types/selenium-webdriver
yarn add @types/selenium-webdriver
pnpm add @types/selenium-webdriver
Overview
TypeScript definitions for selenium-webdriver
Index
Variables
Functions
Classes
Builder
- build()
- disableEnvironmentOverrides()
- forBrowser()
- getCapabilities()
- getChromeOptions()
- getFirefoxOptions()
- getHttpAgent()
- getSafariOptions()
- getServerUrl()
- getWebDriverProxy()
- setAlertBehavior()
- setChromeOptions()
- setChromeService()
- setEdgeOptions()
- setEdgeService()
- setFirefoxOptions()
- setFirefoxService()
- setIeOptions()
- setIeService()
- setLoggingPrefs()
- setProxy()
- setSafariOptions()
- usingHttpAgent()
- usingServer()
- usingWebDriverProxy()
- withCapabilities()
Capabilities
- [Symbols.serialize]()
- chrome()
- delete()
- edge()
- firefox()
- get()
- getAcceptInsecureCerts()
- getAlertBehavior()
- getBrowserName()
- getBrowserVersion()
- getPageLoadStrategy()
- getPlatform()
- getProxy()
- has()
- ie()
- keys()
- merge()
- safari()
- set()
- setAcceptInsecureCerts()
- setAlertBehavior()
- setBrowserName()
- setBrowserVersion()
- setLoggingPrefs()
- setPageLoadStrategy()
- setPlatform()
- setProxy()
WebDriver
- actions()
- close()
- createCDPConnection()
- createSession()
- execute()
- executeAsyncScript()
- executeScript()
- findElement()
- findElementInternal_()
- findElements()
- findElementsInternal_()
- get()
- getAllWindowHandles()
- getCapabilities()
- getCurrentUrl()
- getExecutor()
- getPageSource()
- getSession()
- getTitle()
- getWindowHandle()
- getWsUrl()
- logMutationEvents()
- manage()
- navigate()
- normalize_()
- onIntercept()
- onLogEvent()
- onLogException()
- printPage()
- quit()
- register()
- setFileDetector()
- sleep()
- switchTo()
- takeScreenshot()
- wait()
Interfaces
Enums
Type Aliases
Namespaces
error
- checkLegacyResponse()
- checkResponse()
- ElementClickInterceptedError
- ElementNotInteractableError
- ElementNotSelectableError
- encodeError()
- ErrorCode
- ErrorCodeType
- ErrorData
- IError
- InsecureCertificateError
- InvalidArgumentError
- InvalidCookieDomainError
- InvalidCoordinatesError
- InvalidElementStateError
- InvalidSelectorError
- JavascriptError
- MaybeLegacyResponse
- MoveTargetOutOfBoundsError
- NoSuchAlertError
- NoSuchCookieError
- NoSuchElementError
- NoSuchFrameError
- NoSuchSessionError
- NoSuchWindowError
- Response
- ScriptTimeoutError
- SessionNotCreatedError
- StaleElementReferenceError
- throwDecodedError()
- TimeoutError
- UnableToCaptureScreenError
- UnableToSetCookieError
- UnexpectedAlertOpenError
- UnknownCommandError
- UnknownMethodError
- UnsupportedOperationError
- WebDriverError
until
- ableToSwitchToFrame()
- alertIsPresent()
- elementIsDisabled()
- elementIsEnabled()
- elementIsNotSelected()
- elementIsNotVisible()
- elementIsSelected()
- elementIsVisible()
- elementLocated()
- elementsLocated()
- elementTextContains()
- elementTextIs()
- elementTextMatches()
- stalenessOf()
- titleContains()
- titleIs()
- titleMatches()
- urlContains()
- urlIs()
- urlMatches()
Variables
variable Browser
const Browser: IBrowser;
Instace of
variable Capability
const Capability: ICapability;
The standard WebDriver capability keys.
variable Key
const Key: IKey;
Representations of pressable keys that aren't text. These are stored in the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to http://www.google.com.au/search?&q=unicode+pua&btnG=Search
Functions
function checkedLocator
checkedLocator: (locator: Locator) => By | Function;
Checks if a value is a valid locator.
Parameter locator
The value to check. {!(By|Function)} The valid locator.
Throws
{TypeError} If the given value does not define a valid locator strategy.
function escapeCss
escapeCss: (css: string) => string;
Escapes a CSS string.
Parameter css
the string to escape. {string} the escaped string.
Throws
{TypeError} if the input value is not a string.
Throws
{InvalidCharacterError} if the string contains an invalid character.
See Also
https://drafts.csswg.org/cssom/#serialize-an-identifier
function locateWith
locateWith: (by: Locator) => RelativeBy;
Start searching for relative objects using search criteria with By.
Parameter by
A By map that shows how to find the initial element
Returns
{RelativeBy} RelativeBy instance
function withTagName
withTagName: (tagName: By) => RelativeBy;
Start Searching for relative objects using the value returned from
By.tagName()
.Note: this method will likely be removed in the future please use
locateWith
.Parameter tagName
The value returned from calling By.tagName()
Returns
{RelativeBy} RelativeBy instance
Classes
class Actions
class Actions {}
Class for defining sequences of complex user interactions. Each sequence will not be executed until is called.
Example:
new Actions(driver). keyDown(Key.SHIFT). click(element1). click(element2). dragAndDrop(element3, element4). keyUp(Key.SHIFT). perform();
constructor
constructor( executor: Executor, options?: | { async: boolean; bridge: boolean } | { async: boolean } | { bridge: boolean });
method clear
clear: () => Promise<void>;
Executes this action sequence. {!Promise} A promise that will be resolved once this sequence has completed.
method click
click: (element?: WebElement) => Actions;
Short-hand for performing a simple left-click (down/up) with the mouse.
Parameter element
If specified, the mouse will first be moved to the center of the element before performing the click. {!Actions} a self reference.
method contextClick
contextClick: (element?: WebElement) => Actions;
Short-hand for performing a simple right-click (down/up) with the mouse.
Parameter element
If specified, the mouse will first be moved to the center of the element before performing the click. {!Actions} a self reference.
method doubleClick
doubleClick: (element?: WebElement) => Actions;
Short-hand for performing a double left-click with the mouse.
Parameter element
If specified, the mouse will first be moved to the center of the element before performing the click. {!Actions} a self reference.
method dragAndDrop
dragAndDrop: ( from: WebElement, to?: | WebElement | { x?: number | string | undefined; y?: number | string | undefined } | null) => Actions;
Convenience function for performing a 'drag and drop' manuever. The target element may be moved to the location of another element, or by an offset (in pixels).
method keyboard
keyboard: () => Keyboard;
method keyDown
keyDown: (key: string) => Actions;
Performs a modifier key press. The modifier key is not released until or is called. The key press will be targetted at the currently focused element.
Parameter key
The modifier key to push. Must be one of {ALT, CONTROL, SHIFT, COMMAND, META}. {!Actions} A self reference.
Throws
{Error} If the key is not a valid modifier key.
method keyUp
keyUp: (key: string) => Actions;
Performs a modifier key release. The release is targetted at the currently focused element.
Parameter key
The modifier key to release. Must be one of {ALT, CONTROL, SHIFT, COMMAND, META}. {!Actions} A self reference.
Throws
{Error} If the key is not a valid modifier key.
method mouse
mouse: () => Pointer;
method move
move: (direction: IDirection) => Actions;
Inserts an action for moving the mouse
x
andy
pixels relative to the specifiedorigin
. Theorigin
may be defined as the mouse's , the , or the center of a specific .You may adjust how long the remote end should take, in milliseconds, to perform the move using the
duration
parameter (defaults to 100 ms). The number of incremental move events generated over this duration is an implementation detail for the remote end.Defaults to moving the mouse to the top-left corner of the viewport over 100ms.
method pause
pause: (duration?: number | Device, ...devices: Device[]) => Actions;
method perform
perform: () => Promise<void>;
Executes this action sequence. {!Promise} A promise that will be resolved once this sequence has completed.
method press
press: (button?: Button) => Actions;
Inserts an action to press a mouse button at the mouse's current location. Defaults to
LEFT
.
method release
release: (button?: Button) => Actions;
Inserts an action to release a mouse button at the mouse's current location. Defaults to
LEFT
.
method sendKeys
sendKeys: (...var_args: Array<string | Promise<string>>) => Actions;
Simulates typing multiple keys. Each modifier key encountered in the sequence will not be released until it is encountered again. All key events will be targeted at the currently focused element.
Parameter var_args
The keys to type. {!Actions} A self reference.
Throws
{Error} If the key is not a valid modifier key.
class Alert
class Alert {}
Represents a modal dialog such as , , or . Provides functions to retrieve the message displayed with the alert, accept or dismiss the alert, and set the response text (in the case of ).
constructor
constructor(driver: WebDriver, text: string);
Parameter driver
The driver controlling the browser this alert is attached to.
Parameter text
The message text displayed with this alert.
method accept
accept: () => Promise<void>;
Accepts this alert.
{!Promise} A promise that will be resolved when this command has completed.
method dismiss
dismiss: () => Promise<void>;
Dismisses this alert.
{!Promise} A promise that will be resolved when this command has completed.
method getText
getText: () => Promise<string>;
Retrieves the message text displayed with this alert. For instance, if the alert were opened with alert("hello"), then this would return "hello".
{!Promise} A promise that will be resolved to the text displayed with this alert.
method sendKeys
sendKeys: (text: string) => Promise<void>;
Sets the response text on this alert. This command will return an error if the underlying alert does not support response text (e.g. window.alert and window.confirm).
Parameter text
The text to set. {!Promise} A promise that will be resolved when this command has completed.
class Builder
class Builder {}
Creates new instances. The environment variables listed below may be used to override a builder's configuration, allowing quick runtime changes.
- : defines the target browser in the form .
- : defines the remote URL for all builder instances. This environment variable should be set to a fully qualified URL for a WebDriver server (e.g. http://localhost:4444/wd/hub). This option always takes precedence over .
- : defines the path to the standalone Selenium server jar to use. The server will be started the first time a WebDriver instance and be killed when the process exits.
Suppose you had mytest.js that created WebDriver with
var driver = new Builder() .forBrowser('chrome') .build();
This test could be made to use Firefox on the local machine by running with
SELENIUM_BROWSER=firefox node mytest.js
. Rather than change the code to target Google Chrome on a remote machine, you can simply set theSELENIUM_BROWSER
andSELENIUM_REMOTE_URL
environment variables:SELENIUM_BROWSER=chrome:36:LINUX \ SELENIUM_REMOTE_URL=http://www.example.com:4444/wd/hub \ node mytest.js
You could also use a local copy of the standalone Selenium server:
SELENIUM_BROWSER=chrome:36:LINUX \ SELENIUM_SERVER_JAR=/path/to/selenium-server-standalone.jar \ node mytest.js
constructor
constructor();
method build
build: () => ThenableWebDriver;
Creates a new WebDriver client based on this builder's current configuration.
This method will return a instance, allowing users to issue commands directly without calling
then()
. The returned thenable wraps a promise that will resolve to a concrete instance. The promise will be rejected if the remote end fails to create a new session.{!ThenableWebDriver} A new WebDriver instance.
Throws
{Error} If the current configuration is invalid.
method disableEnvironmentOverrides
disableEnvironmentOverrides: () => Builder;
Configures this builder to ignore any environment variable overrides and to only use the configuration specified through this instance's API.
{!Builder} A self reference.
method forBrowser
forBrowser: ( name: string, opt_version?: string, opt_platform?: string) => Builder;
Configures the target browser for clients created by this instance. Any calls to after this function will overwrite these settings.
You may also define the target browser using the environment variable. If set, this environment variable should be of the form .
Parameter name
The name of the target browser; common defaults are available on the Browser enum.
Parameter opt_version
A desired version; may be omitted if any version should be used.
Parameter opt_platform
The desired platform; may be omitted if any version may be used. {!Builder} A self reference.
method getCapabilities
getCapabilities: () => Capabilities;
Returns the base set of capabilities this instance is currently configured to use. {!Capabilities} The current capabilities for this builder.
method getChromeOptions
getChromeOptions: () => chrome.Options;
{chrome.Options} the Chrome specific options currently configured for this builder.
method getFirefoxOptions
getFirefoxOptions: () => firefox.Options;
{firefox.Options} the Firefox specific options currently configured for this instance.
method getHttpAgent
getHttpAgent: () => any | null;
{http.Agent} The http agent used for each request
method getSafariOptions
getSafariOptions: () => safari.Options;
{safari.Options} the Safari specific options currently configured for this instance.
method getServerUrl
getServerUrl: () => string;
{string} The URL of the WebDriver server this instance is configured to use.
method getWebDriverProxy
getWebDriverProxy: () => string | null;
{?string} The URL of the proxy server to use for the WebDriver's HTTP connections, or
null
if not set.
method setAlertBehavior
setAlertBehavior: (behavior?: string) => Builder;
Sets the default action to take with an unexpected alert before returning an error.
Parameter beahvior
The desired behavior; should be 'accept', 'dismiss', or 'ignore'. Defaults to 'dismiss'. {!Builder} A self reference.
method setChromeOptions
setChromeOptions: (options: chrome.Options) => Builder;
Sets Chrome-specific options for drivers created by this builder. Any logging or proxy settings defined on the given options will take precedence over those set through and , respectively.
Parameter options
The ChromeDriver options to use. {!Builder} A self reference.
method setChromeService
setChromeService: (service: chrome.ServiceBuilder) => Builder;
Sets the service builder to use for managing the chromedriver child process when creating new Chrome sessions.
Parameter service
the service to use. {!Builder} A self reference.
method setEdgeOptions
setEdgeOptions: (options: edge.Options) => Builder;
Set specific to Microsoft's Edge browser for drivers created by this builder. Any proxy settings defined on the given options will take precedence over those set through .
Parameter options
The MicrosoftEdgeDriver options to use. {!Builder} A self reference.
method setEdgeService
setEdgeService: (service: edge.ServiceBuilder) => Builder;
Sets the edge.ServiceBuilder to use to manage the MicrosoftEdgeDriver child process when creating sessions locally.
Parameter service
the service to use. {!Builder} a self reference.
method setFirefoxOptions
setFirefoxOptions: (options: firefox.Options) => Builder;
Sets Firefox-specific options for drivers created by this builder. Any logging or proxy settings defined on the given options will take precedence over those set through and , respectively.
Parameter options
The FirefoxDriver options to use. {!Builder} A self reference.
method setFirefoxService
setFirefoxService: (service: firefox.ServiceBuilder) => Builder;
Sets the firefox.ServiceBuilder to use to manage the geckodriver child process when creating Firefox sessions locally.
Parameter service
the service to use. {!Builder} a self reference.
method setIeOptions
setIeOptions: (options: ie.Options) => Builder;
Set Internet Explorer specific for drivers created by this builder. Any proxy settings defined on the given options will take precedence over those set through .
Parameter options
The IEDriver options to use. {!Builder} A self reference.
method setIeService
setIeService: (service: ie.ServiceBuilder) => Builder;
Sets the ie.ServiceBuilder to use to manage the geckodriver child process when creating IE sessions locally.
Parameter service
the service to use. {!Builder} a self reference.
method setLoggingPrefs
setLoggingPrefs: (prefs: logging.Preferences | {}) => Builder;
Sets the logging preferences for the created session. Preferences may be changed by repeated calls, or by calling .
Parameter prefs
The desired logging preferences. {!Builder} A self reference.
method setProxy
setProxy: (config: ProxyConfig) => Builder;
Sets the proxy configuration to use for WebDriver clients created by this builder. Any calls to after this function will overwrite these settings.
Parameter config
The configuration to use. {!Builder} A self reference.
method setSafariOptions
setSafariOptions: (options: safari.Options) => Builder;
Sets Safari specific for drivers created by this builder. Any logging settings defined on the given options will take precedence over those set through .
Parameter options
The Safari options to use. {!Builder} A self reference.
method usingHttpAgent
usingHttpAgent: (agent: any) => Builder;
Sets the http agent to use for each request. If this method is not called, the Builder will use http.globalAgent by default.
Parameter agent
The agent to use for each request. {!Builder} A self reference.
method usingServer
usingServer: (url: string) => Builder;
Sets the URL of a remote WebDriver server to use. Once a remote URL has been specified, the builder direct all new clients to that server. If this method is never called, the Builder will attempt to create all clients locally.
As an alternative to this method, you may also set the environment variable.
Parameter url
The URL of a remote server to use. {!Builder} A self reference.
method usingWebDriverProxy
usingWebDriverProxy: (proxy: string) => Builder;
Sets the URL of the proxy to use for the WebDriver's HTTP connections. If this method is never called, the Builder will create a connection without a proxy.
Parameter proxy
The URL of a proxy to use. {!Builder} A self reference.
method withCapabilities
withCapabilities: (capabilities: {} | Capabilities) => Builder;
Sets the desired capabilities when requesting a new session. This will overwrite any previously set capabilities.
Parameter capabilities
The desired capabilities for a new session. {!Builder} A self reference.
class By
class By {}
Typings for lib/by.js Describes a mechanism for locating an element on the page.
constructor
constructor(using: string, value: string);
Parameter using
the name of the location strategy to use.
Parameter value
the value to search for.
property using
using: string;
property value
value: string;
method className
static className: (name: string) => By;
Locates elements that have a specific class name.
Parameter name
The class name to search for. {!By} The new locator.
See Also
http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes
http://www.w3.org/TR/CSS2/selector.html#class-html
method css
static css: (selector: string) => By;
Locates elements using a CSS selector.
Parameter selector
The CSS selector to use. {!By} The new locator.
See Also
http://www.w3.org/TR/CSS2/selector.html
method id
static id: (id: string) => By;
Locates eleemnts by the ID attribute. This locator uses the CSS selector
*[id='$ID']
, _not_document.getElementById
.Parameter id
The ID to search for. {!By} The new locator.
method js
static js: ( script: string | Function, ...var_args: any[]) => (webdriver: WebDriver) => Promise<any>;
Locates an elements by evaluating a . The result of this expression must be an element or list of elements.
Parameter script
The script to execute.
Parameter var_args
The arguments to pass to the script. {function(!./WebDriver): !./Promise} A new JavaScript-based locator function.
method linkText
static linkText: (text: string) => By;
Locates link elements whose matches the given string.
Parameter text
The link text to search for. {!By} The new locator.
method name
static name: (name: string) => By;
Locates elements whose
name
attribute has the given value.Parameter name
The name attribute to search for. {!By} The new locator.
method partialLinkText
static partialLinkText: (text: string) => By;
Locates link elements whose contains the given substring.
Parameter text
The substring to check for in a link's visible text. {!By} The new locator.
method tagName
static tagName: (name: string) => By;
Locates elements with a given tag name.
Parameter name
The tag name to search for. {!By} The new locator.
Deprecated
Use instead.
method toObject
toObject: () => Object;
method toString
toString: () => string;
Modifiers
@override
method xpath
static xpath: (xpath: string) => By;
Locates elements matching a XPath selector. Care should be taken when using an XPath selector with a WebElement as WebDriver will respect the context in the specified in the selector. For example, given the selector
//div
, WebDriver will search from the document root regardless of whether the locator was used with a WebElement.Parameter xpath
The XPath selector to use. {!By} The new locator.
See Also
http://www.w3.org/TR/xpath/
class Capabilities
class Capabilities {}
Describes a set of capabilities for a WebDriver session.
constructor
constructor(other?: {} | Capabilities | Map<string, any>);
Parameter other
Another set of capabilities to initialize this instance from.
method [Symbols.serialize]
[Symbols.serialize]: () => {};
{!Object<string, ?>} The JSON representation of this instance. Note, the returned object may contain nested promised values. {checkTypes} Suppress [] access on a struct (state inherited from Map).
method chrome
static chrome: () => Capabilities;
{!Capabilities} A basic set of capabilities for Chrome.
method delete
delete: (key: string) => boolean;
Deletes an entry from this set of capabilities.
Parameter key
the capability key to delete.
method edge
static edge: () => Capabilities;
{!Capabilities} A basic set of capabilities for Microsoft Edge.
method firefox
static firefox: () => Capabilities;
{!Capabilities} A basic set of capabilities for Firefox.
method get
get: (key: string) => any;
Parameter key
The capability to return. {*} The capability with the given key, or if it has not been set.
method getAcceptInsecureCerts
getAcceptInsecureCerts: () => boolean;
{boolean} whether the session is configured to accept insecure TLS certificates.
method getAlertBehavior
getAlertBehavior: () => string | undefined;
{(UserPromptHandler|undefined)} the behavior pattern for responding to unhandled user prompts, or undefined if not set.
method getBrowserName
getBrowserName: () => string | undefined;
{(string|undefined)} the configured browser name, or undefined if not set.
method getBrowserVersion
getBrowserVersion: () => string | undefined;
{(string|undefined)} the configured browser version, or undefined if not set.
method getPageLoadStrategy
getPageLoadStrategy: () => string | undefined;
Returns the configured page load strategy.
{(string|undefined)} the page load strategy.
method getPlatform
getPlatform: () => string | undefined;
{(string|undefined)} the configured platform or undefined if not set.
method getProxy
getProxy: () => ProxyConfig | undefined;
{(proxy.Config|undefined)} the configured proxy settings, or undefined if not set.
method has
has: (key: string) => boolean;
Parameter key
The capability to check. {boolean} Whether the specified capability is set.
method ie
static ie: () => Capabilities;
{!Capabilities} A basic set of capabilities for Internet Explorer.
method keys
keys: () => IterableIterator<string>;
{!Iterator} an iterator of the keys set.
method merge
merge: (other: Capabilities | Map<string, any> | {}) => Capabilities;
Merges another set of capabilities into this instance.
Parameter other
The other set of capabilities to merge. {!Capabilities} A self reference.
method safari
static safari: () => Capabilities;
{!Capabilities} A basic set of capabilities for Safari.
method set
set: (key: string, value: any) => Capabilities;
Parameter key
The capability key.
Parameter value
The capability value. {!Capabilities} A self reference.
Throws
{TypeError} If the
key
is not a string.
method setAcceptInsecureCerts
setAcceptInsecureCerts: (accept: boolean) => Capabilities;
Sets whether a WebDriver session should implicitly accept self-signed, or other untrusted TLS certificates on navigation.
Parameter accept
whether to accept insecure certs. {!Capabilities} a self reference.
method setAlertBehavior
setAlertBehavior: (behavior: string) => Capabilities;
Sets the default action to take with an unexpected alert before returning an error. If unspecified, WebDriver will default to UserPromptHandler.DISMISS_AND_NOTIFY.
Parameter behavior
The way WebDriver should respond to unhandled user prompts. {!Capabilities} A self reference.
method setBrowserName
setBrowserName: (name: string) => Capabilities;
Sets the name of the target browser.
Parameter name
the browser name. {!Capabilities} a self reference.
method setBrowserVersion
setBrowserVersion: (version: string) => Capabilities;
Sets the desired version of the target browser.
Parameter version
the desired version. {!Capabilities} a self reference.
method setLoggingPrefs
setLoggingPrefs: (prefs: logging.Preferences | {}) => Capabilities;
Sets the logging preferences. Preferences may be specified as a instance, or as a map of log-type to log-level.
Parameter prefs
The logging preferences. {!Capabilities} A self reference.
method setPageLoadStrategy
setPageLoadStrategy: (strategy: string) => Capabilities;
Sets the desired page loading strategy for a new WebDriver session.
Parameter strategy
the desired strategy. {!Capabilities} a self reference.
method setPlatform
setPlatform: (platform: string) => Capabilities;
Sets the target platform.
Parameter platform
the target platform. {!Capabilities} a self reference.
method setProxy
setProxy: (proxy: ProxyConfig) => Capabilities;
Sets the proxy configuration for this instance.
Parameter proxy
The desired proxy configuration. {!Capabilities} A self reference.
class Condition
class Condition<T> {}
Defines a condition for use with WebDriver's .
constructor
constructor(message: string, fn: ConditionFn<T>);
Parameter message
A descriptive error message. Should complete the sentence "Waiting [...]"
Parameter fn
The condition function to evaluate on each iteration of the wait loop.
method description
description: () => string;
{string} A description of this condition.
class EventEmitter
class EventEmitter {}
Object that can emit events for others to listen for. This is used instead of Closure's event system because it is much more light weight. The API is based on Node's EventEmitters.
constructor
constructor();
method addListener
addListener: ( type: string, fn: Function, opt_scope?: any, opt_oneshot?: boolean) => EventEmitter;
Registers a listener.
Parameter type
The type of event to listen for.
Parameter fn
The function to invoke when the event is fired.
Parameter opt_self
The object in whose scope to invoke the listener.
Parameter opt_oneshot
Whether the listener should b (e removed after the first event is fired. {!EventEmitter} A self reference.
method emit
emit: (type: string, ...var_args: any[]) => void;
Fires an event and calls all listeners.
Parameter type
The type of event to emit.
Parameter var_args
Any arguments to pass to each listener.
method listeners
listeners: (type: string) => any;
Returns a mutable list of listeners for a specific type of event.
Parameter type
The type of event to retrieve the listeners for. {!Set<!Listener>} The registered listeners for the given event type.
method on
on: (type: string, fn: Function, opt_scope?: any) => EventEmitter;
An alias for .
Parameter type
The type of event to listen for.
Parameter fn
The function to invoke when the event is fired.
Parameter opt_scope
The object in whose scope to invoke the listener. {!EventEmitter} A self reference.
method once
once: (type: string, fn: any, opt_scope?: any) => EventEmitter;
Registers a one-time listener which will be called only the first time an event is emitted, after which it will be removed.
Parameter type
The type of event to listen for.
Parameter fn
The function to invoke when the event is fired.
Parameter opt_scope
The object in whose scope to invoke the listener. {!EventEmitter} A self reference.
method removeAllListeners
removeAllListeners: (opt_type?: string) => EventEmitter;
Removes all listeners for a specific type of event. If no event is specified, all listeners across all types will be removed.
Parameter opt_type
The type of event to remove listeners from. {!EventEmitter} A self reference.
method removeListener
removeListener: (type: string, listenerFn: Function) => EventEmitter;
Removes a previously registered event listener.
Parameter type
The type of event to unregister.
Parameter listenerFn
The handler function to remove. {!EventEmitter} A self reference.
class FileDetector
class FileDetector {}
Used with on file input elements (
<input type="file">
) to detect when the entered key sequence defines the path to a file.By default, will enter all key sequences exactly as entered. You may set a on the parent WebDriver instance to define custom behavior for handling file elements. Of particular note is the , which should be used when running against a remote [Selenium Server](https://selenium.dev/downloads/).
method handleFile
handleFile: (driver: WebDriver, path: string) => Promise<string>;
Handles the file specified by the given path, preparing it for use with the current browser. If the path does not refer to a valid file, it will be returned unchanged, otherwise a path suitable for use with the current browser will be returned.
This default implementation is a no-op. Subtypes may override this function for custom tailored file handling.
Parameter driver
The driver for the current browser.
Parameter path
The path to process. {!Promise} A promise for the processed file path.
class Listener
class Listener {}
Describes an event listener registered on an .
constructor
constructor(fn: Function, scope: {}, oneshot: boolean);
Parameter fn
The acutal listener function.
Parameter scope
The object in whose scope to invoke the listener.
Parameter oneshot
Whether this listener should only be used once.
class Logs
class Logs {}
Interface for managing WebDriver log records.
constructor
constructor(driver: WebDriver);
Parameter driver
The parent driver.
method get
get: (type: string) => Promise<logging.Entry[]>;
Fetches available log entries for the given type.
Note that log buffers are reset after each call, meaning that available log entries correspond to those entries not yet returned for a given log type. In practice, this means that this call will return the available log entries since the last call, or from the start of the session.
Parameter type
The desired log type. {!Promise.<!Array.<!logging.Entry>>} A promise that will resolve to a list of log entries for the specified type.
method getAvailableLogTypes
getAvailableLogTypes: () => Promise<string[]>;
Retrieves the log types available to this driver. {!Promise.<!Array.<!logging.Type>>} A promise that will resolve to a list of available log types.
class Navigation
class Navigation {}
Interface for navigating back and forth in the browser history.
This class should never be instantiated directly. Instead, obtain an instance with
webdriver.navigate()
See Also
WebDriver#navigate()
constructor
constructor(driver: WebDriver);
Parameter driver
The parent driver.
method back
back: () => Promise<void>;
Moves backwards in the browser history.
{!Promise} A promise that will be resolved when the navigation event has completed.
method forward
forward: () => Promise<void>;
Moves forwards in the browser history.
{!Promise} A promise that will be resolved when the navigation event has completed.
method refresh
refresh: () => Promise<void>;
Refreshes the current page.
{!Promise} A promise that will be resolved when the navigation event has completed.
method to
to: (url: string) => Promise<void>;
Navigates to a new URL.
Parameter url
The URL to navigate to. {!Promise} A promise that will be resolved when the URL has been loaded.
class Options
class Options {}
Provides methods for managing browser and driver state.
This class should never be instantiated directly. Instead, obtain an instance with .
constructor
constructor(driver: WebDriver);
Parameter driver
The parent driver.
method addCookie
addCookie: (spec: IWebDriverOptionsCookie) => Promise<void>;
Adds a cookie.
__Sample Usage:__
// Set a basic cookie. driver.manage().addCookie({name: 'foo', value: 'bar'});
// Set a cookie that expires in 10 minutes. let expiry = new Date(Date.now() + (10 * 60 * 1000)); driver.manage().addCookie({name: 'foo', value: 'bar', expiry});
// The cookie expiration may also be specified in seconds since epoch. driver.manage().addCookie({ name: 'foo', value: 'bar', expiry: Math.floor(Date.now() / 1000) });
Parameter spec
Defines the cookie to add. {!Promise} A promise that will be resolved when the cookie has been added to the page.
Throws
{error.InvalidArgumentError} if any of the cookie parameters are invalid.
Throws
{TypeError} if
spec
is not a cookie object.
method deleteAllCookies
deleteAllCookies: () => Promise<void>;
Deletes all cookies visible to the current page.
{!Promise} A promise that will be resolved when all cookies have been deleted.
method deleteCookie
deleteCookie: (name: string) => Promise<void>;
Deletes the cookie with the given name. This command is a no-op if there is no cookie with the given name visible to the current page.
Parameter name
The name of the cookie to delete. {!Promise} A promise that will be resolved when the cookie has been deleted.
method getCookie
getCookie: (name: string) => Promise<IWebDriverOptionsCookie>;
Retrieves the cookie with the given name. Returns null if there is no such cookie. The cookie will be returned as a JSON object as described by the WebDriver wire protocol.
Parameter name
The name of the cookie to retrieve. {!Promise<?Options.Cookie>} A promise that will be resolved with the named cookie
Throws
{error.NoSuchCookieError} if there is no such cookie.
method getCookies
getCookies: () => Promise<IWebDriverOptionsCookie[]>;
Retrieves all cookies visible to the current page. Each cookie will be returned as a JSON object as described by the WebDriver wire protocol.
{!Promise<!Array<!Options.Cookie>>} A promise that will be resolved with the cookies visible to the current browsing context.
method getTimeouts
getTimeouts: () => Promise<ITimeouts>;
Fetches the timeouts currently configured for the current session.
{!Promise<{script: number, pageLoad: number, implicit: number}>} A promise that will be resolved with the timeouts currently configured for the current session.
See Also
#setTimeouts()
method legacyTimeout
legacyTimeout: (driver: WebDriver, type: string, ms: number) => Promise<void>;
Parameter driver
Parameter type
Parameter ms
{!Promise}
method logs
logs: () => Logs;
{!Logs} The interface for managing driver logs.
method setTimeouts
setTimeouts: (timeouts: ITimeouts) => Promise<void>;
Sets the timeout durations associated with the current session.
The following timeouts are supported (all timeouts are specified in milliseconds):
-
implicit
specifies the maximum amount of time to wait for an element locator to succeed when on the page. Defaults to 0 milliseconds.-
pageLoad
specifies the maximum amount of time to wait for a page to finishing loading. Defaults to 300000 milliseconds.-
script
specifies the maximum amount of time to wait for an to run. If set tonull
, the script timeout will be indefinite. Defaults to 30000 milliseconds.Parameter conf
The desired timeout configuration. {!Promise} A promise that will be resolved when the timeouts have been set.
Throws
{!TypeError} if an invalid options object is provided.
See Also
#getTimeouts()
<https://w3c.github.io/webdriver/webdriver-spec.html#dfn-set-timeouts>
method window
window: () => Window;
{!Window} The interface for managing the current window.
class RelativeBy
class RelativeBy {}
Describes a mechanism for locating an element relative to others on the page.
constructor
constructor(findDetails: By, filters: Object[]);
Parameter findDetails
Parameter filters
method above
above: (locatorOrElement: Locator | WebElement) => RelativeBy;
Look for elements above the root element passed in
Parameter locatorOrElement
{!RelativeBy} Return this object
method below
below: (locatorOrElement: Locator | WebElement) => RelativeBy;
Look for elements below the root element passed in
Parameter locatorOrElement
{!RelativeBy} Return this object
method marshall
marshall: () => Object;
Returns a marshalled version of the RelativeBy {!Object} Object representation of a WebElement that will be used in .
method near
near: (locatorOrElement: Locator | WebElement) => RelativeBy;
Look for elements near the root element passed in
Parameter locatorOrElement
{!RelativeBy} Return this object
method toLeftOf
toLeftOf: (locatorOrElement: Locator | WebElement) => RelativeBy;
Look for elements left the root element passed in
Parameter locatorOrElement
{!RelativeBy} Return this object
method toRightOf
toRightOf: (locatorOrElement: Locator | WebElement) => RelativeBy;
Look for elements right the root element passed in
Parameter locatorOrElement
{!RelativeBy} Return this object
method toString
toString: () => string;
Modifiers
@override
class Session
class Session {}
Contains information about a WebDriver session.
constructor
constructor(id: string, capabilities: {} | Capabilities);
Parameter id
The session ID.
Parameter capabilities
The session capabilities.
method getCapabilities
getCapabilities: () => Capabilities;
{!Capabilities} This session's capabilities.
method getCapability
getCapability: (key: string) => any;
Retrieves the value of a specific capability.
Parameter key
The capability to retrieve. {*} The capability value.
method getId
getId: () => string;
{string} This session's ID.
method toJSON
toJSON: () => string;
Returns the JSON representation of this object, which is just the string session ID. {string} The JSON representation of this Session.
class TargetLocator
class TargetLocator {}
An interface for changing the focus of the driver to another frame or window.
This class should never be instantiated directly. Instead, obtain an instance with
webdriver.switchTo()
See Also
WebDriver#switchTo()
constructor
constructor(driver: WebDriver);
Parameter driver
The parent driver.
method activeElement
activeElement: () => WebElementPromise;
Locates the DOM element on the current page that corresponds to
document.activeElement
ordocument.body
if the active element is not available.{!WebElementPromise} The active element.
method alert
alert: () => AlertPromise;
Changes focus to the active modal dialog, such as those opened by
window.alert()
,window.confirm()
, andwindow.prompt()
. The returned promise will be rejected with a if there are no open alerts.{!AlertPromise} The open alert.
method defaultContent
defaultContent: () => Promise<void>;
Switches focus of all future commands to the topmost frame in the current window.
{!Promise} A promise that will be resolved when the driver has changed focus to the default content.
method frame
frame: (id: number | string | WebElement | null) => Promise<void>;
Changes the focus of all future commands to another frame on the page. The target frame may be specified as one of the following:
- A number that specifies a (zero-based) index into [window.frames]( https://developer.mozilla.org/en-US/docs/Web/API/Window.frames). - A WebElement reference, which correspond to a
frame
oriframe
DOM element. - Thenull
value, to select the topmost frame on the page. Passingnull
is the same as calling .If the specified frame can not be found, the returned promise will be rejected with a .
Parameter id
The frame locator. {!Promise} A promise that will be resolved when the driver has changed focus to the specified frame.
method newWindow
newWindow: (typeHint: string) => Promise<void>;
Creates a new browser window and switches the focus for future commands of this driver to the new window.
Parameter typeHint
'window' or 'tab'. The created window is not guaranteed to be of the requested type; if the driver does not support the requested type, a new browser window will be created of whatever type the driver does support. {!Promise} A promise that will be resolved when the driver has changed focus to the new window.
method parentFrame
parentFrame: () => Promise<void>;
Changes the focus of all future commands to the parent frame of the currently selected frame. This command has no effect if the driver is already focused on the top-level browsing context.
{!Promise} A promise that will be resolved when the command has completed.
method window
window: (nameOrHandle: string) => Promise<void>;
Changes the focus of all future commands to another window. Windows may be specified by their attribute or by its handle (as returned by WebDriver#getWindowHandles).
If the specified window cannot be found, the returned promise will be rejected with a .
Parameter nameOrHandle
The name or window handle of the window to switch focus to. {!Promise} A promise that will be resolved when the driver has changed focus to the specified window.
class TouchSequence
class TouchSequence {}
Class for defining sequences of user touch interactions. Each sequence will not be executed until is called.
Example:
new TouchSequence(driver). tapAndHold({x: 0, y: 0}). move({x: 3, y: 4}). release({x: 10, y: 10}). perform();
constructor
constructor(driver: WebDriver);
method doubleTap
doubleTap: (elem: WebElement) => TouchSequence;
Double taps an element.
Parameter elem
The element to double tap. {!TouchSequence} A self reference.
method flick
flick: (speed: ISpeed) => TouchSequence;
Flick, starting anywhere on the screen, at speed xspeed and yspeed.
Parameter speed
The speed to flick in each direction, in pixels per second. {!TouchSequence} A self reference.
method flickElement
flickElement: ( elem: WebElement, offset: IOffset, speed: number) => TouchSequence;
Flick starting at elem and moving by x and y at specified speed.
Parameter elem
The element where flick starts.
Parameter offset
The offset to flick to.
Parameter speed
The speed to flick at in pixels per second. {!TouchSequence} A self reference.
method longPress
longPress: (elem: WebElement) => TouchSequence;
Long press on an element.
Parameter elem
The element to long press. {!TouchSequence} A self reference.
method move
move: (location: ILocation) => TouchSequence;
Move a held to the specified location.
Parameter location
The location to move to. {!TouchSequence} A self reference.
method perform
perform: () => Promise<void>;
Executes this action sequence. {!Promise} A promise that will be resolved once this sequence has completed.
method release
release: (location: ILocation) => TouchSequence;
Release a held at the specified location.
Parameter location
The location to release at. {!TouchSequence} A self reference.
method scroll
scroll: (offset: IOffset) => TouchSequence;
Scrolls the touch screen by the given offset.
Parameter offset
The offset to scroll to. {!TouchSequence} A self reference.
method scrollFromElement
scrollFromElement: (elem: WebElement, offset: IOffset) => TouchSequence;
Scrolls the touch screen, starting on
elem
and moving by the specified offset.Parameter elem
The element where scroll starts.
Parameter offset
The offset to scroll to. {!TouchSequence} A self reference.
method tap
tap: (elem: WebElement) => TouchSequence;
Taps an element.
Parameter elem
The element to tap. {!TouchSequence} A self reference.
method tapAndHold
tapAndHold: (location: ILocation) => TouchSequence;
Touch down at the given location.
Parameter location
The location to touch down at. {!TouchSequence} A self reference.
class WebDriver
class WebDriver {}
Each WebDriver instance provides automated control over a browser session.
constructor
constructor( session: Session | Promise<Session>, executor: Executor, onQuit?: (this: void) => any);
Parameter session
Either a known session or a promise that will be resolved to a session.
Parameter executor
The executor to use when sending commands to the browser.
Parameter onQuit
A function to call, if any, when the session is terminated.
method actions
actions: (options?: { async?: boolean | undefined; bridge?: boolean | undefined;}) => Actions;
Modifiers
@override
method close
close: () => Promise<void>;
Closes the current window.
{!Promise} A promise that will be resolved when this command has completed.
method createCDPConnection
createCDPConnection: (target: string) => Promise<any>;
Creates a new WebSocket connection. {!Promise} A new CDP instance.
method createSession
static createSession: (...var_args: any[]) => 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 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));
Parameter executor
The executor to create the new session with.
Parameter capabilities
The desired capabilities for the new session.
Parameter onQuit
A callback to invoke when the newly created session is terminated. This should be used to clean up any resources associated with the session. {!WebDriver} The driver for the newly created session.
method execute
execute: (command: Command) => Promise<void>;
Modifiers
@override
method executeAsyncScript
executeAsyncScript: <T>(script: string | Function, ...args: any[]) => Promise<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 . 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 , 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']); });
Parameter script
The script to execute.
Parameter args
The arguments to pass to the script. {!IThenable} A promise that will resolve to the scripts return value. T
method executeScript
executeScript: <T>(script: string | Function, ...args: any[]) => Promise<T>;
Modifiers
@override
method findElement
findElement: (locator: Locator) => 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 :
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(); }); }
Parameter locator
The locator to use. {!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.
method findElementInternal_
findElementInternal_: ( locatorFn: Function, context: WebDriver | WebElement) => Promise<WebElement>;
Parameter locatorFn
The locator function to use.
Parameter context
The search context. {!Promise<!WebElement>} A promise that will resolve to a list of WebElements.
method findElements
findElements: (locator: Locator) => Promise<WebElement[]>;
Search for multiple elements on the page. Refer to the documentation on for information on element locator strategies.
Parameter locator
The locator to use. {!Promise<!Array<!WebElement>>} A promise that will resolve to an array of WebElements.
method findElementsInternal_
findElementsInternal_: ( locatorFn: Function, context: WebDriver | WebElement) => Promise<WebElement[]>;
Parameter locatorFn
The locator function to use.
Parameter context
The search context. {!Promise<!Array<!WebElement>>} A promise that will resolve to an array of WebElements.
method get
get: (url: string) => Promise<void>;
Navigates to the given URL.
Parameter url
The fully qualified URL to open. {!Promise} A promise that will be resolved when the document has finished loading.
method getAllWindowHandles
getAllWindowHandles: () => Promise<string[]>;
Retrieves a list of all available window handles.
{!Promise<!Array>} A promise that will be resolved with an array of window handles.
method getCapabilities
getCapabilities: () => Promise<Capabilities>;
Modifiers
@override
method getCurrentUrl
getCurrentUrl: () => Promise<string>;
Retrieves the URL for the current page.
{!Promise} A promise that will be resolved with the current URL.
method getExecutor
getExecutor: () => Executor;
Modifiers
@override
method getPageSource
getPageSource: () => 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.
{!Promise} A promise that will be resolved with the current page source.
method getSession
getSession: () => Promise<Session>;
Modifiers
@override
method getTitle
getTitle: () => Promise<string>;
Retrieves the current page title.
{!Promise} A promise that will be resolved with the current page's title.
method getWindowHandle
getWindowHandle: () => Promise<string>;
Retrieves the current window handle.
{!Promise} A promise that will be resolved with the current window handle.
method getWsUrl
getWsUrl: ( debuggerAddress: string, target: string, caps: Capabilities) => Promise<string>;
Retrieves 'webSocketDebuggerUrl' by sending a http request using debugger address
Parameter debuggerAddress
Parameter target
Parameter caps
{string} Returns parsed webSocketDebuggerUrl obtained from the http request
method logMutationEvents
logMutationEvents: ( connection: WebSocket, callback: (event: any) => void) => Promise<void>;
Parameter connection
Parameter callback
Returns
{Promise}
method manage
manage: () => Options;
{!Options} The options interface for this instance.
method navigate
navigate: () => Navigation;
{!Navigation} The navigation interface for this instance.
method normalize_
normalize_: (webElementPromise: Function) => Promise<WebElement>;
Parameter webElementPromise
The webElement in unresolved state {!Promise<!WebElement>} First single WebElement from array of resolved promises
method onIntercept
onIntercept: ( connection: WebSocket, httpResponse: HttpResponse, callback: () => void) => Promise<void>;
Handle Network interception requests
Parameter connection
WebSocket connection to the browser
Parameter httpResponse
Object representing what we are intercepting as well as what should be returned.
Parameter callback
callback called when we intercept requests.
method onLogEvent
onLogEvent: ( connection: WebSocket, callback: (event: any) => void) => Promise<void>;
Parameter connection
Parameter callback
Returns
{Promise}
method onLogException
onLogException: ( connection: WebSocket, callback: (event: any) => void) => Promise<void>;
Parameter connection
Parameter callback
Returns
{Promise}
method printPage
printPage: (options: { orientation: string | undefined; scale: number | undefined; background: boolean | undefined; width: number | undefined; height: number | undefined; top: number | undefined; bottom: number | undefined; left: number | undefined; right: number | undefined; shrinkToFit: boolean | undefined; pageRanges: [] | undefined;}) => void;
Takes a PDF of the current page. The driver makes a best effort to return a PDF based on the provided parameters.
Parameter options
method quit
quit: () => Promise<void>;
Modifiers
@override
method register
register: (username: string, password: string, connection: any) => Promise<void>;
Sets a listener for Fetch.authRequired event from CDP If event is triggered, it enter username and password and allows the test to move forward
Parameter username
Parameter password
Parameter connection
CDP Connection
method setFileDetector
setFileDetector: (detector: FileDetector) => void;
Modifiers
@override
method sleep
sleep: (ms: number) => Promise<void>;
Makes the driver sleep for the given amount of time.
Parameter ms
The amount of time, in milliseconds, to sleep. {!Promise} A promise that will be resolved when the sleep has finished.
method switchTo
switchTo: () => TargetLocator;
{!TargetLocator} The target locator interface for this instance.
method takeScreenshot
takeScreenshot: () => 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
{!Promise} A promise that will be resolved to the screenshot as a base-64 encod ed PNG.
method wait
wait: { ( condition: WebElementCondition, timeout?: number, message?: string, pollTimeout?: number ): WebElementPromise; <T>( condition: | Function | PromiseLike<T> | Condition<T> | ((driver: WebDriver) => T | PromiseLike<T>), timeout?: number, message?: string, pollTimeout?: number ): Promise<T>;};
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 , 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(); }
Parameter condition
The condition to wait on, defined as a promise, condition object, or a function to evaluate as a condition.
Parameter timeout
The duration in milliseconds, how long to wait for the condition to be true.
Parameter message
An optional message to use if the wait times out.
Parameter pollTimeout
The duration in milliseconds, how long to wait between polling the condition. {!(IThenable|WebElementPromise)} 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.
Throws
{TypeError} if the provided
condition
is not a valid type. T
class WebElement
class WebElement implements Serializable<IWebElementId> {}
Represents a DOM element. WebElements can be found by searching from the document root using a WebDriver instance, or by searching under another WebElement:
driver.get('http://www.google.com'); var searchForm = driver.findElement(By.tagName('form')); var searchBox = searchForm.findElement(By.name('q')); searchBox.sendKeys('webdriver');
The WebElement is implemented as a promise for compatibility with the promise API. It will always resolve itself when its internal state has been fully resolved and commands may be issued against the element. This can be used to catch errors when an element cannot be located on the page:
driver.findElement(By.id('not-there')).then(function(element) { alert('Found an element that was not expected to be there!'); }, function(error) { alert('The element was not found, as expected'); });
constructor
constructor(driver: WebDriver, id: string | Promise<string>);
Parameter driver
the parent WebDriver instance for this element.
Parameter id
The server-assigned opaque ID for the underlying DOM element.
method buildId
static buildId: (id: string, opt_noLegacy?: boolean) => IWebElementId;
Parameter id
The raw ID.
Parameter opt_noLegacy
Whether to exclude the legacy element key. {!Object} The element ID for use with WebDriver's wire protocol.
method clear
clear: () => Promise<void>;
Schedules a command to clear the
value
of this element. This command has no effect if the underlying DOM element is neither a text INPUT element nor a TEXTAREA element. {!Promise} A promise that will be resolved when the element has been cleared.
method click
click: () => Promise<void>;
Schedules a command to click on this element. {!Promise.} A promise that will be resolved when the click command has completed.
method equals
static equals: (a: WebElement, b: WebElement) => Promise<boolean>;
Compares two WebElements for equality.
Parameter a
A WebElement.
Parameter b
A WebElement. {!Promise} A promise that will be resolved to whether the two WebElements are equal.
method extractId
static extractId: (obj: IWebElementId) => string;
Extracts the encoded WebElement ID from the object.
Parameter obj
The object to extract the ID from. {string} the extracted ID.
Throws
{TypeError} if the object is not a valid encoded ID.
method findElement
findElement: (locator: Locator) => WebElementPromise;
Schedule a command to find a descendant of this element. 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 .
The search criteria for an element may be defined using one of the factories in the By namespace, or as a short-hand By.Hash object. For example, the following two statements are equivalent:
var e1 = element.findElement(By.id('foo')); var e2 = element.findElement({id:'foo'});
You may also provide a custom locator function, which takes as input this WebDriver instance and returns a 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 = element.findElement(firstVisibleLink);
function firstVisibleLink(element) { var links = element.findElements(By.tagName('a')); return promise.filter(links, function(link) { return links.isDisplayed(); }).then(function(visibleLinks) { return visibleLinks[0]; }); }
Parameter locator
The locator strategy to use when searching for the element. {!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.
method findElements
findElements: (locator: Locator) => Promise<WebElement[]>;
Schedules a command to find all of the descendants of this element that match the given search criteria.
Parameter locator
The locator strategy to use when searching for the element. {!Promise<!Array<!WebElement>>} A promise that will resolve to an array of WebElements.
method getAttribute
getAttribute: (attributeName: string) => Promise<string>;
Schedules a command to query for the value of the given attribute of the element. Will return the current value, even if it has been modified after the page has been loaded. More exactly, this method will return the value of the given attribute, unless that attribute is not present, in which case the value of the property with the same name is returned. If neither value is set, null is returned (for example, the 'value' property of a textarea element). The 'style' attribute is converted as best can be to a text representation with a trailing semi-colon. The following are deemed to be 'boolean' attributes and will return either 'true' or null:
async, autofocus, autoplay, checked, compact, complete, controls, declare, defaultchecked, defaultselected, defer, disabled, draggable, ended, formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, selected, spellcheck, truespeed, willvalidate
Finally, the following commonly mis-capitalized attribute/property names are evaluated as expected:
- 'class' - 'readonly'
Parameter attributeName
The name of the attribute to query. {!Promise.<?string>} A promise that will be resolved with the attribute's value. The returned value will always be either a string or null.
method getCssValue
getCssValue: (cssStyleProperty: string) => Promise<string>;
Schedules a command to query for the computed style of the element represented by this instance. If the element inherits the named style from its parent, the parent will be queried for its value. Where possible, color values will be converted to their hex representation (e.g. #00ff00 instead of rgb(0, 255, 0)).
_Warning:_ the value returned will be as the browser interprets it, so it may be tricky to form a proper assertion.
Parameter cssStyleProperty
The name of the CSS style property to look up. {!Promise} A promise that will be resolved with the requested CSS value.
method getDriver
getDriver: () => WebDriver;
{!WebDriver} The parent driver for this instance.
method getId
getId: () => Promise<string>;
{!Promise} A promise that resolves to the server-assigned opaque ID assigned to this element.
method getLocation
getLocation: () => Promise<ILocation>;
DEPRECATED 3.0 Schedules a command to compute the location of this element in page space. {!Promise.<{x: number, y: number}>} A promise that will be resolved to the element's location as a {@code {x:number, y:number}} object.
method getRect
getRect: () => Promise<IRectangle>;
Returns an object describing an element's location, in pixels relative to the document element, and the element's size in pixels.
method getShadowRoot
getShadowRoot: () => ShadowRootPromise;
Get the shadow root of the current web element.
Returns
{!Promise} A promise that will be resolved with the elements shadow root or rejected with NoSuchShadowRootError
method getSize
getSize: () => Promise<ISize>;
DEPRECATED 3.0 Schedules a command to compute the size of this element's bounding box, in pixels. {!Promise.<{width: number, height: number}>} A promise that will be resolved with the element's size as a {@code {width:number, height:number}} object.
method getTagName
getTagName: () => Promise<string>;
Schedules a command to query for the tag/node name of this element. {!Promise.} A promise that will be resolved with the element's tag name.
method getText
getText: () => Promise<string>;
Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace. {!Promise.} A promise that will be resolved with the element's visible text.
method isDisplayed
isDisplayed: () => Promise<boolean>;
Schedules a command to test whether this element is currently displayed. {!Promise.} A promise that will be resolved with whether this element is currently visible on the page.
method isEnabled
isEnabled: () => Promise<boolean>;
Schedules a command to query whether the DOM element represented by this instance is enabled, as dicted by the attribute. {!Promise.} A promise that will be resolved with whether this element is currently enabled.
method isId
static isId: (obj: IWebElementId) => boolean;
Parameter obj
the object to test. {boolean} whether the object is a valid encoded WebElement ID.
method isSelected
isSelected: () => Promise<boolean>;
Schedules a command to query whether this element is selected. {!Promise.} A promise that will be resolved with whether this element is currently selected.
method sendKeys
sendKeys: ( ...var_args: Array<string | number | Promise<string | number>>) => Promise<void>;
Schedules a command to type a sequence on the DOM element represented by this promsieinstance.
Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is processed in the keysequence, that key state is toggled until one of the following occurs:
- The modifier key is encountered again in the sequence. At this point the state of the key is toggled (along with the appropriate keyup/down events). - The Key.NULL key is encountered in the sequence. When this key is encountered, all modifier keys current in the down state are released (with accompanying keyup events). The NULL key can be used to simulate common keyboard shortcuts:
element.sendKeys('text was', Key.CONTROL, 'a', Key.NULL, 'now text is'); // Alternatively: element.sendKeys('text was', Key.chord(Key.CONTROL, 'a'), 'now text is');
- The end of the keysequence is encountered. When there are no more keys to type, all depressed modifier keys are released (with accompanying keyup events).
If this element is a file input (), the specified key sequence should specify the path to the file to attach to the element. This is analgous to the user clicking 'Browse...' and entering the path into the file select dialog.
var form = driver.findElement(By.css('form')); var element = form.findElement(By.css('input[type=file]')); element.sendKeys('/path/to/file.txt'); form.submit();
For uploads to function correctly, the entered path must reference a file on the _browser's_ machine, not the local machine running this script. When running against a remote Selenium server, a FileDetector may be used to transparently copy files to the remote machine before attempting to upload them in the browser.
__Note:__ On browsers where native keyboard events are not supported (e.g. Firefox on OS X), key events will be synthesized. Special punctionation keys will be synthesized according to a standard QWERTY en-us keyboard layout.
Parameter var_args
The sequence of keys to type. All arguments will be joined into a single sequence. {!Promise.} A promise that will be resolved when all keys have been typed.
method serialize
serialize: () => Promise<IWebElementId>;
Modifiers
@override
method submit
submit: () => Promise<void>;
Schedules a command to submit the form containing this element (or this element if it is a FORM element). This command is a no-op if the element is not contained in a form. {!Promise.} A promise that will be resolved when the form has been submitted.
method takeScreenshot
takeScreenshot: (opt_scroll?: boolean) => Promise<string>;
Take a screenshot of the visible region encompassed by this element's bounding rectangle.
Parameter opt_scroll
Optional argument that indicates whether the element should be scrolled into view before taking a screenshot. Defaults to false. {!Promise} A promise that will be resolved to the screenshot as a base-64 encoded PNG.
class WebElementCondition
class WebElementCondition extends Condition<WebElement> {}
Defines a condition that will result in a WebElement.
constructor
constructor(message: string, fn: ConditionFn<WebElement>);
Parameter message
A descriptive error message. Should complete the sentence "Waiting [...]"
Parameter fn
The condition function to evaluate on each iteration of the wait loop.
class WebElementPromise
class WebElementPromise extends WebElement {}
Implement WebElementPromise
constructor
constructor(driver: WebDriver, el: Promise<WebElement>);
Parameter driver
The parent WebDriver instance for this element.
Parameter el
A promise that will resolve to the promised element.
class Window
class Window {}
An interface for managing the current window.
constructor
constructor(driver: WebDriver);
Parameter driver
The parent driver.
method fullscreen
fullscreen: () => Promise<void>;
Invokes the "full screen" operation on the current window. The exact behavior of this command is specific to individual window managers, but this will typically increase the window size to the size of the physical display and hide the browser chrome.
{!Promise} A promise that will be resolved when the command has completed.
See Also
<https://fullscreen.spec.whatwg.org/#fullscreen-an-element>
method getPosition
getPosition: () => Promise<ILocation>;
Retrieves the window's current position, relative to the top left corner of the screen. {!Promise} A promise that will be resolved with the window's position in the form of a {x:number, y:number} object literal.
method getRect
getRect: () => Promise<IRectangle>;
Returns the current top-level window's size and position.
method getSize
getSize: () => Promise<ISize>;
Retrieves the window's current size. {!Promise} A promise that will be resolved with the window's size in the form of a {width:number, height:number} object literal.
method maximize
maximize: () => Promise<void>;
Maximizes the current window. The exact behavior of this command is specific to individual window managers, but typically involves increasing the window to the maximum available size without going full-screen. {!Promise} A promise that will be resolved when the command has completed.
method minimize
minimize: () => Promise<void>;
Minimizes the current window. The exact behavior of this command is specific to individual window managers, but typically involves hiding the window in the system tray. {!Promise} A promise that will be resolved when the command has completed.
method setPosition
setPosition: (x: number, y: number) => Promise<void>;
Repositions the current window.
Parameter x
The desired horizontal position, relative to the left side of the screen.
Parameter y
The desired vertical position, relative to the top of the of the screen. {!Promise} A promise that will be resolved when the command has completed.
method setRect
setRect: ({ x, y, width, height }: Partial<IRectangle>) => Promise<IRectangle>;
Sets the current top-level window's size and position. You may update just the size by omitting
x
&y
, or just the position by omittingwidth
&height
options.
method setSize
setSize: (width: number, height: number) => Promise<void>;
Resizes the current window.
Parameter width
The desired window width.
Parameter height
The desired window height. {!Promise} A promise that will be resolved when the command has completed.
Interfaces
interface IRectangle
interface IRectangle {}
x,y,w,h
interface ISize
interface ISize {}
width, height
interface ISpeed
interface ISpeed {}
delta x,y
interface ITimeouts
interface ITimeouts {}
property implicit
implicit?: number | undefined;
The maximum amount of time, in milliseconds, to spend attempting to an element on the current page.
property pageLoad
pageLoad?: number | undefined;
The timeout, in milliseconds, to apply to navigation events along with the PageLoadStrategy.
property script
script?: number | undefined;
Defines when, in milliseconds, to interrupt a script that is being .
interface IWebDriverOptionsCookie
interface IWebDriverOptionsCookie {}
property domain
domain?: string | undefined;
The domain the cookie is visible to. Defaults to the current browsing context's document's URL when adding a cookie.
property expiry
expiry?: number | Date | undefined;
When the cookie expires.
When , this may be specified in _seconds_ since Unix epoch (January 1, 1970). The expiry will default to 20 years in the future if omitted.
The expiry is always returned in seconds since epoch when from the browser.
property httpOnly
httpOnly?: boolean | undefined;
Whether the cookie is an HTTP only cookie. Defaults to false when adding a new cookie.
property name
name: string;
The name of the cookie.
property path
path?: string | undefined;
The cookie path. Defaults to "/" when adding a cookie.
property sameSite
sameSite?: string;
property secure
secure?: boolean | undefined;
Whether the cookie is a secure cookie. Defaults to false when adding a new cookie.
property value
value: string;
The cookie value.
interface IWebElement
interface IWebElement {}
Represents a DOM element. WebElements can be found by searching from the document root using a instance, or by searching under another : driver.get('http://www.google.com'); var searchForm = driver.findElement(By.tagName('form')); var searchBox = searchForm.findElement(By.name('q')); searchBox.sendKeys('webdriver');
The WebElement is implemented as a promise for compatibility with the promise API. It will always resolve itself when its internal state has been fully resolved and commands may be issued against the element. This can be used to catch errors when an element cannot be located on the page: driver.findElement(By.id('not-there')).then(function(element) { alert('Found an element that was not expected to be there!'); }, function(error) { alert('The element was not found, as expected'); });
method clear
clear: () => Promise<void>;
Schedules a command to clear the of this element. This command has no effect if the underlying DOM element is neither a text INPUT element nor a TEXTAREA element. {!Promise} A promise that will be resolved when the element has been cleared.
method click
click: () => Promise<void>;
Schedules a command to click on this element. {!Promise} A promise that will be resolved when the click command has completed.
method getAttribute
getAttribute: (attributeName: string) => Promise<string>;
Schedules a command to query for the value of the given attribute of the element. Will return the current value even if it has been modified after the page has been loaded. More exactly, this method will return the value of the given attribute, unless that attribute is not present, in which case the value of the property with the same name is returned. If neither value is set, null is returned. The 'style' attribute is converted as best can be to a text representation with a trailing semi-colon. The following are deemed to be 'boolean' attributes and will be returned as thus:
async, autofocus, autoplay, checked, compact, complete, controls, declare, defaultchecked, defaultselected, defer, disabled, draggable, ended, formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, selected, spellcheck, truespeed, willvalidate
Finally, the following commonly mis-capitalized attribute/property names are evaluated as expected: 'class' 'readonly'
Parameter attributeName
The name of the attribute to query. {!Promise} A promise that will be resolved with the attribute's value.
method getCssValue
getCssValue: (cssStyleProperty: string) => Promise<string>;
Schedules a command to query for the computed style of the element represented by this instance. If the element inherits the named style from its parent, the parent will be queried for its value. Where possible, color values will be converted to their hex representation (e.g. #00ff00 instead of rgb(0, 255, 0)). Warning: the value returned will be as the browser interprets it, so it may be tricky to form a proper assertion.
Parameter cssStyleProperty
The name of the CSS style property to look up. {!Promise} A promise that will be resolved with the requested CSS value.
method getId
getId: () => Promise<IWebElementId>;
{!Promise.<WebElement.Id>} A promise that resolves to this element's JSON representation as defined by the WebDriver wire protocol.
See Also
http://code.google.com/p/selenium/wiki/JsonWireProtocol
method getLocation
getLocation: () => Promise<ILocation>;
Schedules a command to compute the location of this element in page space. {!Promise} A promise that will be resolved to the element's location as a {@code {x:number, y:number}} object.
method getRect
getRect: () => Promise<IRectangle>;
Returns an object describing an element's location, in pixels relative to the document element, and the element's size in pixels.
method getSize
getSize: () => Promise<ISize>;
Schedules a command to compute the size of this element's bounding box, in pixels. {!Promise} A promise that will be resolved with the element's size as a {@code {width:number, height:number}} object.
method getTagName
getTagName: () => Promise<string>;
Schedules a command to query for the tag/node name of this element. {!Promise} A promise that will be resolved with the element's tag name.
method getText
getText: () => Promise<string>;
Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace. {!Promise} A promise that will be resolved with the element's visible text.
method isDisplayed
isDisplayed: () => Promise<boolean>;
Schedules a command to test whether this element is currently displayed. {!Promise} A promise that will be resolved with whether this element is currently visible on the page.
method isEnabled
isEnabled: () => Promise<boolean>;
Schedules a command to query whether the DOM element represented by this instance is enabled, as dicted by the attribute. {!Promise} A promise that will be resolved with whether this element is currently enabled.
method isSelected
isSelected: () => Promise<boolean>;
Schedules a command to query whether this element is selected. {!Promise} A promise that will be resolved with whether this element is currently selected.
method sendKeys
sendKeys: ( ...var_args: Array<number | string | Promise<string | number>>) => Promise<void>;
Schedules a command to type a sequence on the DOM element represented by this instance.
Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is processed in the key sequence, that key state is toggled until one of the following occurs:
- The modifier key is encountered again in the sequence. At this point the state of the key is toggled (along with the appropriate keyup/down events). - The input.Key.NULL key is encountered in the sequence. When this key is encountered, all modifier keys current in the down state are released (with accompanying keyup events). The NULL key can be used to simulate common keyboard shortcuts:
element.sendKeys('text was', Key.CONTROL, 'a', Key.NULL, 'now text is'); // Alternatively: element.sendKeys('text was', Key.chord(Key.CONTROL, 'a'), 'now text is');
- The end of the key sequence is encountered. When there are no more keys to type, all depressed modifier keys are released (with accompanying keyup events).
If this element is a file input (), the specified key sequence should specify the path to the file to attach to the element. This is analogous to the user clicking 'Browse...' and entering the path into the file select dialog.
var form = driver.findElement(By.css('form')); var element = form.findElement(By.css('input[type=file]')); element.sendKeys('/path/to/file.txt'); form.submit();
For uploads to function correctly, the entered path must reference a file on the _browser's_ machine, not the local machine running this script. When running against a remote Selenium server, a input.FileDetector may be used to transparently copy files to the remote machine before attempting to upload them in the browser.
__Note:__ On browsers where native keyboard events are not supported (e.g. Firefox on OS X), key events will be synthesized. Special punctuation keys will be synthesized according to a standard QWERTY en-us keyboard layout.
Parameter var_args
The sequence of keys to type. Number keys may be referenced numerically or by string (1 or '1'). All arguments will be joined into a single sequence. {!Promise} A promise that will be resolved when all keys have been typed.
method submit
submit: () => Promise<void>;
Schedules a command to submit the form containing this element (or this element if it is a FORM element). This command is a no-op if the element is not contained in a form. {!Promise} A promise that will be resolved when the form has been submitted.
interface IWebElementFinders
interface IWebElementFinders {}
method findElement
findElement: (locator: Locator) => WebElementPromise;
Schedule a command to find a descendant of this element. If the element cannot be found, a 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 .
The search criteria for an element may be defined using one of the factories in the By namespace, or as a short-hand By.Hash object. For example, the following two statements are equivalent: var e1 = element.findElement(By.id('foo')); var e2 = element.findElement({id:'foo'});
You may also provide a custom locator function, which takes as input this WebDriver instance and returns a 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 = element.findElement(firstVisibleLink);
function firstVisibleLink(element) { var links = element.findElements(By.tagName('a')); return promise.filter(links, function(link) { return links.isDisplayed(); }).then(function(visibleLinks) { return visibleLinks[0]; }); }
Parameter locator
The locator strategy to use when searching for the element. {!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.
method findElements
findElements: (locator: Locator) => Promise<WebElement[]>;
Schedules a command to find all of the descendants of this element that match the given search criteria.
Parameter locator
The locator strategy to use when searching for the elements. {!Promise.<!Array.<!WebElement>>} A promise that will resolve to an array of WebElements.
interface IWebElementId
interface IWebElementId {}
index signature
[ELEMENT: string]: string;
interface ProxyConfig
interface ProxyConfig {}
ProxyConfig
property ftpProxy
ftpProxy?: string | undefined;
property httpProxy
httpProxy?: string | undefined;
property noProxy
noProxy?: string | undefined;
property proxyAutoconfigUrl
proxyAutoconfigUrl?: string | undefined;
property proxyType
proxyType: string;
property socksPassword
socksPassword?: string | undefined;
property socksProxy
socksProxy?: string | undefined;
property socksUsername
socksUsername?: string | undefined;
property sslProxy
sslProxy?: string | undefined;
interface Serializable
interface Serializable<T> {}
Defines an object that can be asynchronously serialized to its WebDriver wire representation.
T
method serialize
serialize: () => T | Promise<T>;
Returns either this instance's serialized represention, if immediately available, or a promise for its serialized representation. This function is conceptually equivalent to objects that have a property, except the serialize() result may be a promise or an object containing a promise (which are not directly JSON friendly).
{!(T|IThenable.<!T>)} This instance's serialized wire format.
interface ThenableWebDriver
interface ThenableWebDriver extends WebDriver, Promise<WebDriver> {}
A thenable wrapper around a instance that allows commands to be issued directly instead of having to repeatedly call
then
:let driver = new Builder().build(); driver.then(d => d.get(url)); // You can do this... driver.get(url); // ...or this
If the driver instance fails to resolve (e.g. the session cannot be created), every issued command will fail.
interface WebElementPromise
interface WebElementPromise extends Promise<WebElement> {}
WebElementPromise is a promise that will be fulfilled with a WebElement. This serves as a forward proxy on WebElement, allowing calls to be scheduled without directly on this instance before the underlying WebElement has been fulfilled. In other words, the following two statements are equivalent: driver.findElement({id: 'my-button'}).click(); driver.findElement({id: 'my-button'}).then(function(el) { return el.click(); });
Parameter driver
The parent WebDriver instance for this element.
Parameter el
A promise that will resolve to the promised element.
Enums
Type Aliases
type ByHash
type ByHash = | { className: string } | { css: string } | { id: string } | { js: string } | { linkText: string } | { name: string } | { partialLinkText: string } | { tagName: string } | { xpath: string };
Short-hand expressions for the primary element locator strategies. For example the following two statements are equivalent:
var e1 = driver.findElement(By.id('foo')); var e2 = driver.findElement({id: 'foo'});
Care should be taken when using JavaScript minifiers (such as the Closure compiler), as locator hashes will always be parsed using the un-obfuscated properties listed.
type CreateSessionCapabilities
type CreateSessionCapabilities = | Capabilities | { desired?: Capabilities | undefined; required?: Capabilities | undefined; };
type Locator
type Locator = By | Function | ByHash | RelativeBy;
Namespaces
namespace chromium
module 'chromium.d.ts' {}
Creates instances that manage a WebDriver server in a child process.
class ChromiumWebDriver
class ChromiumWebDriver extends webdriver.WebDriver {}
Creates a new WebDriver client for Chromium-based browsers.
method createSession
static createSession: ( caps?: webdriver.Capabilities | Options, opt_serviceExecutor?: remote.DriverService | Executor, vendorPrefix?: string, vendorCapabilityKey?: string) => ChromiumWebDriver;
Creates a new session with the WebDriver server.
Parameter caps
The configuration options.
Parameter opt_serviceExecutor
Either a DriverService to use for the remote end, or a preconfigured executor for an externally managed endpoint. If neither is provided, the will be used by default.
Parameter vendorPrefix
Either 'goog' or 'ms'
Parameter vendorCapabilityKey
Either 'goog:chromeOptions' or 'ms:edgeOptions' {!ChromiumWebDriver} A new driver instance.
method deleteNetworkConditions
deleteNetworkConditions: () => Promise<any>;
Schedules a command to delete Chromium network emulation settings. {!Promise} A promise that will be resolved when network emulation settings have been deleted.
method getCastIssueMessage
getCastIssueMessage: () => Promise<string>;
Returns an error message when there is any issue in a Cast session. {!promise.Thenable} A promise that will be resolved when the mirror command has been issued to the device.
method getCastSinks
getCastSinks: () => Promise<string[]>;
Returns the list of cast sinks (Cast devices) available to the Chrome media router.
{!promise.Thenable} A promise that will be resolved with an array of Strings containing the friendly device names of available cast sink targets.
method getNetworkConditions
getNetworkConditions: () => Promise<any>;
Schedules a command to get Chromium network emulation settings. {!Promise} A promise that will be resolved when network emulation settings are retrieved.
method launchApp
launchApp: (id: string) => Promise<void>;
Schedules a command to launch Chrome App with given ID.
Parameter id
ID of the App to launch. {!Promise} A promise that will be resolved when app is launched.
method sendAndGetDevToolsCommand
sendAndGetDevToolsCommand: (cmd: string, params: object) => Promise<string>;
Sends an arbitrary devtools command to the browser and get the result.
Parameter cmd
The name of the command to send.
Parameter params
The command parameters. {!Promise} A promise that will be resolved when the command has finished.
See Also
<https://chromedevtools.github.io/devtools-protocol/>
method sendDevToolsCommand
sendDevToolsCommand: (cmd: string, params: object) => Promise<void>;
Sends an arbitrary devtools command to the browser.
Parameter cmd
The name of the command to send.
Parameter params
The command parameters. {!Promise} A promise that will be resolved when the command has finished.
See Also
<https://chromedevtools.github.io/devtools-protocol/>
method setCastSinkToUse
setCastSinkToUse: (deviceName: string) => Promise<void>;
Selects a cast sink (Cast device) as the recipient of media router intents (connect or play).
Parameter deviceName
name of the target device. {!promise.Thenable} A promise that will be resolved when the target device has been selected to respond further webdriver commands.
method setDownloadPath
setDownloadPath: (path: string) => Promise<void>;
Sends a DevTools command to change the browser's download directory.
Parameter path
The desired download directory. {!Promise} A promise that will be resolved when the command has finished.
See Also
#sendDevToolsCommand
method setFileDetector
setFileDetector: () => void;
This function is a no-op as file detectors are not supported by this implementation.
Modifiers
@override
method setNetworkConditions
setNetworkConditions: (spec: { offline: boolean; latency: number; download_throughput: number; upload_throughput: number;}) => Promise<void>;
Schedules a command to set Chromium network emulation settings.
__Sample Usage:__
driver.setNetworkConditions({ offline: false, latency: 5, // Additional latency (ms). download_throughput: 500 * 1024, // Maximal aggregated download throughput. upload_throughput: 500 * 1024 // Maximal aggregated upload throughput. });
Parameter spec
Defines the network conditions to set {!Promise} A promise that will be resolved when network emulation settings are set.
method setPermission
setPermission: ( name: string, state: 'granted' | 'denied' | 'prompt') => Promise<object>;
Set a permission state to the given value.
Parameter name
A name of the permission to update.
Parameter state
State to set permission to.
Returns
{!Promise} A promise that will be resolved when the command has finished.
See Also
<https://w3c.github.io/permissions/#permission-registry> for valid names
method startCastTabMirroring
startCastTabMirroring: (deviceName: string) => Promise<void>;
Initiates tab mirroring for the current browser tab on the specified device.
Parameter deviceName
name of the target device. {!promise.Thenable} A promise that will be resolved when the mirror command has been issued to the device.
method startDesktopMirroring
startDesktopMirroring: (deviceName: string) => Promise<void>;
Initiates desktop mirroring for the current browser tab on the specified device.
Parameter deviceName
name of the target device. {!promise.Thenable} A promise that will be resolved when the mirror command has been issued to the device.
method stopCasting
stopCasting: (deviceName: string) => Promise<void>;
Stops casting from media router to the specified device, if connected.
Parameter deviceName
name of the target device. {!promise.Thenable} A promise that will be resolved when the stop command has been issued to the device.
class Extensions
class Extensions {}
A list of extensions to install when launching the browser.
constructor
constructor();
property length
length: number;
{number} The length of the extensions list.
method add
add: (...args: Array<string | Buffer>) => void;
Add additional extensions to install when launching the browser. Each extension should be specified as the path to the packed CRX file, or a Buffer for an extension.
Parameter args
The extensions to add.
class Options
class Options extends webdriver.Capabilities {}
Class for managing WebDriver options specific to a Chromium-based browser.
constructor
constructor(other?: object | webdriver.Capabilities | Map<string, any>);
Parameter other
Another set of capabilities to initialize this instance from.
method addArguments
addArguments: (...args: string[]) => Options;
Add additional command line arguments to use when launching the browser. Each argument may be specified with or without the "--" prefix (e.g. "--foo" and "foo"). Arguments with an associated value should be delimited by an "=": "foo=bar".
Parameter args
The arguments to add. {!Options} A self reference.
method addExtensions
addExtensions: (...args: Array<string | Buffer>) => Options;
Add additional extensions to install when launching the browser. Each extension should be specified as the path to the packed CRX file, or a Buffer for an extension.
Parameter args
The extensions to add. {!Options} A self reference.
method androidActivity
androidActivity: (name: string) => Options;
Sets the name of the activity hosting a Chrome-based Android WebView. This option must be set to connect to an [Android WebView]( https://chromedriver.chromium.org/getting-started/getting-started---android)
Parameter name
The activity name. {!Options} A self reference.
method androidDeviceSerial
androidDeviceSerial: (serial: string) => Options;
Sets the device serial number to connect to via ADB. If not specified, the WebDriver server will select an unused device at random. An error will be returned if all devices already have active sessions.
Parameter serial
The device serial number to connect to. {!Options} A self reference.
method androidPackage
androidPackage: (pkg: string | null) => Options;
Sets the package name of the Chrome or WebView app.
Parameter pkg
The package to connect to, or
null
to disable Android and switch back to using desktop browser. {!Options} A self reference.
method androidProcess
androidProcess: (processName: string) => Options;
Sets the process name of the Activity hosting the WebView (as given by
ps
). If not specified, the process name is assumed to be the same as .Parameter processName
The main activity name. {!Options} A self reference.
method androidUseRunningApp
androidUseRunningApp: (useRunning: boolean) => Options;
Sets whether to connect to an already-running instead of the specified instead of launching the app with a clean data directory.
Parameter useRunning
Whether to connect to a running instance. {!Options} A self reference.
method debuggerAddress
debuggerAddress: (address: string) => Options;
Sets the address of a Chromium remote debugging server to connect to. Address should be of the form "{hostname|IP address}:port" (e.g. "localhost:9222").
Parameter address
The address to connect to. {!Options} A self reference.
method detachDriver
detachDriver: (detach: boolean) => Options;
Sets whether to leave the started browser process running if the controlling driver service is killed before is called.
Parameter detach
Whether to leave the browser running if the driver service is killed before the session. {!Options} A self reference.
method enableBidi
enableBidi: () => webdriver.Capabilities;
Enable bidi connection
Returns
{!Capabilities}
method excludeSwitches
excludeSwitches: (...args: string[]) => Options;
List of Chrome command line switches to exclude that ChromeDriver by default passes when starting Chrome. Do not prefix switches with "--".
Parameter args
The switches to exclude. {!Options} A self reference.
method setBinaryPath
setBinaryPath: (path: string) => Options;
Sets the path to the browser binary to use. On Mac OS X, this path should reference the actual Chromium executable, not just the application binary (e.g. "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome").
The binary path can be absolute or relative to the WebDriver server executable, but it must exist on the machine that will launch the browser.
Parameter path
The path to the browser binary to use. {!Options} A self reference.
method setBrowserLogFile
setBrowserLogFile: (path: string) => Options;
Sets the path to the browser's log file. This path should exist on the machine that will launch the browser.
Parameter path
Path to the log file to use. {!Options} A self reference.
method setBrowserMinidumpPath
setBrowserMinidumpPath: (path: string) => Options;
Sets the directory to store browser minidumps in. This option is only supported when the driver is running on Linux.
Parameter path
The directory path. {!Options} A self reference.
method setLocalState
setLocalState: (state: object) => Options;
Sets preferences for the "Local State" file in Chrome's user data directory.
Parameter state
Dictionary of local state preferences. {!Options} A self reference.
method setMobileEmulation
setMobileEmulation: ( config?: | { deviceName: string } | { width: number; height: number; pixelRatio: number }) => Options;
Configures the browser to emulate a mobile device. For more information, refer to the ChromeDriver project page on [mobile emulation][em]. Configuration options include:
-
deviceName
: The name of a pre-configured [emulated device][devem] -width
: screen width, in pixels -height
: screen height, in pixels -pixelRatio
: screen pixel ratio__Example 1: Using a Pre-configured Device__
let options = new chrome.Options().setMobileEmulation( {deviceName: 'Google Nexus 5'});
let driver = chrome.Driver.createSession(options);
__Example 2: Using Custom Screen Configuration__
let options = new chrome.Options().setMobileEmulation({deviceMetrics: { width: 360, height: 640, pixelRatio: 3.0 }});
let driver = chrome.Driver.createSession(options);
[em]: https://chromedriver.chromium.org/mobile-emulation [devem]: https://developer.chrome.com/devtools/docs/device-mode
Parameter config
The mobile emulation configuration, or
null
to disable emulation. {!Options} A self reference.
method setPerfLoggingPrefs
setPerfLoggingPrefs: (prefs: { enableNetwork: boolean; enablePage: boolean; enableTimeline: boolean; traceCategories: string; bufferUsageReportingInterval: number;}) => Options;
Sets the performance logging preferences. Options include:
-
enableNetwork
: Whether or not to collect events from Network domain. -enablePage
: Whether or not to collect events from Page domain. -enableTimeline
: Whether or not to collect events from Timeline domain. Note: when tracing is enabled, Timeline domain is implicitly disabled, unlessenableTimeline
is explicitly set to true. -traceCategories
: A comma-separated string of Chromium tracing categories for which trace events should be collected. An unspecified or empty string disables tracing. -bufferUsageReportingInterval
: The requested number of milliseconds between DevTools trace buffer usage events. For example, if 1000, then once per second, DevTools will report how full the trace buffer is. If a report indicates the buffer usage is 100%, a warning will be issued.Parameter prefs
The performance logging preferences. {!Options} A self reference.
method setUserPreferences
setUserPreferences: (prefs: object) => Options;
Sets the user preferences for Chrome's user profile. See the "Preferences" file in Chrome's user data directory for examples.
Parameter prefs
Dictionary of user preferences to use. {!Options} A self reference.
method windowSize
windowSize: ({ width, height }: { width: number; height: number }) => Options;
Sets the initial window size.
Parameter size
The desired window size. {!Options} A self reference.
Throws
{TypeError} if width or height is unspecified, not a number, or less than or equal to 0.
method windowTypes
windowTypes: (...args: string[]) => Options;
Sets a list of the window types that will appear when getting window handles. For access to elements, include "webview" in the list.
Parameter args
The window types that will appear when getting window handles. {!Options} A self reference.
class ServiceBuilder
class ServiceBuilder extends remote.DriverService.Builder {}
Creates instances that manage a WebDriver server in a child process.
constructor
constructor(exe?: string);
Parameter exe
Path to the server executable to use. Subclasses should ensure a valid path to the appropriate exe is provided.
method enableChromeLogging
enableChromeLogging: () => ServiceBuilder;
Enables Chrome logging.
Returns
{!ServiceBuilder} A self reference.
method enableVerboseLogging
enableVerboseLogging: () => ServiceBuilder;
Enables verbose logging. {!ServiceBuilder} A self reference.
method loggingTo
loggingTo: (path: string) => ServiceBuilder;
Sets the path of the log file the driver should log to. If a log file is not specified, the driver will log to stderr.
Parameter path
Path of the log file to use. {!ServiceBuilder} A self reference.
method setAdbPort
setAdbPort: (port: number) => ServiceBuilder;
Sets which port adb is listening to. _The driver will connect to adb if an is requested, but adb **must** be started beforehand._
Parameter port
Which port adb is running on. {!ServiceBuilder} A self reference.
method setNumHttpThreads
setNumHttpThreads: (n: number) => ServiceBuilder;
Sets the number of threads the driver should use to manage HTTP requests. By default, the driver will use 4 threads.
Parameter n
The number of threads to use. {!ServiceBuilder} A self reference.
method setPath
setPath: (path: string) => any;
Modifiers
@override
namespace error
namespace error {}
Typings for lib/error
variable ErrorCode
const ErrorCode: ErrorCodeType;
function checkLegacyResponse
checkLegacyResponse: (response: MaybeLegacyResponse) => MaybeLegacyResponse;
Checks a legacy response from the Selenium 2.0 wire protocol for an error.
function checkResponse
checkResponse: (data: Response) => Response;
Checks a response object from a server that adheres to the W3C WebDriver protocol.
function encodeError
encodeError: (err: any) => { error: string; message: string };
Lookup the err in table of errors.
function throwDecodedError
throwDecodedError: (data: ErrorData | string) => never;
Throws an error coded from the W3C protocol. A generic error will be thrown if the provided
data
is not a valid encoded error.
class ElementClickInterceptedError
class ElementClickInterceptedError extends WebDriverError {}
Indicates a could not completed because the click target is obscured by other elements on the page.
constructor
constructor(message?: string);
class ElementNotInteractableError
class ElementNotInteractableError extends WebDriverError {}
Indicates a command could not be completed because the target element is not pointer or keyboard interactable. This will often occur if an element is present in the DOM, but not rendered (i.e. its CSS style has "display: none").
constructor
constructor(message?: string);
class ElementNotSelectableError
class ElementNotSelectableError extends WebDriverError {}
An attempt was made to select an element that cannot be selected.
constructor
constructor(message?: string);
class IError
class IError extends Error {}
constructor
constructor(message?: string);
property message
message: string;
class InsecureCertificateError
class InsecureCertificateError extends WebDriverError {}
Indicates a navigation event caused the browser to generate a certificate warning. This is usually caused by an expired or invalid TLS certificate.
constructor
constructor(message?: string);
class InvalidArgumentError
class InvalidArgumentError extends WebDriverError {}
The arguments passed to a command are either invalid or malformed.
constructor
constructor(message?: string);
class InvalidCookieDomainError
class InvalidCookieDomainError extends WebDriverError {}
An illegal attempt was made to set a cookie under a different domain than the current page.
constructor
constructor(message?: string);
class InvalidCoordinatesError
class InvalidCoordinatesError extends WebDriverError {}
The coordinates provided to an interactions operation are invalid.
constructor
constructor(message?: string);
class InvalidElementStateError
class InvalidElementStateError extends WebDriverError {}
An element command could not be completed because the element is in an invalid state, e.g. attempting to click an element that is no longer attached to the document.
constructor
constructor(message?: string);
class InvalidSelectorError
class InvalidSelectorError extends WebDriverError {}
Argument was an invalid selector.
constructor
constructor(message?: string);
class JavascriptError
class JavascriptError extends WebDriverError {}
An error occurred while executing JavaScript supplied by the user.
constructor
constructor(message?: string);
class MoveTargetOutOfBoundsError
class MoveTargetOutOfBoundsError extends WebDriverError {}
The target for mouse interaction is not in the browser’s viewport and cannot be brought into that viewport.
constructor
constructor(message?: string);
class NoSuchAlertError
class NoSuchAlertError extends WebDriverError {}
An attempt was made to operate on a modal dialog when one was not open.
constructor
constructor(message?: string);
class NoSuchCookieError
class NoSuchCookieError extends WebDriverError {}
Indicates a named cookie could not be found in the cookie jar for the currently selected document.
constructor
constructor(message?: string);
class NoSuchElementError
class NoSuchElementError extends WebDriverError {}
An element could not be located on the page using the given search parameters.
constructor
constructor(message?: string);
class NoSuchFrameError
class NoSuchFrameError extends WebDriverError {}
A request to switch to a frame could not be satisfied because the frame could not be found.
constructor
constructor(message?: string);
class NoSuchSessionError
class NoSuchSessionError extends WebDriverError {}
Occurs when a command is directed to a session that does not exist.
constructor
constructor(message?: string);
class NoSuchWindowError
class NoSuchWindowError extends WebDriverError {}
A request to switch to a window could not be satisfied because the window could not be found.
constructor
constructor(message?: string);
class ScriptTimeoutError
class ScriptTimeoutError extends WebDriverError {}
A script did not complete before its timeout expired.
constructor
constructor(message?: string);
class SessionNotCreatedError
class SessionNotCreatedError extends WebDriverError {}
A new session could not be created.
constructor
constructor(message?: string);
class StaleElementReferenceError
class StaleElementReferenceError extends WebDriverError {}
An element command failed because the referenced element is no longer attached to the DOM.
constructor
constructor(message?: string);
class TimeoutError
class TimeoutError extends WebDriverError {}
An operation did not completErrorCodee before its timeout expired.
constructor
constructor(message?: string);
class UnableToCaptureScreenError
class UnableToCaptureScreenError extends WebDriverError {}
A screen capture operation was not possible.
constructor
constructor(message?: string);
class UnableToSetCookieError
class UnableToSetCookieError extends WebDriverError {}
A request to set a cookie’s value could not be satisfied.
constructor
constructor(message?: string);
class UnexpectedAlertOpenError
class UnexpectedAlertOpenError extends WebDriverError {}
A modal dialog was open, blocking this operation.
constructor
constructor(message?: string, openAlertText?: string);
method getAlertText
getAlertText: () => string;
{(string|undefined)} The text displayed with the unhandled alert, if available.
class UnknownCommandError
class UnknownCommandError extends WebDriverError {}
A command could not be executed because the remote end is not aware of it.
constructor
constructor(message?: string);
class UnknownMethodError
class UnknownMethodError extends WebDriverError {}
The requested command matched a known URL but did not match an method for that URL.
constructor
constructor(message?: string);
class UnsupportedOperationError
class UnsupportedOperationError extends WebDriverError {}
Reports an unsupport operation.
constructor
constructor(message?: string);
class WebDriverError
class WebDriverError extends IError {}
The base WebDriver error type. This error type is only used directly when a more appropriate category is not defined for the offending error.
constructor
constructor(message?: string);
property remoteStacktrace
remoteStacktrace?: string;
interface ErrorCodeType
interface ErrorCodeType {}
index signature
[key: string]: number;
interface ErrorData
interface ErrorData {}
property error
error: string | number;
property message
message: string;
index signature
[key: string]: string | number;
interface MaybeLegacyResponse
interface MaybeLegacyResponse {}
property message
message?: string | undefined;
property status
status?: number | undefined;
property value
value?: { message: string } | undefined;
method getAlertText
getAlertText: () => string;
namespace logging
module 'lib/logging.d.ts' {}
Defines a message level that may be used to control logging output.
variable Type
const Type: IType;
Common log types.
function addConsoleHandler
addConsoleHandler: (opt_logger?: Logger) => void;
Adds the console handler to the given logger. The console handler will log all messages using the JavaScript Console API.
Parameter opt_logger
The logger to add the handler to; defaults to the root logger.
function getLevel
getLevel: (nameOrValue: string | number) => Level;
Converts a level name or value to a logging.Level value. If the name/value is not recognized, logging.Level.ALL will be returned.
Parameter nameOrValue
The log level name, or value, to convert . {!logging.Level} The converted level.
function getLogger
getLogger: (name?: string) => Logger;
Retrieves a named logger, creating it in the process. This function will implicitly create the requested logger, and any of its parents, if they do not yet exist.
Parameter name
the logger's name. {!Logger} the requested logger.
function installConsoleHandler
installConsoleHandler: () => void;
Installs the console log handler on the root logger.
function removeConsoleHandler
removeConsoleHandler: (opt_logger?: Logger) => void;
Removes the console log handler from the given logger.
Parameter opt_logger
The logger to remove the handler from; defaults to the root logger.
See Also
exports.addConsoleHandler
class Entry
class Entry {}
A single log entry.
constructor
constructor( level: string | number | Level, message: string, opt_timestamp?: number, opt_type?: string | IType);
Parameter level
The entry level.
Parameter message
The log message.
Parameter opt_timestamp
The time this entry was generated, in milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the current time will be used.
Parameter opt_type
The log type, if known.
property level
level: Level;
property message
message: string;
property timestamp
timestamp: number;
property type
type: string;
method toJSON
toJSON: () => IEntryJSON;
{{level: string, message: string, timestamp: number, type: string}} The JSON representation of this entry.
class Level
class Level {}
Defines a message level that may be used to control logging output.
constructor
constructor(name: string, level: number);
Parameter name
the level's name.
Parameter level
the level's numeric value.
property ALL
static ALL: Level;
Indicates all log messages should be recorded.
property DEBUG
static DEBUG: Level;
Log messages with a level of
700
or higher.
property FINE
static FINE: Level;
Log messages with a level of
500
or higher.
property FINER
static FINER: Level;
Log messages with a level of
400
or higher.
property FINEST
static FINEST: Level;
Log messages with a level of
300
or higher.
property INFO
static INFO: Level;
Log messages with a level of
800
or higher.
property name
name: string;
This logger's name.
property name_
name_: string;
property OFF
static OFF: Level;
Indicates no log messages should be recorded.
property SEVERE
static SEVERE: Level;
Log messages with a level of
1000
or higher.
property value
value: number;
The numeric log level.
property value_
value_: number;
property WARNING
static WARNING: Level;
Log messages with a level of
900
or higher.
method toString
toString: () => string;
Modifiers
@override
class Logger
class Logger {}
An object used to log debugging messages. Loggers use a hierarchical, dot-separated naming scheme. For instance, 'foo' is considered the parent of the 'foo.bar' and an ancestor of 'foo.bar.baz'.
Each logger may be assigned a , which controls which level of messages will be reported to the attached to this instance. If a log level is not explicitly set on a logger, it will inherit its parent.
This class should never be directly instantiated. Instead, users should obtain logger references using the function.
constructor
constructor(name: string, opt_level?: Level);
Parameter name
the name of this logger.
Parameter opt_level
the initial level for this logger.
property handlers_
handlers_: any;
property level_
level_: Level;
property name_
name_: string;
property parent_
parent_: Logger;
method addHandler
addHandler: (handler: any) => void;
Adds a handler to this logger. The handler will be invoked for each message logged with this instance, or any of its descendants.
Parameter handler
the handler to add.
method debug
debug: (loggable: string | Function) => void;
Logs a message at the Level.DEBUG log level.
Parameter loggable
the message to log, or a function that will return the message.
method fine
fine: (loggable: string | Function) => void;
Logs a message at the Level.FINE log level.
Parameter loggable
the message to log, or a function that will return the message.
method finer
finer: (loggable: string | Function) => void;
Logs a message at the Level.FINER log level.
Parameter loggable
the message to log, or a function that will return the message.
method finest
finest: (loggable: string | Function) => void;
Logs a message at the Level.FINEST log level.
Parameter loggable
the message to log, or a function that will return the message.
method getEffectiveLevel
getEffectiveLevel: () => Level;
{!Level} the effective level for this logger.
method getLevel
getLevel: () => Level;
{Level} the log level for this logger.
method getName
getName: () => string;
{string} the name of this logger.
method info
info: (loggable: string | Function) => void;
Logs a message at the Level.INFO log level.
Parameter loggable
the message to log, or a function that will return the message.
method isLoggable
isLoggable: (level: Level) => boolean;
Parameter level
the level to check. {boolean} whether messages recorded at the given level are loggable by this instance.
method log
log: (level: Level, loggable: string | Function) => void;
Logs a message at the given level. The message may be defined as a string or as a function that will return the message. If a function is provided, it will only be invoked if this logger's includes the given
level
.Parameter level
the level at which to log the message.
Parameter loggable
the message to log, or a function that will return the message.
method removeHandler
removeHandler: (handler: any) => void;
Removes a handler from this logger.
Parameter handler
the handler to remove. {boolean} whether a handler was successfully removed.
method setLevel
setLevel: (level: Level) => void;
Parameter level
the new level for this logger, or
null
if the logger should inherit its level from its parent logger.
method severe
severe: (loggable: string | Function) => void;
Logs a message at the Level.SEVERE log level.
Parameter loggable
the message to log, or a function that will return the message.
method warning
warning: (loggable: string | Function) => void;
Logs a message at the Level.WARNING log level.
Parameter loggable
the message to log, or a function that will return the message.
class LogManager
class LogManager {}
Maintains a collection of loggers.
method createLogger_
createLogger_: (name: string, parent: Logger) => Logger;
Creates a new logger.
Parameter name
the logger's name.
Parameter parent
the logger's parent. {!Logger} the new logger.
method getLogger
getLogger: (name?: string) => Logger;
Retrieves a named logger, creating it in the process. This function will implicitly create the requested logger, and any of its parents, if they do not yet exist.
Parameter name
the logger's name. {!Logger} the requested logger.
class Preferences
class Preferences {}
Describes the log preferences for a WebDriver session.
constructor
constructor();
property prefs_
prefs_: Map<string, Level>;
method setLevel
setLevel: (type: string | IType, level: Level) => void;
Sets the desired logging level for a particular log type.
Parameter type
The log type.
Parameter level
The desired log level.
Throws
{TypeError} if
type
is not astring
.
method toJSON
toJSON: () => { [key: string]: string };
Converts this instance to its JSON representation. {!Object<string, string>} The JSON representation of this set of preferences.
interface IEntryJSON
interface IEntryJSON {}
interface IType
interface IType {}
property BROWSER
BROWSER: string;
Logs originating from the browser.
property CLIENT
CLIENT: string;
Logs from a WebDriver client.
property DRIVER
DRIVER: string;
Logs from a WebDriver implementation.
property PERFORMANCE
PERFORMANCE: string;
Logs related to performance.
property SERVER
SERVER: string;
Logs from the remote server.
namespace promise
namespace promise {}
promise
function checkedNodeCall
checkedNodeCall: <T>(fn: Function, ...varArgs: any[]) => Promise<T>;
Wraps a function that expects a node-style callback as its final argument. This callback expects two arguments: an error value (which will be null if the call succeeded), and the success value as the second argument. The callback will the resolve or reject the returned promise, based on its arguments.
function delayed
delayed: (ms: number) => Promise<void>;
Creates a promise that will be resolved at a set time in the future.
function filter
filter: <T, V>( arr: T[] | Promise<T[]>, fn: (element: T, index: number, array: T[]) => V, optSelf?: any) => Promise<V[]>;
Calls a function for each element in an array, and if the function returns true adds the element to a new array.
If the return value of the filter function is a promise, this function will wait for it to be fulfilled before determining whether to insert the element into the new array.
If the filter function throws or returns a rejected promise, the promise returned by this function will be rejected with the same reason. Only the first failure will be reported; all subsequent errors will be silently ignored.
function fullyResolved
fullyResolved: (value: any) => Promise<any>;
Returns a promise that will be resolved with the input value in a fully-resolved state. If the value is an array, each element will be fully resolved. Likewise, if the value is an object, all keys will be fully resolved. In both cases, all nested arrays and objects will also be fully resolved. All fields are resolved in place; the returned promise will resolve on and not a copy.
Warning: This function makes no checks against objects that contain cyclical references:
var value = {}; value['self'] = value; promise.fullyResolved(value); // Stack overflow.
function isPromise
isPromise: (value: any) => boolean;
Determines whether a should be treated as a promise. Any object whose 'then' property is a function will be considered a promise.
function map
map: <T, V>( arr: T[] | Promise<T[]>, fn: (self: any, type: T, index: number, array: T[]) => V, optSelf?: any) => Promise<V[]>;
Calls a function for each element in an array and inserts the result into a new array, which is used as the fulfillment value of the promise returned by this function.
If the return value of the mapping function is a promise, this function will wait for it to be fulfilled before inserting it into the new array.
If the mapping function throws or returns a rejected promise, the promise returned by this function will be rejected with the same reason. Only the first failure will be reported; all subsequent errors will be silently ignored.
function thenFinally
thenFinally: <R>(promise: any, callback: () => R | Promise<R>) => Promise<R>;
Registers a listener to invoke when a promise is resolved, regardless of whether the promise's value was successfully computed. This function is synonymous with the clause in a synchronous API:
// Synchronous API: try { doSynchronousWork(); } finally { cleanUp(); }
// Asynchronous promise API: doAsynchronousWork().finally(cleanUp);
__Note:__ similar to the clause, if the registered callback returns a rejected promise or throws an error, it will silently replace the rejection error (if any) from this promise:
try { throw Error('one'); } finally { throw Error('two'); // Hides Error: one }
let p = Promise.reject(Error('one')); promise.finally(p, function() { throw Error('two'); // Hides Error: one });
namespace until
module 'lib/until.d.ts' {}
Creates a condition that will wait until the input driver is able to switch to the designated frame. The target frame may be specified as
1. a numeric index into [window.frames](https://developer.mozilla.org/en-US/docs/Web/API/Window.frames) for the currently selected frame. 2. a , which must reference a FRAME or IFRAME element on the current page. 3. a locator which may be used to first locate a FRAME or IFRAME on the current page before attempting to switch to it.
Upon successful resolution of this condition, the driver will be left focused on the new frame.
Parameter frame
The frame identifier. {!Condition} A new condition.
function ableToSwitchToFrame
ableToSwitchToFrame: ( frame: number | WebElement | By | ByHash | ((webdriver: WebDriver) => WebElement)) => Condition<boolean>;
Creates a condition that will wait until the input driver is able to switch to the designated frame. The target frame may be specified as
1. a numeric index into [window.frames](https://developer.mozilla.org/en-US/docs/Web/API/Window.frames) for the currently selected frame. 2. a , which must reference a FRAME or IFRAME element on the current page. 3. a locator which may be used to first locate a FRAME or IFRAME on the current page before attempting to switch to it.
Upon successful resolution of this condition, the driver will be left focused on the new frame.
Parameter frame
The frame identifier. {!Condition} A new condition.
function alertIsPresent
alertIsPresent: () => Condition<Alert>;
Creates a condition that waits for an alert to be opened. Upon success, the returned promise will be fulfilled with the handle for the opened alert.
{!Condition<!./Alert>} The new condition.
function elementIsDisabled
elementIsDisabled: (element: WebElement) => WebElementCondition;
Creates a condition that will wait for the given element to be disabled.
Parameter element
The element to test. {!WebElementCondition} The new condition.
See Also
WebDriver#isEnabled
function elementIsEnabled
elementIsEnabled: (element: WebElement) => WebElementCondition;
Creates a condition that will wait for the given element to be enabled.
Parameter element
The element to test. {!WebElementCondition} The new condition.
See Also
WebDriver#isEnabled
function elementIsNotSelected
elementIsNotSelected: (element: WebElement) => WebElementCondition;
Creates a condition that will wait for the given element to be deselected.
Parameter element
The element to test. {!WebElementCondition} The new condition.
See Also
WebDriver#isSelected
function elementIsNotVisible
elementIsNotVisible: (element: WebElement) => WebElementCondition;
Creates a condition that will wait for the given element to be in the DOM, yet not visible to the user.
Parameter element
The element to test. {!WebElementCondition} The new condition.
See Also
WebDriver#isDisplayed
function elementIsSelected
elementIsSelected: (element: WebElement) => WebElementCondition;
Creates a condition that will wait for the given element to be selected.
Parameter element
The element to test. {!WebElementCondition} The new condition.
See Also
WebDriver#isSelected
function elementIsVisible
elementIsVisible: (element: WebElement) => WebElementCondition;
Creates a condition that will wait for the given element to become visible.
Parameter element
The element to test. {!WebElementCondition} The new condition.
See Also
WebDriver#isDisplayed
function elementLocated
elementLocated: (locator: Locator) => WebElementCondition;
Creates a condition that will loop until an element is with the given locator.
Parameter locator
The locator to use. {!WebElementCondition} The new condition.
function elementsLocated
elementsLocated: (locator: Locator) => Condition<WebElement[]>;
Creates a condition that will loop until at least one element is with the given locator.
Parameter locator
The locator to use. {!Condition.<!Array.<!WebElement>>} The new condition.
function elementTextContains
elementTextContains: ( element: WebElement, substr: string) => WebElementCondition;
Creates a condition that will wait for the given element's to contain the given substring.
Parameter element
The element to test.
Parameter substr
The substring to search for. {!WebElementCondition} The new condition.
See Also
WebDriver#getText
function elementTextIs
elementTextIs: (element: WebElement, text: string) => WebElementCondition;
Creates a condition that will wait for the given element's to match the given exactly.
Parameter element
The element to test.
Parameter text
The expected text. {!WebElementCondition} The new condition.
See Also
WebDriver#getText
function elementTextMatches
elementTextMatches: (element: WebElement, regex: RegExp) => WebElementCondition;
Creates a condition that will wait for the given element's to match a regular expression.
Parameter element
The element to test.
Parameter regex
The regular expression to test against. {!WebElementCondition} The new condition.
See Also
WebDriver#getText
function stalenessOf
stalenessOf: (element: WebElement) => Condition<boolean>;
Creates a condition that will wait for the given element to become stale. An element is considered stale once it is removed from the DOM, or a new page has loaded.
Parameter element
The element that should become stale. {!Condition} The new condition.
function titleContains
titleContains: (substr: string) => Condition<boolean>;
Creates a condition that will wait for the current page's title to contain the given substring.
Parameter substr
The substring that should be present in the page title. {!Condition.} The new condition.
function titleIs
titleIs: (title: string) => Condition<boolean>;
Creates a condition that will wait for the current page's title to match the given value.
Parameter title
The expected page title. {!Condition} The new condition.
function titleMatches
titleMatches: (regex: RegExp) => Condition<boolean>;
Creates a condition that will wait for the current page's title to match the given regular expression.
Parameter regex
The regular expression to test against. {!Condition.} The new condition.
function urlContains
urlContains: (substrUrl: string) => Condition<boolean>;
Creates a condition that will wait for the current page's url to contain the given substring.
Parameter substrUrl
The substring that should be present in the current URL. {!Condition} The new condition.
function urlIs
urlIs: (url: string) => Condition<boolean>;
Creates a condition that will wait for the current page's url to match the given value.
Parameter url
The expected page url. {!Condition} The new condition.
function urlMatches
urlMatches: (regex: RegExp) => Condition<boolean>;
Creates a condition that will wait for the current page's url to match the given regular expression.
Parameter regex
The regular expression to test against. {!Condition} The new condition.
Package Files (9)
Dependencies (2)
Dev Dependencies (0)
No dev dependencies.
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@types/selenium-webdriver
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@types/selenium-webdriver)
- HTML<a href="https://www.jsdocs.io/package/@types/selenium-webdriver"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 9249 ms. - Missing or incorrect documentation? Open an issue for this package.