API Reference

You can view reference information for browser testing APIs.

actions

This browser testing API function creates a new action sequence by using the WebDriver. The sequence is not submitted for execution until you call the Actions.perform() function in your code.

Usage

$browser.actions().sendKeys("synthetic").perform();

Parameters

Parameters Type Description
RETURN Actions New action sequence for this instance.
options Object Configuration options for the Actions sequence.

Examples

Example 1: To click, use the following code:

const element = await $browser.waitForAndFindElement(by, timeout);
$browser.actions().move({origin: element}).press().release().perform();

Example 2: To hover the mouse on a browser element, use the following code:

const element = await $browser.waitForAndFindElement(by, timeout);
$browser.actions().move({origin: element, duration: 2000}).perform();

To be compatible with the old mouseMove function, use the following command:

$browser.actions().mouseMove(element).perform();

Browser testing APIs support the $browser.actions().mouseMove() method for compatibility with an earlier version and implement the method with $browser.actions().move() because the method was removed by Selenium in 2021 in this PR.

Example 3: To send keys, run the following code:

await $browser.get("http://www.bing.com");
await $browser.actions().sendKeys("synthetic").perform();

addHeader

This browser testing API modifies header for HTTP requests.

Usage

$browser.addHeader(key: string, val: string): Promise<void>;

Parameters

Parameters Type Description
RETURN Promise<void> The returned value is a promise.
key string The HTTP Header name.
val string The HTTP Header value.

Examples

await $browser.addHeader(
  "User-Agent",
  "Mozilla/5.0 (iPhone; CPU OS 10_15_5 (Ergänzendes Update) like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Mobile/14E304 Safari/605.1.15"
);

await $browser.get("https://www.yahoo.com/");
await $browser.takeScreenshot();

await $browser.addHeader(
  "User-Agent",
  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.16; rv:86.0) Gecko/20100101 Firefox/86.0"
);

await $browser.get("https://www.yahoo.com/");
await $browser.takeScreenshot();

addHeaders

This browser testing API modifies header for HTTP requests.

Usage

$browser.addHeaders(headers: { [key: string]: string }): Promise<void>;

Parameters

Parameters Type Description
RETURN Promise<void> The returned value is a promise.
headers { [key: string]: string } HTTP Headers

Examples

await $browser.addHeaders({
  key1: "val1",
  key2: "val2",
});

addHostnamesToDenylist

This browser testing API adds hostnames to your deny list.

Usage

$browser.addHostnamesToDenylist(hostnameArr: string[]): Promise<void>

Instana provides the addHostnamesToDenylist funtion for URL filtering but doesn’t remove the addHostnamesToBlacklist function to ensure that the code is compatible with earlier versions.

$browser.addHostnamesToBlacklist(hostnameArr: string[]): Promise<void>

Parameters

Parameters Type Description
RETURN Promise<void> The returned value is a promise.
hostnameArr string[] Hostname to match and support wildcards

Examples

await $browser.addHostnamesToDenylist(["*.css", "*.png"]);
await $browser.addHostnamesToAllowlist(["*"]);

addHostnamesToAllowlist

This browser testing API adds hostnames to your allow list.

Usage

$browser.addHostnamesToAllowlist(hostnameArr: string[]): Promise<void>

Instana provides the addHostnamesToAllowlist function for URL filtering but doesn’t remove the addHostnamesToWhitelist function to ensure that the code is compatible with earlier versions.

$browser.addHostnamesToWhitelist(hostnameArr: string[]): Promise<void>

Parameters

Parameters Type Description
RETURN Promise<void> The returned value is a promise.
hostnameArr string[] Hostname to match and support wildcards.

Examples

await $browser.addHostnamesToDenylist(["*.css", "*.png"]);
await $browser.addHostnamesToAllowlist(["*"]);

addHostnameToDenylist

This browser testing API adds a hostname to your deny list.

Usage

$browser.addHostnameToDenylist(hostname: string): Promise<void>

Instana provides the addHostnameToDenylist function for URL filtering but doesn’t remove the addHostnameToBlacklist function to ensure that the code is compatible with earlier versions.

$browser.addHostnameToBlacklist(hostname: string): Promise<void>

Parameters

Parameters Type Description
RETURN Promise<void> The returned value is a promise.
hostname string The hostname to match and support wildcards

Examples

await $browser.addHostnameToDenylist(`*.css`);
await $browser.addHostnameToAllowlist(`*`);

addHostnameToAllowlist

This browser testing API adds a hostname to your allow list.

Usage

$browser.addHostnameToAllowlist(hostname: string): Promise<void>

Instana provides the addHostnameToAllowlist funtion for URL filtering but doesn’t remove the addHostnameToWhitelist function to ensure that the code is compatible with earlier versions.

$browser.addHostnameToWhitelist(hostname: string): Promise<void>

Parameters

Parameters Type Description
RETURN Promise<void> The returned value is a promise.
hostname string The hostname to match and support wildcards.

Examples

await $browser.addHostnameToDenylist(`*.css`);
await $browser.addHostnameToAllowlist(`*`);

clearProxy

This browser testing API clears or removes the current proxy configuration.

Usage

$browser.clearProxy(): Promise<void>;

deleteHeader

This browser testing API deletes user-defined header.

Usage

$browser.deleteHeader(key: string): Promise<void>;

Parameters

Parameters Type Description
RETURN Promise<void> A promise that will be resolved when this command completes.
key string The HTTP Header name.

Examples

await $browser.addHeader('header1-xxx', 'abcd');
await $browser.addHeaders({
    key1: 'val1',
    key2: 'val2',
});
await $browser.deleteHeaders(['key1']);

await $browser.get(`http://localhost:${devport}/header-test`);
let userHeaders: Map<string, any>  = $browser.getHeaders();
console.log("User customized headers: ", [...userHeaders]);
expect(userHeaders.size).toEqual(2);

deleteHeaders

This browser testing API deletes user-defined headers.

Usage

$browser.deleteHeaders: (header: string[]) => Promise<void>;

Parameters

Parameters Type Description
RETURN Promise<void> A promise that will be resolved when this command completes.
header string[] HTTP Header names.

Examples

await $browser.addHeader('header1-xxx', 'abcd');
await $browser.addHeaders({
    key1: 'val1',
    key2: 'val2',
});
await $browser.deleteHeaders(['key1']);

await $browser.get(`http://localhost:${devport}/header-test`);
let userHeaders: Map<string, any>  = $browser.getHeaders();
console.log("User customized headers: ", [...userHeaders]);
expect(userHeaders.size).toEqual(2);

deleteHostnameFromDenylist

This browser testing API deletes a hostname from your deny list.

Usage

$browser.deleteHostnameFromDenylist(hostname: string): Promise<void>;

Instana provides the deleteHostnameFromDenylist function for URL filtering but doesn’t remove the deleteHostnameFromBlacklist function to ensure that the code is compatible with earlier versions.

$browser.deleteHostnameFromBlacklist(hostname: string): Promise<void>;

Parameters

Parameters Type Description
RETURN Promise<void> The returned value is a promise.
hostname string The hostname to match and support wildcards.

deleteHostnameFromAllowlist

This browser testing APIs delete a hostname from your allow list.

Usage

$browser.deleteHostnameFromAllowlist(hostname: string): Promise<void>;

The code adds the deleteHostnameFromAllowlist function to the API but doesn’t remove the deleteHostnameFromWhitelist function to ensure that the code is compatible with earlier versions.

$browser.deleteHostnameFromWhitelist(hostname: string): Promise<void>;

Parameters

Parameters Type Description
RETURN Promise<void> The returned value is a promise.
hostname string The hostname to match and support wildcards.

deleteHostnamesFromDenylist

This browser testing API deletes hostnames from your deny list.

Usage

$browser.deleteHostnamesFromDenylist(hostnameArr: string[]): Promise<void>

Instana provides the deleteHostnamesFromDenylist function for URL filtering but doesn’t remove the deleteHostnamesFromBlacklist function to ensure that the code is compatible with earlier versions.

$browser.deleteHostnamesFromBlacklist(hostnameArr: string[]): Promise<void>

Parameters

Parameters Type Description
RETURN Promise<void> The returned value is a promise.
hostnameArr string[] The hostname to match and support wildcards.

deleteHostnamesFromAllowlist

This browser testing API deletes hostnames from your allow list.

Usage

$browser.deleteHostnamesFromAllowlist(hostnameArr: string[]): Promise<void>

Instana provides the deleteHostnamesFromAllowlist function for URL filtering but doesn’t remove the deleteHostnamesFromWhitelist function to ensure that the code is compatible with earlier versions.

$browser.deleteHostnamesFromWhitelist(hostnameArr: string[]): Promise<void>

Parameters

Parameters Type Description
RETURN Promise<void> The returned value is a promise.
hostnameArr string[] The hostname to match and support wildcards.

dollar-dollar

The $$ command is a shortcut to call the findElements command to fetch multiple elements on the page. The command returns an array with element results. These results have an extended prototype to call action commands.

You can chain $ or $$ together to navigate the DOM tree.

For more information about how to select specific elements, see the CSS Selectors.

Usage

$browser.$$(selector);

Parameters

Name Type Description
RETURN Promise<WebElement[]> The returned value is a promise that will be resolved with an array of WebElements.
selector String, Function The Selector or JavaScript function to fetch a certain element.

Examples

The index.html file is as follows:

<ul id="menu">
  <li><a href="/">Home</a></li>
  <li><a href="/">Developer Guide</a></li>
  <li><a href="/">API</a></li>
  <li><a href="/">Contribute</a></li>
</ul>

Use $$ to find elements as follows:

test("should get text a menu link", async () => {
  const menu = (await $browser.$$("#menu"))[0];
  const li = await menu.$$("li");

  console.log(await li[2].$("a").getText()); // outputs: "API"
});

test("should get text a menu link - JS Function", async () => {
  const text = (
    await $browser.$$(function () {
      // Arrow function is not allowed here.
      return document.querySelectorAll("#menu"); // Element[]
    })
  )[0];

  const li3Text = await (await text.$$("li"))[2].$("a").getText();
  console.log(li3Text); // outputs: "API"
});

dollar

The $ command is a shortcut to call the findElement command to fetch a single element on the page. The command returns an object. The object has an extended prototype to call action commands.

You can chain $ or $$ together to navigate the DOM tree.

For more information about how to select specific elements, see the CSS Selectors.

Usage

$browser.$(selector): WebElementPromise;

Parameters

Name Type Description
RETURN WebElementPromise The returned value is a WebElementPromise.
selector String, Function The Selector or JavaScript function to fetch multiple elements.

Examples

The index.html file is as follows:

<ul id="menu">
  <li><a href="/">Home</a></li>
  <li><a href="/">Developer Guide</a></li>
  <li><a href="/">API</a></li>
  <li><a href="/">Contribute</a></li>
</ul>

Use $ to find element as follows:

test("should get text a menu link", async () => {
  const text = await $browser.$("#menu").$$("li");
  console.log(await text[2].$("a").getText()); // outputs: "API"
});

test("should get text a menu link - JS Function", async () => {
  const text = await $browser.$(function () {
      // Arrow function is not allowed here.
      return document.querySelector("#menu"); // Element
    }).$$("li");

  console.log(text.$$("li")[2].$("a").getText()); // outputs: "API"
});

execute

This browser testing API runs the provided [Command] by using command.Executor of the WebDriver.

Usage

$browser.execute(command) => Promise<T>

Promise<T> is a promise that will be resolved with the command result.

Parameters

Parameter Type Description
command Command Command to schedule

executeAsyncScript

This browser testing API runs a snippet of asynchronous JavaScript in the context of the currently selected frame or window. The script fragment is run as the body of an anonymous function. If the script is provided as a function object, that function is converted to a string for injection into the target window.

If you provide any arguments in addition to the script, it is included as script arguments and can be referenced by using the arguments object. Arguments can be a Boolean, number, string, or WebElement. Arrays and objects can also be used as script arguments if each item adheres to the stated types.

Unlike running synchronous JavaScript with executeScript, scripts run with this function must explicitly signal that they are finished by starting the provided callback. This callback is always injected into the executed function as the last argument, and thus might be referenced with arguments[arguments.length - 1]. The following steps are taken for resolving this function's return value against the first argument to the script's callback function:

  • For an HTML element, the value resolves to a WebElement.
  • Null and undefined return values resolve to null.
  • Booleans, numbers, and strings resolve as is.
  • Functions resolve to their string representation.
  • For arrays and objects, each member item is converted according to the stated rules.

Usage

$browser.executeAsyncScript<T>(script: string|Function, ...var_args: any[]): Promise<T>;

Parameters

Parameters Type Description
RETURN Promise.<T> A promise that will be resolved with the script's return value.
script string, Function The script to run.
...args * The arguments to pass to the script.

Examples

Example 1: To perform a sleep that is synchronized with the currently selected window, use the commands as shown in the following example:

const start = new Date().getTime();
$browser.executeAsyncScript(
    "window.setTimeout(arguments[arguments.length - 1], 500);"
  ).then(function () {
    console.log("Elapsed time: " + (new Date().getTime() - start) + " ms");
  });

Example 2: To synchronize a test with an Ajax application, use the commands as shown in the following example:

const button = $browser.$("#compose-button");
button.click();
$browser.executeAsyncScript(
  "var callback = arguments[arguments.length - 1];" +
    "mailClient.getComposeWindowWidget().onload(callback);"
);
$browser.switchTo().frame("composeWidget");
$browser.$("#to").sendKeys("dog@example.com");

Example 3: To inject XMLHttpRequest and wait for the result, use the following commands. In this example, the inject script is specified with a function literal. When you use this format, the function is converted to a string for injection. So the function must not reference any symbols that are not defined in the scope of the page under test.

$browser.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"]);
  });

executeScript

This browser testing API runs a snippet of JavaScript in the context of the currently selected frame or window. The script fragment is run as the body of an anonymous function. If you provide the script as a function object, that function is converted to a string for injection into the target window.

If you provide any arguments in addition to the script, it is included as script arguments and might be referenced by using the arguments object. Arguments can be a Boolean, number, string, or WebElement. Arrays and objects can also be used as script arguments if each item adheres to the stated types.

The script might refer to any variables accessible from the current window. Furthermore, the script runs in the window's context, thus document might be used to refer to the current document. No local variables are available after the script finishes running, though global variables persist.

If the script has a return value, that is, if the script contains a return statement, then the following steps are taken for resolving this function's return value:

  • For an HTML element, the value resolves to a WebElement.
  • Null and undefined return values resolve to null.
  • Booleans, numbers, and strings resolve as is.
  • Functions resolve to their string representation.
  • For arrays and objects, each member item is converted according to the stated rules.

Usage

$browser.executeScript<T>(script: string|Function, ...var_args: any[]): Promise<T>;

Parameters

Parameters Type Description
RETURN Promise.<T> A promise that will be resolved with the script's return value.
script string, Function The script to run.
...args * The arguments to pass to the script.

findElement

This browser testing API locates an element on the page. If the element cannot be found, the driver returns error.NoSuchElementError.

Usage

$browser.findElement(locator: Locator): WebElementPromise;

Parameters

Parameters Type Description
RETURN WebElementPromise A WebElement that can be used to issue commands against the located element. If the element is not found, the element is invalidated and all scheduled commands are stopped.
locator By, function The locator to use.

Examples

You must not use this function to test whether an element is present on the page. Instead, you must use findElements:

$browser.findElements($driver.By.id("foo"))
  .then((found) => console.log("Element found? %s", !!found.length));

You can define the search criteria for an element by 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 = $browser.findElement($driver.By.id("foo"));
var e2 = $browser.findElement({ id: "foo" });

You can also provide a custom locator function, which takes as input this instance and returns a WebElement, or a promise that will be resolved with a WebElement. If the returned promise resolves with an array of WebElements, WebDriver uses the first element. For example, to find the first visible link on a page, you can use the following commands:

var link = $browser.findElement(firstVisibleLink);

function firstVisibleLink(driver) {
  var links = driver.findElements(By.tagName("a"));
  return promise.filter(links, function (link) {
    return link.isDisplayed();
  });
}

findElements

This browser testing API searches for multiple elements on the page. For information about element locator strategies, see findElement.

Usage

$browser.findElements(locator: Locator): Promise<WebElement[]>;

Parameters

Parameters Type Description
RETURN Promise<WebElement[]> A promise that will be resolved with an array of WebElements.
locator By, function The locator to use.

generateTOTPToken

This browser testing API generates a time-based one-time password (TOTP) token from a TOTP key. You can use this API to log in with two-factor authentication.

Usage

$browser.generateTOTPToken(key: string, options?: TOTPOptions): string;

Parameters

Parameter Type Description
RETURN string A time-based one-time password (TOTP) token
key string A TOTP key, base32 strings
options Object,undefined Optional: optional settings e.g. {digits: 8, algorithm: "SHA-512", period: 60}. The default settings are {digits: 6, algorithm: "SHA-1", period: 30}

Examples

Example 1: To generate a TOTP token and log in with two-factor authentication in Browser Script test:

await $browser.waitForAndFindElement($driver.By.id("password"), 15000);

let totp_token = $browser.generateTOTPToken($secure.totpKey);

await $browser.findElement($driver.By.id("password")).then((element) => {
  return element.clear().then(() => {
    return element.sendKeys(totp_token);
  });
});

Example 2: To generate a TOTP token in Selenium SIDE script test:

{
  "id": "ec51296b-4d16-4167-ac83-ba87f89cc0c7",
  "comment": "Generate a TOTP token from a TOTP key",
  "command": "executeScript",
  "target": "return $browser.generateTOTPToken($secure.totpKey);",
  "targets": [],
  "value": "totpToken"
}

get

This browser testing API goes to a URL.

Usage

$browser.get(url: string): Promise<void>;

Parameters

Parameters Type Description
RETURN Promise<void> A promise that will be resolved when the document finishes loading.
url string The fully qualified URL to open.

getAllWindowHandles

This browser testing API schedules a command to retrieve the current list of available window handles.

Usage

$browser.getAllWindowHandles(): Promise<string[]>;

Parameters

Parameter Type Description
RETURN Promise<string[]> A promise that will be resolved with an array of window handles.

getCapabilities

This browser testing API gets this instance's capabilities.

Usage

$browser.getCapabilities(): Promise<Capabilities>;

Parameters

Parameter Type Description
RETURN Promise<Capabilities> A promise that will be resolved with this instance's capabilities.

getCurrentUrl

This browser testing API schedules a command to retrieve the URL of the current page.

Usage

$browser.getCurrentUrl(): Promise<string>;

Parameters

Parameter Type Description
RETURN Promise<string> A promise that will be resolved with the current URL.

getHeaders

This browser testing API gets user customized headers.

Usage

$browser.getHeaders(): Map<string, any>;

Parameters

Parameter Type Description
RETURN Map<string, any> User-defined headers

Examples

await $browser.addHeader('header1-xxx', 'abcd');
await $browser.addHeaders({
    key1: 'val1',
    key2: 'val2',
});
await $browser.deleteHeaders(['key1']);

await $browser.get(`http://localhost:${devport}/header-test`);
let userHeaders: Map<string, any>  = $browser.getHeaders();
console.log("User customized headers: ", [...userHeaders]);
expect(userHeaders.size).toEqual(2);

getPageSource

This browser testing API retrieves the current page's source. The returned source is a representation of the underlying DOM. Do not expect the source to be formatted or escaped in the same way as the raw response sent from the web server.

Usage

$browser.getPageSource(): Promise<string>;

Parameters

Parameter Type Description
RETURN Promise<string> A promise that will be resolved with the current page source.

getProxy

This browser testing API retrieves the current proxy configuration.

Usage

$browser.getProxy(): FFProxyConfig | CProxyConfig;

This API can also be called through the $network object:

$network.getProxy(): FFProxyConfig | CProxyConfig;

Parameters

Parameter Type Description
RETURN CProxyConfig or FFProxyConfig Proxy config object in Chrome or Firefox specific encapsulation.

Proxy configuration

/**
 * Firefox extension - An object encapsulating a complete proxy configuration
 * https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/proxy/settings
 */
export interface FFProxyConfig {
  proxyType?: FFProxyType,
  http?: string;
  ssl?: string,
  ftp?: string;
  autoConfigUrl?: string,
  autoLogin?: boolean,
  httpProxyAll?: boolean,
  passthrough?: string,
  proxyDNS?: boolean,
  socks?: string,
  socksVersion?: number,
}

/**
 * Chrome extension - An object encapsulating a complete proxy configuration
 * https://developer.chrome.com/docs/extensions/reference/proxy/#type-ProxyConfig
 */
export interface CProxyConfig {
  mode: CProxyType,
  rules?: {
    bypassList?: string[],
    fallbackProxy?: ProxyServer,
    proxyForFtp?: ProxyServer,
    proxyForHttp?: ProxyServer,
    proxyForHttps?: ProxyServer,
    singleProxy?: ProxyServer,
  },
  pacScript?: {
    data?: string,
    mandatory?: boolean,
    url?: string,
  },
};

getSession

This browser testing API retrieves this client's session.

Usage

$browser.getSession(): Promise<Session>;

Parameters

Parameter Type Description
RETURN Promise<Session> A promise for this client's session.

getTitle

This browser testing API schedules a command to retrieve the current page's title.

Usage

$browser.getTitle(): Promise<string>;

Parameters

Parameter Type Description
RETURN Promise<string> A promise that will be resolved with the current page's title.

getWindowHandle

This browser testing API schedules a command to retrieve the current window handle.

Usage

$browser.getWindowHandle(): Promise<string>;

Parameters

Parameter Type Description
RETURN Promise<string> A promise that will be resolved with the current window handle.

manage

This browser testing API gets the options interface for this instance.

Usage

$browser.manage(): Options;

Parameters

Parameter Type Description
RETURN Options The options interface for this instance.

Options

The options provide methods for managing browser and driver state.

Type Description
addCookie(spec: IWebDriverOptionsCookie): Promise<void> Schedules a command to add a cookie.
deleteAllCookies(): Promise<void>; Schedules a command to delete all cookies visible to the current page.
deleteCookie(name: string): Promise<void>; Schedules a command to delete the cookie with the given name. If no cookie with the given name visible to the current page, then this command is a no-op.
getCookies(): Promise<IWebDriverCookie[]>; Schedules a command to retrieve all cookies visible to the current page. Each cookie is returned as a JSON object as described by the WebDriver wire protocol.
getCookie(name: string): Promise<IWebDriverCookie>; Schedules a command to retrieve the cookie with the given name. Returns null if no such cookie is available. The cookie is returned as a JSON object, as described by the WebDriver wire protocol.
logs(): Logs; Provides the interface for managing driver logs.
getTimeouts(): Promise<ITimeouts>; Gets the current timeouts.
setTimeouts(timeouts: ITimeouts): Promise<void>; Sets current timeouts.
window(): Window; Provides the interface for managing the current window.

IWebDriverCookie

Parameters Type Description
name string The name of the cookie.
value string The cookie value.
path string The cookie path. Defaults to "/" when a cookie is added.
domain string The domain the cookie is visible to. Defaults to the current browsing context's document's URL when a cookie is added.
secure boolean The parameter indicates whether the cookie is a secure cookie. The default value is false, which means that the cookie is not a secure cookie.
httpOnly boolean The parameter indicates whether the cookie is an HTTP only cookie. The default value is false, which means that the cookie is not an HTTP only cookie.
expiry number The expiry is always returned in seconds since epoch when retrieving cookies from the browser.

ITimeouts

Parameter Type Description
script number Specifies the maximum amount of time to wait for an evaluated script to run.
pageLoad number Specifies the maximum amount of time to wait for a page to finishing loading. Defaults to 300000 milliseconds.
implicit number Specifies the maximum amount of time to wait for an element locator to succeed when locating elements on the page. Defaults to 0 milliseconds.

Window

export interface ILocation {
  x: number;
  y: number;
}

export interface ISize {
  width: number;
  height: number;
}

export interface IRectangle {
  x: number;
  y: number;
  width: number;
  height: number;
}

An interface for managing the current window.

Type Description
getPosition(): Promise<ILocation>; Retrieves the window's current position, relative to the upper left of the screen.
setPosition(x: number, y: number): Promise<void>; Repositions the current window.
getSize(): Promise<ISize>; Retrieves the window's current size.
setSize(width: number, height: number): Promise<void>; Resizes the current window.
getRect(): Promise<IRectangle>; Returns the current top-level window's size and position.
setRect({x, y, width, height}: Partial<IRectangle>): Promise<IRectangle>; Sets the current top-level window's size and position. You can update just the size by omitting x and y or just the position by omitting width and height options.
maximize(): Promise<void>; Maximizes the current window.

Examples

let tm = await $browser.manage().getTimeouts();
console.log('current timeout', tm.implicit, tm.pageLoad, tm.script);

await $browser.manage().timeouts().pageLoadTimeout(119);
tm = await $browser.manage().getTimeouts();
expect(tm.pageLoad).toBe(119);
console.log('current timeout', tm.implicit, tm.pageLoad, tm.script);

await $browser.manage().timeouts().pageLoadTimeout(89);
tm = await $browser.manage().getTimeouts();
expect(tm.pageLoad).toBe(89);
console.log('current timeout', tm.implicit, tm.pageLoad, tm.script);

This browser testing API gets the navigation interface for this instance.

Usage

$browser.navigate(): Navigation;

Parameters

Parameter Type Description
RETURN Navigation The navigation interface for this instance.

The navigation interface for going back and forth in the browser history.

Type Description
to(url: string): Promise<void>; Schedules a command to go to a new URL.
back(): Promise<void>; Schedules a command to move backwards in the browser history.
forward(): Promise<void>; Schedules a command to move forwards in the browser history.
refresh(): Promise<void>; Schedules a command to refresh the current page.

setAuthentication

This browser testing API changes authentication settings for coming HTTP requests.

Usage

$browser.setAuthentication(authName: string, authPass: string): Promise<void>;

Parameters

Parameters Type Description
RETURN Promise<void> A promise is resolved when settings are applied.
authName string Username for authentication.
authPass string User password for authentication.

Examples

await $browser.setAuthentication(basicauthuser, password);
await $browser.get(`http://${httpserver}/basic/page1.html`)
.then(() => $browser.takeScreenshot());

setProxy

This browser testing API sets a proxy server to be used for all HTTP, HTTPS, and FTP requests.

Usage

$browser.setProxy(proxyURL: string | URL, noProxy?: string): Promise<void>;

This API can also be called through the $network object.

$network.setProxy(proxyURL: string | URL, noProxy?: string): Promise<void>

Parameters

Parameters Type Description
RETURN Promise<void> A promise is resolved when settings are applied.
proxyURL string, URL A URL string to connect to the proxy server. The URL string must be in a format as defined in the Node's url.parse(urlString) method. For example, http://proxy_host:8888 or https://user:pass@proxy_host:8888
noProxy string Optional: A comma-separated list of hosts that bypasses all proxies.

setProxyAdvanced

This browser testing API sets the proxy configuration by using the format that is supported by Chrome or Firefox Extension API for proxying.

Usage

$browser.setProxyAdvanced(proxyConfig: CProxyConfig | FFProxyConfig, authName?: string, authPass?: string): Promise<void>;

This API can also be called through the $network object.

$network.setProxyAdvanced(proxyConfig: CProxyConfig | FFProxyConfig, authName?: string, authPass?: string): Promise<void>;

Parameters

Parameter Type Description
RETURN Promise<void> A promise is resolved when settings are applied.
proxyConfig CProxyConfig or FFProxyConfig A proxy config object in Chrome or Firefox specific encapsulation.
authName string Optional: A username of the proxy server for authentication.
authPass string Optional: A user password of the proxy server for authentication.

Examples

async function testProxyAdvanced() {
  await $browser.clearProxy();
  var ffconfig = {
    proxyType: "manual",
    //proxyType: "autoConfig",
    http: proxy_4,
    ssl: proxy_4,
    ftp: proxy_4,
    autoConfigUrl: pacfile,
    passthrough: noproxy,
    autoLogin: true,
  }

  var pxyserver = {
    host: httpserver,
    port: 8088,
    scheme: "http",
  }

  var cconfig = {
    mode: "fixed_servers",
    rules: {
      bypassList: noproxy.split(','),
      fallbackProxy: {
        host: "my-proxy-server.us.ibm.com",
        port: 8080,
      },
      proxyForFtp: pxyserver,
      proxyForHttp: pxyserver,
      proxyForHttps: pxyserver,
    },
    pacScript: {
      url: pacfile,
    },
  }

  var bname = null;
  await $browser.getCapabilities().then(cap=> {
    bname = cap.getBrowserName();
   });

  var config = (bname == 'chrome') ? cconfig : ffconfig;

  await $browser.setProxyAdvanced(config, proxyuser, password);
  await $browser.get(`http://${httpserver}/demo/page2.html`)
    .then(() => $browser.takeScreenshot());
}

setProxyAuthentication

This browser testing API changes proxy authentication settings for coming HTTP, HTTPS, and FTP requests.

Usage

$browser.setProxyAuthentication(authName: string, authPass: string): Promise<void>;

Parameters

Parameters Type Description
RETURN Promise<void> A promise is resolved when settings are applied.
authName string A username of the proxy server for authentication.
authPass string A user password of the proxy server for authentication.

Examples

async function testProxyAuthentication() {
  await $browser.clearProxy();
  await $browser.setProxy(proxy_3, noproxy);
  await $browser.setProxyAuthentication(proxyuser, password);
  await $browser.get(`http://${httpserver}/demo/page2.html`)
    .then(() => $browser.takeScreenshot());
}

setProxyForHttp

This browser testing API sets a proxy server to be used for all HTTP requests.

Usage

$browser.setProxyForHttp(proxyURL: string | URL, noProxy?: string): Promise<void>

This API can also be called through the $network object.

$network.setProxyForHttp(proxyURL: string | URL, noProxy?: string): Promise<void>

Parameters

Parameter Type Description
RETURN Promise<void> A promise is resolved when settings are applied.
proxyURL string, URL A URL string to connect to the proxy server. The URL string must be in a format as defined in Node's url.parse(urlString) method. For example, http://proxy_host:8888 or https://user:pass@proxy_host:8888
noProxy string Optional: A comma-separated list of hosts that must bypass all proxies.

Examples

let website;
let proxyServer = "proxyHost:proxyPort";

console.log(">>>>>>>>>>>>>>>>>>>", "Clear proxy configuration");
await $network.clearProxy();
console.log(">>>>>>>>>>>>>>>>>>>", "Set proxy configuration for HTTP request");
await $network.setProxyForHttp(proxyServer);
website = await accessWebSite();
checkHostname("www.google.com.hk", website)

setProxyForHttps

This browser testing API sets a proxy server to be used for all HTTPS requests.

Usage

$browser.setProxyForHttps(proxyURL: string | URL, noProxy?: string): Promise<void>;

This API can also be called through the $network object.

$network.setProxyForHttps(proxyURL: string | URL, noProxy?: string): Promise<void>;

Parameters

Parameter Type Description
RETURN Promise<void> A promise is resolved when settings are applied
proxyURL string, URL A URL string to connect to the proxy server. The URL string must be in a format as defined in the Node's url.parse(urlString) method. For example, http://proxy_host:8888 or https://user:pass@proxy_host:8888
noProxy string Optional: A comma-separated list of hosts that must bypass all proxies.

Examples

let website;
let sslProxyServer = "username:password@proxyHost:proxyPort";

console.log(">>>>>>>>>>>>>>>>>>>", "Clear proxy configuration");
await $network.clearProxy();
console.log(">>>>>>>>>>>>>>>>>>>", "Set proxy configuration for HTTPS request");
let testURL = new URL("http://" + sslProxyServer);
await $network.setProxyForHttps(testURL);
website = await accessWebSite();
checkHostname("www.google.com", website);

setProxyPAC

This browser testing API sets a proxy server through a proxy auto-config (PAC) script.

Usage

$browser.setProxyPAC(pacScriptURL: string, noProxy?: string, authMap?: Map<string, any>): Promise<void>;

Parameters

Parameter Type Description
RETURN Promise<void> A promise is resolved when settings are applied.
pacScriptURL string The URL of the PAC script.
noProxy string Optional: A comma-separated list of hosts that must bypass all proxies.
authMap Map Optional: A map of authentication credentials to be provided to the proxy servers, which are keyed by the Hostname of the proxy servers. Values of this map must be defined in the format {username: "authUsername", password: "authPassword"}.

Examples

const httpserver = '<DemoServerIP>';
const noproxy = "localhost,google.com,192.168.1.0/24";
const pacfile = `http://${httpserver}/pacfile`;
const authmap = new Map([
  [ httpserver, {username: "proxyuser", password: "passw0rd"} ],
  [ "httpserver2", {username: "user1", password: "passw0rd"} ],
])

async function testProxyPAC() {
  await $browser.clearProxy();
  await $browser.setProxyPAC(pacfile, noproxy, authmap);
  await $browser
    .get(`http://${httpserver}/demo/page2.html`)
    .then(() => $browser.takeScreenshot());
}

sleep

This browser testing API schedules a command to make the driver sleep for a specific amount of time.

Usage

$browser.sleep(ms: number): Promise<void>;

Parameters

Parameters Type Description
RETURN Promise<void> A promise that will be resolved when the sleep finishes.
ms number The amount of time, in milliseconds, to sleep.

Examples

await $browser.get("https://www.yahoo.com/");
await $browser.sleep(3 * 1000);
await $browser.takeScreenshot();

switchTo

This browser testing API gets an interface for changing the focus of the driver to another frame or window.

Usage

$browser.switchTo(): TargetLocator;

Parameters

Parameter Type Description
RETURN TargetLocator The TargetLocator interface for this instance.

TargetLocator

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

Instance methods

Type Description
activeElement(): WebElementPromise; Schedules a command retrieve the document.activeElement element on the current document or document.body if activeElement is not available.
defaultContent(): Promise<void>; Schedules a command to switch focus of all future commands to the first frame on the page. The target frame can be specified as one of the following values:
- A number that specifies a (zero-based) index into window.frames.
- A WebElement reference, which corresponds to a frame or iframe DOM element.
- The null value to select the topmost frame on the page. Passing null is the same as calling defaultContent.
frame(id: Number |WebElement| null): Promise<void>; Changes the focus of all future commands to another frame on the page.
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.
window(nameOrHandle: string): Promise<void>; Schedules a command to switch the focus of all future commands to another window. Windows can be specified by their window.name attribute or by their handle (as returned by getWindowHandle).
newWindow(typeHint: string): Promise<void>; Creates a browser window and switches the focus for future commands of this driver to the new window.
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 is created of whatever type the driver does support.
Returned promise is resolved when the driver changes focus to the new window.
alert(): AlertPromise; Schedules a command to change focus to the active modal dialog, such as the ones opened by window.alert(), window.confirm(), and window.prompt(). The returned promise is rejected with a error.NoSuchAlertError if no open alerts are available.

Examples

/**
 * samples of getting current window handle
 * switch to a new window
 * open new page in new tab
 */
console.log("Windows handle: ", await $browser.getWindowHandle(), "Current url: ", await $browser.getCurrentUrl());
console.log("switch to calendar tab");
let originalWindow = await $browser.getWindowHandle();
await $browser.switchTo().newWindow();

/**
 * navigate to www.timeanddate.com
 * assert page title by getTitle() api
 * assert page title by getPageSource() api
 */
console.log("Access time and date page");
await $browser.get("http://www.timeanddate.com");
let page = await $browser.getPageSource();
assert.isTrue(page.includes("<title>timeanddate.com</title>"));
console.log("Page title: ", await $browser.getTitle());

/**
 * switch back to original window
 * take screenshot
 */
await $browser.switchTo().window(originalWindow);
await $browser.takeScreenshot();

takeScreenshot

This browser testing API schedules a command to take a screenshot. The driver tries to return a screenshot of the following elements, in order of preference:

  1. Entire page
  2. Current window
  3. Visible portion of the current frame
  4. Entire display that contains the browser

Usage

$browser.takeScreenshot(): Promise<string>;

Parameters

Parameter Type Description
RETURN Promise<string> A promise that will be resolved with the screenshot as a base-64 encoded PNG.

wait

This browser testing API waits for a condition to evaluate to a "truthy" value. The condition can be specified by a Condition, as a custom function, or as any promise-like thenable.

For a Condition or function, the wait repeatedly evaluates the condition until it returns a truthy value. If any errors occur while the API evaluates the condition, the errors are allowed to propagate. When a condition returns a promise, the polling loop waits for it to be resolved and uses the resolved value to check whether the condition is satisfied. The resolution time for a promise is always factored into to check whether a wait is timed out.

If the provided condition is a WebElementCondition, then the wait returns a WebElementPromise that resolves to the element that satisfied the condition.

Usage

$browser.wait(
    condition: WebElementCondition,
    opt_timeout?: number,
    opt_message?: string): WebElementPromise;

Parameters

Parameter Type Description
RETURN Promise<string> A promise that will be resolved with the first truthy value that is 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 is a WebElementPromise.
condition IThenable<(T|null)> or Condition<(T|null)> or function(WebDriver): (T|null) The condition to wait on, defined as a promise, condition object, or a function to evaluate as a condition.
opt_timeout number The duration, in milliseconds, to wait for the condition to be true.
opt_message string or function An optional message to use if the wait times out.

Examples

Example 1: To wait up to 10 seconds for an element to be present on the page, use the commands as shown in the following example:

async function example() {
  let button = await $browser.wait(
    $driver.until.elementLocated($driver.By.id("foo")),
    10000
  );
  await button.click();
}

Example 2: To wait for an element and click, use the commands as shown in the following example:

await $browser.wait(until.elementLocated(by), timeout);
const element = await $browser.findElement(by, timeout);
await $browser.wait(until.elementIsVisible(element), timeout, `${by} not visible`);
await $browser.wait(until.elementIsEnabled(element), timeout, `${by} not enabled`);
await element.click();

waitForAndFindElement

This browser testing API waits for and finds an element on the page and waits for it to be visible. If not found, Synthetic monitoring returns an error. The timeout value is optional. It is applied separately to both tasks of finding the element and waiting for its visibility. Thus, in the worst case scenario, this method can take up to twice the provided timeout value. The default timeout value is 1000 ms (1 second).

A WebElementPromise is returned if an element is found with the locator that is given in the parameters and the element become visible, or when the stated conditions are not fulfilled within the specified timeout.

Usage

$browser.waitForAndFindElement(locator: Locator, timeout?: number) : WebElementPromise;

The function is similar as follows:

const element = await $browser.wait(until.elementLocated(locator), timeout);
await $browser.wait(until.elementIsVisible(element), timeout);
return await $browser.findElement(locator);

Parameters

Parameters Type Description
RETURN WebElementPromise A WebElement that can be used to issue commands against the located element. If the element is not found, the element is invalidated and all scheduled commands are stopped.
locator by.By | function The locator to use.
timeout number Optional: The amount of time, in milliseconds, to wait.

Examples

$browser.waitForAndFindElement($driver.By.id("username"), 10000);

waitForPendingRequests

This function is for compatibility with earlier versions.

Usage

$browser.waitForPendingRequests(timeout?: number): Promise<void>;

The function is similar as

let script = "return document.readyState === 'complete'";
await $browser.wait(() => {
    return $browser.executeScript(script);
}, timeout);

Parameters

Parameters Type Description
RETURN Promise<void> A promise that will be resolved when the document and all subresources are finished loading.
timeout number The amount of time, in milliseconds, to wait.