# WebdriverIO v10 documentation: Reference > 200 pages. Index of all sections: https://webdriver.io/llms.txt --- Source: https://webdriver.io/docs/api.md # Introduction Welcome to the WebdriverIO API docs. These pages contain reference materials for all implemented protocol bindings and convenience commands. Protocol commands, including [WebDriver](/docs/api/webdriver.md), [WebDriver Bidi](/docs/api/webdriverBidi.md) or mobile commands like [Appium](http://appium.io) are commands that are directly send to the underlying driver backend. Convenience commands provided by the [`browser`](/docs/api/browser.md), [`element`](/docs/api/element.md) or [`mock`](/docs/api/mock.md) object offer higher level interactivity. info These are the docs for WebdriverIO **v10**. Still on v9? Use the [v9 documentation](https://v9.webdriver.io) or follow the [v10 migration guide](/docs/v10-migration.md). ## Contribute[​](#contribute "Direct link to Contribute") If you feel like you have a good example for a command, don't hesitate to open a PR and submit it. Just click on the orange link on the bottom left with the label *“Edit this page”*. Make sure you understand the way we write these docs by checking the [Contributing](https://github.com/webdriverio/webdriverio/blob/main/CONTRIBUTING.md) section. --- Source: https://webdriver.io/docs/configuration.md # Configuration Based on the [setup type](/docs/setuptypes.md) (e.g. using the raw protocol bindings, WebdriverIO as standalone package or the WDIO testrunner) there is a different set of options available to control the environment. ## WebDriver Options[​](#webdriver-options "Direct link to WebDriver Options") The following options are defined when using the [`webdriver`](https://www.npmjs.com/package/webdriver) protocol package: ### protocol[​](#protocol "Direct link to protocol") * Type `String` * Default `http` Protocol to use when communicating with the driver server. ### hostname[​](#hostname "Direct link to hostname") * Type `String` * Default `0.0.0.0` Host of your driver server. ### port[​](#port "Direct link to port") * Type `Number` * Default `undefined` Port your driver server is on. ### path[​](#path "Direct link to path") * Type `String` * Default `/` Path to driver server endpoint. ### queryParams[​](#queryparams "Direct link to queryParams") * Type `Object` * Default `undefined` Query parameters that are propagated to the driver server. ### user[​](#user "Direct link to user") * Type `String` * Default `undefined` Your cloud service username (only works for [Sauce Labs](https://saucelabs.com), [Browserstack](https://www.browserstack.com), [TestingBot](https://testingbot.com) or [TestMu AI](https://www.testmuai.com/) accounts). If set, WebdriverIO will automatically set connection options for you. If you don't use a cloud provider this can be used to authenticate any other WebDriver backend. ### key[​](#key "Direct link to key") * Type `String` * Default `undefined` Your cloud service access key or secret key (only works for [Sauce Labs](https://saucelabs.com), [Browserstack](https://www.browserstack.com), [TestingBot](https://testingbot.com) or [TestMu AI](https://www.testmuai.com/) accounts). If set, WebdriverIO will automatically set connection options for you. If you don't use a cloud provider this can be used to authenticate any other WebDriver backend. ### capabilities[​](#capabilities "Direct link to capabilities") * Type `Object` * Default `null` Defines the capabilities you want to run in your WebDriver session. Check out the [WebDriver Protocol](https://w3c.github.io/webdriver/#capabilities) for more details. Next to the WebDriver based capabilities you can apply browser and vendor specific options that allow deeper configuration to the remote browser or device. These are documented in the corresponding vendor docs, e.g.: * `goog:chromeOptions`: for [Google Chrome](https://chromedriver.chromium.org/capabilities#h.p_ID_106) * `moz:firefoxOptions`: for [Mozilla Firefox](https://firefox-source-docs.mozilla.org/testing/geckodriver/Capabilities.html) * `ms:edgeOptions`: for [Microsoft Edge](https://docs.microsoft.com/en-us/microsoft-edge/webdriver-chromium/capabilities-edge-options#using-the-edgeoptions-class) * `sauce:options`: for [Sauce Labs](https://docs.saucelabs.com/dev/test-configuration-options/#desktop-and-mobile-capabilities-sauce-specific--optional) * `bstack:options`: for [BrowserStack](https://www.browserstack.com/automate/capabilities?tag=selenium-4#) * `selenoid:options`: for [Selenoid](https://github.com/aerokube/selenoid/blob/master/docs/special-capabilities.adoc) Additionally, a useful utility is the Sauce Labs [Automated Test Configurator](https://docs.saucelabs.com/basics/platform-configurator/), which helps you create this object by clicking together your desired capabilities. **Example:** ``` { browserName: 'chrome', // options: `chrome`, `edge`, `firefox`, `safari` browserVersion: '27.0', // browser version platformName: 'Windows 10' // OS platform } ``` If you’re running web or native tests on mobile devices, `capabilities` differs from the WebDriver protocol. See the [Appium Docs](https://appium.io/docs/en/latest/guides/caps/) for more details. ### logLevel[​](#loglevel "Direct link to logLevel") * Type `String` * Default `info` * Values `trace | debug | info | warn | error | silent` Level of logging verbosity. ### outputDir[​](#outputdir "Direct link to outputDir") * Type `String` * Default `null` Directory to store all testrunner log files (including reporter logs and `wdio` logs). If not set, all logs are streamed to `stdout`. Since most reporters are made to log to `stdout`, it is recommended to only use this option for specific reporters where it makes more sense to push report into a file (like the `junit` reporter, for example). When running in standalone mode, the only log generated by WebdriverIO will be the `wdio` log. ### connectionRetryTimeout[​](#connectionretrytimeout "Direct link to connectionRetryTimeout") * Type `Number` * Default `120000` Timeout for any WebDriver request to a driver or grid. ### connectionRetryCount[​](#connectionretrycount "Direct link to connectionRetryCount") * Type `Number` * Default `3` Maximum count of request retries to the Selenium server. ### bidiResponseTimeout[​](#bidiresponsetimeout "Direct link to bidiResponseTimeout") * Type `Number` * Default `180000` Timeout (in ms) for a WebDriver Bidi command to receive a response from the browser. Increase this if you run commands, e.g. [`execute`](/docs/api/browser/execute.md), that legitimately take longer than the default to resolve, otherwise WebdriverIO gives up waiting before the browser is done. `execute` also stops at the `script` timeout of the session (30 seconds by default, see [`setTimeout`](/docs/api/browser/setTimeout.md)). For a `script` timeout longer than `bidiResponseTimeout`, increase both. ### bidiConnectTimeout[​](#bidiconnecttimeout "Direct link to bidiConnectTimeout") * Type `Number` * Default `10000` Timeout (in ms) for the browser to accept the WebDriver Bidi connection. After it, the session continues with WebDriver Classic, and Bidi-only commands such as [`mock`](/docs/api/browser/mock.md) fail. Increase it if a browser that is busy at startup, e.g. several browsers that start at the same time on a CI runner, accepts the connection late. This option applies to sessions in Node.js. In a browser, for example with the [browser runner](/docs/runner.md#browser-runner), the connection waits until it opens or fails. ### agent[​](#agent "Direct link to agent") * Type `Object` * Default ``` { http: new http.Agent({ keepAlive: true }), https: new https.Agent({ keepAlive: true }) } ``` Allows you to use a custom` http`/`https`/`http2` [agent](https://www.npmjs.com/package/got#agent) to make requests. ### headers[​](#headers "Direct link to headers") * Type `Object` * Default `{}` Specify custom `headers` to pass into every WebDriver request. If your Selenium Grid requires Basic Authentification we recommend to pass in an `Authorization` header through this option to authenticate your WebDriver requests, e.g.: ``` import { Buffer } from 'buffer'; // Read the username and password from environment variables const username = process.env.SELENIUM_GRID_USERNAME; const password = process.env.SELENIUM_GRID_PASSWORD; // Combine the username and password with a colon separator const credentials = `${username}:${password}`; // Encode the credentials using Base64 const encodedCredentials = Buffer.from(credentials).toString('base64'); export const config: WebdriverIO.Config = { // ... headers: { Authorization: `Basic ${encodedCredentials}` } // ... } ``` ### transformRequest[​](#transformrequest "Direct link to transformRequest") * Type `(RequestOptions) => RequestOptions` * Default `none` Function intercepting [HTTP request options](https://github.com/sindresorhus/got#options) before a WebDriver request is made ### transformResponse[​](#transformresponse "Direct link to transformResponse") * Type `(Response, RequestOptions) => Response` * Default `none` Function intercepting HTTP response objects after a WebDriver response has arrived. The function is passed the original response object as the first and the corresponding `RequestOptions` as the second argument. ### strictSSL[​](#strictssl "Direct link to strictSSL") * Type `Boolean` * Default `true` Whether it does not require SSL certificate to be valid. It can be set via an environment variables as `STRICT_SSL` or `strict_ssl`. ### enableDirectConnect[​](#enabledirectconnect "Direct link to enableDirectConnect") * Type `Boolean` * Default `true` Whether enable [Appium direct connection feature](https://appiumpro.com/editions/86-connecting-directly-to-appium-hosts-in-distributed-environments). It does nothing if the response did not have proper keys while the flag is enabled. ### cacheDir[​](#cachedir "Direct link to cacheDir") * Type `String` * Default `process.env.WEBDRIVER_CACHE_DIR || os.tmpdir()` The path to the root of the cache directory. This directory is used to store all drivers that are downloaded when attempting to start a session. ### maskingPatterns[​](#maskingpatterns "Direct link to maskingPatterns") * Type `String` * Default `undefined` For more secure logging, regular expressions set with `maskingPatterns` can obfuscate sensitive information from the log. * The string format is a regular expression with or without flags (e.g. `/.../i`) and comma-separated for multiple regular expressions. * For more details on masking patterns, see the [Masking Patterns section in the WDIO Logger README](https://github.com/webdriverio/webdriverio/blob/main/packages/wdio-logger/README.md#masking-patterns). **Example:** ``` { maskingPatterns: '/--key=([^ ]*)/i,/RESULT (.*)/' } ``` ## WebdriverIO[​](#webdriverio "Direct link to WebdriverIO") The following options (including the ones listed above) can be used with WebdriverIO in standalone: ### automationProtocol[​](#automationprotocol "Direct link to automationProtocol") * Type `String` * Default `webdriver` Define the protocol you want to use for your browser automation. Currently only [`webdriver`](https://www.npmjs.com/package/webdriver) is supported, as it is the main browser automation technology WebdriverIO uses. If you want to automate the browser using a different automation technology, make you set this property to a path that resolves to a module that adheres to the following interface: ``` import type { Capabilities } from '@wdio/types'; import type { Client, AttachOptions } from 'webdriver'; export default class YourAutomationLibrary { /** * Start a automation session and return a WebdriverIO [monad](https://github.com/webdriverio/webdriverio/blob/940cd30939864bdbdacb2e94ee6e8ada9b1cc74c/packages/wdio-utils/src/monad.ts) * with respective automation commands. See the [webdriver](https://www.npmjs.com/package/webdriver) package * as a reference implementation * * @param {Capabilities.RemoteConfig} options WebdriverIO options * @param {Function} hook that allows to modify the client before it gets released from the function * @param {PropertyDescriptorMap} userPrototype allows user to add custom protocol commands * @param {Function} customCommandWrapper allows to modify the command execution * @returns a WebdriverIO compatible client instance */ static newSession( options: Capabilities.RemoteConfig, modifier?: (...args: any[]) => any, userPrototype?: PropertyDescriptorMap, customCommandWrapper?: (...args: any[]) => any ): Promise; /** * allows user to attach to existing sessions * @optional */ static attachToSession( options?: AttachOptions, modifier?: (...args: any[]) => any, userPrototype?: {}, commandWrapper?: (...args: any[]) => any ): Client; /** * Changes The instance session id and browser capabilities for the new session * directly into the passed in browser object * * @optional * @param {object} instance the object we get from a new browser session. * @returns {string} the new session id of the browser */ static reloadSession( instance: Client, newCapabilities?: WebdriverIO.Capabilitie ): Promise; } ``` ### baseUrl[​](#baseurl "Direct link to baseUrl") * Type `String` * Default `null` Shorten `url` command calls by setting a base URL. * If your `url` parameter starts with `/`, then `baseUrl` is prepended (except the `baseUrl` path, if it has one). * If your `url` parameter starts without a scheme or `/` (like `some/path`), then the full `baseUrl` is prepended directly. ### waitforTimeout[​](#waitfortimeout "Direct link to waitforTimeout") * Type `Number` * Default `5000` Default timeout for all `waitFor*` commands. (Note the lowercase `f` in the option name.) This timeout **only** affects commands starting with `waitFor*` and their default wait time. To increase the timeout for a *test*, please see the framework docs. ### waitforInterval[​](#waitforinterval "Direct link to waitforInterval") * Type `Number` * Default `100` Default interval for all `waitFor*` commands to check if an expected state (e.g., visibility) has been changed. ### strictSelectors[​](#strictselectors "Direct link to strictSelectors") * Type `Boolean` * Default `true` Makes the [`$`](/docs/api/browser/$.md) command throw a `StrictSelectorError` when the given selector resolves to more than one element, instead of silently using the first match. `$$` is unaffected. You can opt out for a single query by passing `{ strict: false }` as second argument, e.g. `$('button', { strict: false })`. See the [Selectors](/docs/selectors.md#strict-mode) guide for details. ### maxSpyCollectedBodySize[​](#maxspycollectedbodysize "Direct link to maxSpyCollectedBodySize") * Type `Number` * Default `10485760 (10MB)` Maximum size of the response body (in bytes) that can be returned when using the [`mock`](/docs/api/browser/mock.md) command. Use `0` to disable data collection of the spied payload. ### region[​](#region "Direct link to region") * Type `String` * Default `us` * Values `us | eu | us-west-1 | eu-central-1 | us-east-4 | asia-south-2 | staging` If running on Sauce Labs, you can choose to run tests between different data centers. Use short region handles `us` (default, maps to `us-west-1`) or `eu` (maps to `eu-central-1`), or the full region names directly. **Note:** This only has an effect if you provide `user` and `key` options that are connected to your Sauce Labs account. *(only for vm and or em/simulators, except `us-east-4` and `asia-south-2` which host real devices only)* ## Testrunner Options[​](#testrunner-options "Direct link to Testrunner Options") The following options (including the ones listed above) are defined only for running WebdriverIO with the WDIO testrunner: ### specs[​](#specs "Direct link to specs") * Type `(String | String[])[]` * Default `[]` Define specs for test execution. You can either specify a glob pattern to match multiple files at once or wrap a glob or set of paths into an array to run them within a single worker process. All paths are seen as relative from the config file path. ### exclude[​](#exclude "Direct link to exclude") * Type `String[]` * Default `[]` Exclude specs from test execution. All paths are seen as relative from the config file path. ### suites[​](#suites "Direct link to suites") * Type `Object` * Default `{}` An object describing various suites, which you can then specify with the `--suite` option on the `wdio` CLI. ### capabilities[​](#capabilities-1 "Direct link to capabilities") * Type `Object|Object[]` * Default `[{ 'wdio:maxInstances': 5, browserName: 'firefox' }]` The same as the `capabilities` section described above, except with the option to specify either a [multi-remote](/docs/multiremote.md) object, or multiple WebDriver sessions in an array for parallel execution. You can apply the same vendor and browser specific capabilities as defined [above](/docs/configuration.md#capabilities). ### maxInstances[​](#maxinstances "Direct link to maxInstances") * Type `Number` * Default `100` Maximum number of total parallel running workers. **Note:** that it may be a number as high as `100`, when the tests are being performed on some external vendors such as Sauce Labs's machines. There, the tests are not tested on a single machine, but rather, on multiple VMs. If the tests are to be run on a local development machine, use a number that is more reasonable, such as `3`, `4`, or `5`. Essentially, this is the number of browsers that will be concurrently started and running your tests at the same time, so it depends on how much RAM there is on your machine, and how many other apps are running on your machine. You can also apply `maxInstances` within your capability objects using the `wdio:maxInstances` capability. This will limit the amount of parallel sessions for that particular capability. ### maxInstancesPerCapability[​](#maxinstancespercapability "Direct link to maxInstancesPerCapability") * Type `Number` * Default `100` Maximum number of total parallel running workers per capability. ### injectGlobals[​](#injectglobals "Direct link to injectGlobals") * Type `Boolean` * Default `true` Inserts WebdriverIO's globals (e.g. `browser`, `$` and `$$`) into the global environment. If you set to `false`, you should import from `@wdio/globals`, e.g.: ``` import { browser, $, $$, expect } from '@wdio/globals' ``` Note: WebdriverIO doesn't handle injection of test framework specific globals. ### bail[​](#bail "Direct link to bail") * Type `Number` * Default `0 (don't bail; run all tests)` If you want your test run to stop after a specific number of test failures, use `bail`. (It defaults to `0`, which runs all tests no matter what.) **Note:** A test in this context are all tests within a single spec file (when using Mocha or Jasmine) or all steps within a feature file (when using Cucumber). If you want to control the bail behavior within tests of a single test file, take a look at the available [framework](/docs/frameworks.md) options. ### specFileRetries[​](#specfileretries "Direct link to specFileRetries") * Type `Number` * Default `0` The number of times to retry an entire specfile when it fails as a whole. ### specFileRetriesDelay[​](#specfileretriesdelay "Direct link to specFileRetriesDelay") * Type `Number` * Default `0` Delay in seconds between the spec file retry attempts ### specFileRetriesDeferred[​](#specfileretriesdeferred "Direct link to specFileRetriesDeferred") * Type `Boolean` * Default `true` Whether or not retried spec files should be retried immediately or deferred to the end of the queue. ### groupLogsByTestSpec[​](#grouplogsbytestspec "Direct link to groupLogsByTestSpec") * Type `Boolean` * Default `false` Choose the log output view. If set to `false` logs from different test files will be printed in real-time. Please note that this may result in the mixing of log outputs from different files when running in parallel. If set to `true` log outputs will be grouped by Test Spec and printed only when the Test Spec is completed. By default, it is set to `false` so logs are printed in real-time. ### autoAssertOnTestEnd[​](#autoassertontestend "Direct link to autoAssertOnTestEnd") * Type `Boolean` * Default `true` Controls whether WebdriverIO automatically asserts all soft assertions at the end of each test. When set to `true`, any accumulated soft assertions will be automatically checked and cause the test to fail if any assertions failed. When set to `false`, you must manually call the assert method to check soft assertions. ### services[​](#services "Direct link to services") * Type `String[]|Object[]` * Default `[]` Services take over a specific job you don't want to take care of. They enhance your test setup with almost no effort. ### framework[​](#framework "Direct link to framework") * Type `String` * Default `mocha` * Values `mocha | jasmine | cucumber` Defines the test framework to be used by the WDIO testrunner. ### mochaOpts, jasmineOpts and cucumberOpts[​](#mochaopts-jasmineopts-and-cucumberopts "Direct link to mochaOpts, jasmineOpts and cucumberOpts") * Type `Object` * Default `{ timeout: 10000 }` Specific framework-related options. See the framework adapter documentation on which options are available. Read more on this in [Frameworks](/docs/frameworks.md). ### cucumberFeaturesWithLineNumbers[​](#cucumberfeatureswithlinenumbers "Direct link to cucumberFeaturesWithLineNumbers") * Type `String[]` * Default `[]` List of cucumber features with line numbers (when [using cucumber framework](/docs/frameworks.md#using-cucumber)). ### reporters[​](#reporters "Direct link to reporters") * Type `String[]|Object[]` * Default `[]` List of reporters to use. A reporter can be either a string, or an array of `['reporterName', { /* reporter options */}]` where the first element is a string with the reporter name and the second element an object with reporter options. Example: ``` reporters: [ 'dot', 'spec' ['junit', { outputDir: `${__dirname}/reports`, otherOption: 'foobar' }] ] ``` ### reporterSyncInterval[​](#reportersyncinterval "Direct link to reporterSyncInterval") * Type `Number` * Default `100 (ms)` Determines in which interval the reporter should check if they are synchronized if they report their logs asynchronously (e.g. if logs are streamed to a 3rd party vendor). ### reporterSyncTimeout[​](#reportersynctimeout "Direct link to reporterSyncTimeout") * Type `Number` * Default `5000 (ms)` Determines the maximum time reporters have to finish uploading all their logs until an error is being thrown by the testrunner. ### execArgv[​](#execargv "Direct link to execArgv") * Type `String[]` * Default `null` Node arguments to specify when launching child processes. ### cpuProf[​](#cpuprof "Direct link to cpuProf") * Type `Boolean` * Default `false` Enable CPU profiling for the worker process. The profile will be generated automatically when the worker process exits. ### heapProf[​](#heapprof "Direct link to heapProf") * Type `Boolean` * Default `false` Enable Heap profiling for the worker process. The snapshot will be generated automatically when the worker process exits (uses sampling heap profiler). ### profileOutputDir[​](#profileoutputdir "Direct link to profileOutputDir") * Type `String` * Default `./profiles` Directory where the CPU profiles (`.cpuprofile`) and Heap profiles (`.heapprofile`) will be saved. ### filesToWatch[​](#filestowatch "Direct link to filesToWatch") * Type `String[]` * Default `[]` A list of glob supporting string patterns that tell the testrunner to have it additionally watch other files, e.g. application files, when running it with the `--watch` flag. By default the testrunner already watches all spec files. ### updateSnapshots[​](#updatesnapshots "Direct link to updateSnapshots") * Type `'new' | 'all' | 'none'` * Default `none if not provided and tests run in CI, new if not provided, otherwise what's been provided` Set to true if you want to update your snapshots. Ideally used as part of a CLI parameter, e.g. `wdio run wdio.conf.js --s`. ### resolveSnapshotPath[​](#resolvesnapshotpath "Direct link to resolveSnapshotPath") * Type `(testPath: string, snapExtension: string) => string` * Default `stores snapshot files in __snapshots__ directory next to test file` Overrides default snapshot path. For example, to store snapshots next to test files. wdio.conf.ts ``` export const config: WebdriverIO.Config = { resolveSnapshotPath: (testPath, snapExtension) => testPath + snapExtension, } ``` ### tsConfigPath[​](#tsconfigpath "Direct link to tsConfigPath") * Type `String` * Default `null` WDIO uses `tsx` to compile TypeScript files. Your TSConfig is automatically detected from the current working directory but you can specify a custom path here or by setting the TSX\_TSCONFIG\_PATH environment variable. See the `tsx` docs: ### displayServerEnabled[​](#displayserverenabled "Direct link to displayServerEnabled") * Type `Boolean` * Default `true` Start a virtual display for the run on Linux when neither `DISPLAY` nor `WAYLAND_DISPLAY` is set. Set to `false` when you run headless or only on a cloud service or remote grid. It only controls whether a display server starts: with only `WAYLAND_DISPLAY` set, the testrunner still sets `XDG_SESSION_TYPE`, `GDK_BACKEND` and `ELECTRON_OZONE_PLATFORM_HINT` to `wayland` for the run. See [Headless & Display Servers](/docs/headless-and-display-servers.md). ### displayServer[​](#displayserver "Direct link to displayServer") * Type `String` * Default `auto` * Values `auto | wayland | xvfb` Which display server to start. `auto` tries Weston and falls back to Xvfb when Weston is missing or fails to start. `wayland` and `xvfb` only try that server. ### displayServerAutoInstall[​](#displayserverautoinstall "Direct link to displayServerAutoInstall") * Type `Boolean` * Default `false` Install a missing display server with the system package manager when no installed one starts. ### displayServerAutoInstallMode[​](#displayserverautoinstallmode "Direct link to displayServerAutoInstallMode") * Type `String` * Default `sudo` * Values `root | sudo` How the built-in install runs: `root` installs only when running as root, `sudo` uses non-interactive `sudo -n` when not root, or installs without it when `sudo` isn't installed. ### displayServerAutoInstallCommand[​](#displayserverautoinstallcommand "Direct link to displayServerAutoInstallCommand") * Type `String | String[]` A command to run instead of the built-in install, as-is and without `sudo`. It only runs with `displayServerAutoInstall: true`. A string runs in a shell, an array runs without one. With `auto`, it runs for Weston first, and again for Xvfb only if Weston still isn't available or fails to start, and Xvfb is still missing. Set `displayServer` to the server it installs to skip the other server's attempt. ### displayServerWidth[​](#displayserverwidth "Direct link to displayServerWidth") * Type `Number` * Default `1920` Screen width of the virtual display in pixels. ### displayServerHeight[​](#displayserverheight "Direct link to displayServerHeight") * Type `Number` * Default `1080` Screen height of the virtual display in pixels. ### displayServerDepth[​](#displayserverdepth "Direct link to displayServerDepth") * Type `Number` * Default `24` Color depth of the virtual display. Xvfb only. ## Hooks[​](#hooks "Direct link to Hooks") The WDIO testrunner allows you to set hooks to be triggered at specific times of the test lifecycle. This allows custom actions (e.g. take screenshot if a test fails). Every hook has as parameter specific information about the lifecycle (e.g. information about the test suite or test). Read more about all hook properties in [our example config](https://github.com/webdriverio/webdriverio/blob/master/examples/wdio.conf.js#L183-L326). **Note:** Some hooks (`onPrepare`, `onWorkerStart`, `onWorkerEnd` and `onComplete`) are executed in a different process and therefore can not share any global data with the other hooks that live in the worker process. **Errors that no test reports:** with Jasmine and Cucumber, a promise that rejects when no test or step runs, before the worker ends (for example a command without `await` in the last `afterEach` hook, or in the `after` hook), fails the run, and the worker logs it as `Unhandled promise rejection that no test reports`. The worker goes on, so the reporters still write their reports. If a hook waits for that promise, the worker ends 60 seconds after its last activity, also with its reports. An error that is thrown when no test or step runs (for example in a timer) after the tests started ends the worker at once, with its reports. When the worker ends this way, the hooks that did not run yet (for example `after` or `afterSession`) do not run. Before the tests start (in the `beforeSession` and `before` hooks, or while the session starts), a thrown error ends the worker at once without reports, because no test ran yet, and a promise that rejects follows the rules above. While the Mocha tests run, Mocha handles these errors itself: it ignores an unhandled rejection, and an error thrown after the run ends the worker. ### onPrepare[​](#onprepare "Direct link to onPrepare") Gets executed once before all workers get launched. Parameters: * `config` (`object`): WebdriverIO configuration object * `param` (`object[]`): list of capabilities details ### onWorkerStart[​](#onworkerstart "Direct link to onWorkerStart") Gets executed before a worker process is spawned and can be used to initialize specific service for that worker as well as modify runtime environments in an async fashion. Parameters: * `cid` (`string`): capability id (e.g 0-0) * `caps` (`object`): containing capabilities for session that will be spawn in the worker * `specs` (`string[]`): specs to be run in the worker process * `args` (`object`): object that will be merged with the main configuration once worker is initialized * `execArgv` (`string[]`): list of string arguments passed to the worker process ### onWorkerEnd[​](#onworkerend "Direct link to onWorkerEnd") Gets executed just after a worker process has exited. Parameters: * `cid` (`string`): capability id (e.g 0-0) * `exitCode` (`number`): 0 - success, 1 - fail. A worker that was terminated by a signal reports `128` + the signal number instead, e.g. `139` for a `SIGSEGV` * `specs` (`string[]`): specs to be run in the worker process * `retries` (`number`): number of spec level retries used as defined in [*"Add retries on a per-specfile basis"*](/docs/retry.md#add-retries-on-a-per-specfile-basis) * `signal` (`string`): signal that terminated the worker, e.g. `SIGSEGV`, or `null` if it exited on its own ### beforeSession[​](#beforesession "Direct link to beforeSession") Gets executed just before initializing the webdriver session and test framework. It allows you to manipulate configurations depending on the capability or spec. Parameters: * `config` (`object`): WebdriverIO configuration object * `caps` (`object`): containing capabilities for session that will be spawn in the worker * `specs` (`string[]`): specs to be run in the worker process ### before[​](#before "Direct link to before") Gets executed before test execution begins. At this point you can access to all global variables like `browser`. It is the perfect place to define custom commands. Parameters: * `caps` (`object`): containing capabilities for session that will be spawn in the worker * `specs` (`string[]`): specs to be run in the worker process * `browser` (`object`): instance of created browser/device session ### beforeSuite[​](#beforesuite "Direct link to beforeSuite") Hook that gets executed before the suite starts (in Mocha/Jasmine only) Parameters: * `suite` (`object`): suite details ### beforeHook[​](#beforehook "Direct link to beforeHook") Hook that gets executed *before* a hook within the suite starts (e.g. runs before calling beforeEach in Mocha) Parameters: * `test` (`object`): test details * `context` (`object`): test context (represents World object in Cucumber) ### afterHook[​](#afterhook "Direct link to afterHook") Hook that gets executed *after* a hook within the suite ends (e.g. runs after calling afterEach in Mocha) Parameters: * `test` (`object`): test details * `context` (`object`): test context (represents World object in Cucumber) * `result` (`object`): hook result (contains `error`, `result`, `duration`, `passed`, `retries` properties) ### beforeTest[​](#beforetest "Direct link to beforeTest") Function to be executed before a test (in Mocha/Jasmine only). Parameters: * `test` (`object`): test details * `context` (`object`): scope object the test was executed with ### beforeCommand[​](#beforecommand "Direct link to beforeCommand") Runs before a WebdriverIO command gets executed. For an element command, it runs before WebdriverIO waits for the element (see [Auto-waiting](/docs/autowait.md)). Parameters: * `commandName` (`string`): command name * `args` (`*`): arguments that command would receive ### afterCommand[​](#aftercommand "Direct link to afterCommand") Runs after a WebdriverIO command gets executed. For an element command, it runs after the wait for the element. When WebdriverIO retries an element command (for example after a stale element), the hook gets the result or the error of the last try. Parameters: * `commandName` (`string`): command name * `args` (`*`): arguments that command would receive * `result` (`*`): result of the command * `error` (`Error`): error object if any ### afterTest[​](#aftertest "Direct link to afterTest") Function to be executed after a test (in Mocha/Jasmine) ends. It also runs after a test times out. With Mocha, the next test starts after this hook ends (Mocha waits for it up to one more timeout of the test, see [Timeouts](/docs/timeouts.md#mocha-timeouts-and-the-webdriverio-hooks)). Parameters: * `test` (`object`): test details * `context` (`object`): scope object the test was executed with * `result.error` (`Error`): error object in case the test fails, otherwise `undefined` * `result.result` (`Any`): return object of test function * `result.duration` (`Number`): duration of test * `result.passed` (`Boolean`): true if test has passed, otherwise false * `result.retries` (`Object`): information about single test related retries as defined for [Mocha and Jasmine](/docs/retry.md#rerun-single-tests-in-jasmine-or-mocha) as well as [Cucumber](/docs/retry.md#rerunning-in-cucumber), e.g. `{ attempts: 0, limit: 0 }`, see * `result` (`object`): hook result (contains `error`, `result`, `duration`, `passed`, `retries` properties) ### afterSuite[​](#aftersuite "Direct link to afterSuite") Hook that gets executed after the suite has ended (in Mocha/Jasmine only) Parameters: * `suite` (`object`): suite details ### after[​](#after "Direct link to after") Gets executed after all tests are done. You still have access to all global variables from the test. Parameters: * `result` (`number`): 0 - test pass, 1 - test fail * `caps` (`object`): containing capabilities for session that will be spawn in the worker * `specs` (`string[]`): specs to be run in the worker process ### afterSession[​](#aftersession "Direct link to afterSession") Gets executed right after terminating the webdriver session. Parameters: * `config` (`object`): WebdriverIO configuration object * `caps` (`object`): containing capabilities for session that will be spawn in the worker * `specs` (`string[]`): specs to be run in the worker process ### onComplete[​](#oncomplete "Direct link to onComplete") Gets executed after all workers got shut down and the process is about to exit. An error thrown in the onComplete hook will result in the test run failing. Parameters: * `exitCode` (`number`): 0 - success, 1 - fail * `config` (`object`): WebdriverIO configuration object * `caps` (`object`): containing capabilities for session that will be spawn in the worker * `result` (`object`): results object containing test results ### onReload[​](#onreload "Direct link to onReload") Gets executed when a refresh happens. Parameters: * `oldSessionId` (`string`): session ID of the old session * `newSessionId` (`string`): session ID of the new session ### beforeFeature[​](#beforefeature "Direct link to beforeFeature") Runs before a Cucumber Feature. Parameters: * `uri` (`string`): path to feature file * `feature` ([`GherkinDocument.IFeature`](https://github.com/cucumber/common/blob/b94ce625967581de78d0fc32d84c35b46aa5a075/json-to-messages/javascript/src/cucumber-generic/JSONSchema.ts#L8-L17)): Cucumber feature object ### afterFeature[​](#afterfeature "Direct link to afterFeature") Runs after a Cucumber Feature. Parameters: * `uri` (`string`): path to feature file * `feature` ([`GherkinDocument.IFeature`](https://github.com/cucumber/common/blob/b94ce625967581de78d0fc32d84c35b46aa5a075/json-to-messages/javascript/src/cucumber-generic/JSONSchema.ts#L8-L17)): Cucumber feature object ### beforeScenario[​](#beforescenario "Direct link to beforeScenario") Runs before a Cucumber Scenario. Parameters: * `world` ([`ITestCaseHookParameter`](https://github.com/cucumber/cucumber-js/blob/ac124f7b2be5fa54d904c7feac077a2657b19440/src/support_code_library_builder/types.ts#L10-L15)): world object containing information on pickle and test step * `context` (`object`): Cucumber World object ### afterScenario[​](#afterscenario "Direct link to afterScenario") Runs after a Cucumber Scenario. Parameters: * `world` ([`ITestCaseHookParameter`](https://github.com/cucumber/cucumber-js/blob/ac124f7b2be5fa54d904c7feac077a2657b19440/src/support_code_library_builder/types.ts#L10-L15)): world object containing information on pickle and test step * `result` (`object`): results object containing scenario results * `result.passed` (`boolean`): true if scenario has passed * `result.error` (`string`): error stack if scenario failed * `result.duration` (`number`): duration of scenario in milliseconds * `context` (`object`): Cucumber World object ### beforeStep[​](#beforestep "Direct link to beforeStep") Runs before a Cucumber Step. Parameters: * `step` ([`Pickle.IPickleStep`](https://github.com/cucumber/common/blob/b94ce625967581de78d0fc32d84c35b46aa5a075/messages/jsonschema/Pickle.json#L20-L49)): Cucumber step object * `scenario` ([`IPickle`](https://github.com/cucumber/common/blob/b94ce625967581de78d0fc32d84c35b46aa5a075/messages/jsonschema/Pickle.json#L137-L175)): Cucumber scenario object * `context` (`object`): Cucumber World object ### afterStep[​](#afterstep "Direct link to afterStep") Runs after a Cucumber Step. Parameters: * `step` ([`Pickle.IPickleStep`](https://github.com/cucumber/common/blob/b94ce625967581de78d0fc32d84c35b46aa5a075/messages/jsonschema/Pickle.json#L20-L49)): Cucumber step object * `scenario` ([`IPickle`](https://github.com/cucumber/common/blob/b94ce625967581de78d0fc32d84c35b46aa5a075/messages/jsonschema/Pickle.json#L137-L175)): Cucumber scenario object * `result`: (`object`): results object containing step results * `result.passed` (`boolean`): true if scenario has passed * `result.error` (`string`): error stack if scenario failed * `result.duration` (`number`): duration of scenario in milliseconds * `context` (`object`): Cucumber World object ### beforeAssertion[​](#beforeassertion "Direct link to beforeAssertion") Hook that gets executed before a WebdriverIO assertion happens. Parameters: * `params`: assertion information * `params.matcherName` (`string`): name of the matcher that the test called (e.g. `toHaveTitle`). For an alias, it is the name of the alias (e.g. `toBeExisting`, not `toExist`). * `params.expectedValue`: value that is passed into the matcher * `params.options`: assertion options ### afterAssertion[​](#afterassertion "Direct link to afterAssertion") Hook that gets executed after a WebdriverIO assertion happened. Parameters: * `params`: assertion information * `params.matcherName` (`string`): name of the matcher that the test called (e.g. `toHaveTitle`). For an alias, it is the name of the alias (e.g. `toBeExisting`, not `toExist`). * `params.expectedValue`: value that is passed into the matcher * `params.options`: assertion options * `params.result` (`object`): result of the matcher, with `pass` (`boolean`) and `message()`. `pass` is `true` when the value matches the expected value, also with `.not`: with `.not`, the assertion passes when `pass` is `false`. --- Source: https://webdriver.io/docs/api/expect-webdriverio.md # Expect When you're writing tests, you often need to check that values meet certain conditions. `expect` gives you access to a number of "matchers" that let you validate different things on the `browser`, an `element` or `mock` object. **Note**: Browser, element, network and snapshot matchers also support [multi-remote](https://github.com/webdriverio/expect-webdriverio/blob/main/MultiRemote.md), checking every browser instance with a single expected value or, for browser, element and network matchers, one per instance. Examples that do not open a page or show their HTML assume the [guinea pig test page](https://guinea-pig.webdriver.io/) is open: ``` await browser.url('https://guinea-pig.webdriver.io/') // or, with multi-remote await multiRemoteBrowser.url('https://guinea-pig.webdriver.io/') ``` ## Soft Assertions[​](#soft-assertions "Direct link to Soft Assertions") Soft assertions allow you to continue test execution even when an assertion fails. This is useful when you want to check multiple conditions in a test and collect all failures rather than stopping at the first failure. Failures are collected and reported at the end of the test. ### Usage[​](#usage "Direct link to Usage") ``` // Mocha example it('test page smoke', async () => { // These won't throw immediately if they fail await expect.soft(await $('header h1').getText()).toEqual('WebdriverJS Testpage'); await expect.soft(await $('.sometext').getText()).toMatch(/some/); // Also work with basic matcher const h1Text = await $('header h1').getText() expect.soft(h1Text).toEqual('WebdriverJS Testpage'); // Regular assertions still throw immediately await expect(await $('.sendBtn').isClickable()).toBe(true); }); // At the end of the test, all soft assertion failures // will be reported together with their details ``` ### Soft Assertion API[​](#soft-assertion-api "Direct link to Soft Assertion API") #### expect.soft()[​](#expectsoft "Direct link to expect.soft()") Creates a soft assertion that collects failures instead of immediately throwing errors. ``` await expect.soft(actual).toBeDisplayed(); await expect.soft(actual).not.toHaveText('Wrong text'); ``` #### expect.getSoftFailures()[​](#expectgetsoftfailures "Direct link to expect.getSoftFailures()") Get all collected soft assertion failures for the current test. ``` const failures = expect.getSoftFailures(); console.log(`There are ${failures.length} soft assertion failures`); ``` #### expect.assertSoftFailures()[​](#expectassertsoftfailures "Direct link to expect.assertSoftFailures()") Manually assert all collected soft failures. This will throw an aggregated error if any soft assertions have failed. ``` // Manually throw if any soft assertions have failed expect.assertSoftFailures(); ``` #### expect.clearSoftFailures()[​](#expectclearsoftfailures "Direct link to expect.clearSoftFailures()") Clear all collected soft assertion failures for the current test. ``` // Clear all collected failures expect.clearSoftFailures(); ``` ### Integration with Test Frameworks[​](#integration-with-test-frameworks "Direct link to Integration with Test Frameworks") The soft assertions feature integrates with WebdriverIO's test runner automatically. By default, it will report all soft assertion failures at the end of each test (Mocha) or step (Cucumber). To use with WebdriverIO, add the SoftAssertionService to your services list: ``` // wdio.conf.js import { SoftAssertionService } from 'expect-webdriverio' export const config = { // ... services: [ // ...other services [SoftAssertionService, {}] ], // ... } ``` #### Configuration Options[​](#configuration-options "Direct link to Configuration Options") The SoftAssertionService can be configured with options to control its behavior: ``` // wdio.conf.js import { SoftAssertionService } from 'expect-webdriverio' export const config = { // ... services: [ // ...other services [SoftAssertionService, { // Disable automatic assertion at the end of tests (default: true) autoAssertOnTestEnd: false }] ], // ... } ``` ##### autoAssertOnTestEnd[​](#autoassertontestend "Direct link to autoAssertOnTestEnd") * **Type**: `boolean` * **Default**: `true` When set to `true` (default), the service will automatically assert all soft assertions at the end of each test and throw an aggregated error if any failures are found. When set to `false`, you must manually call `expect.assertSoftFailures()` to verify soft assertions. This is useful if you want full control over when soft assertions are verified or if you want to handle soft assertion failures in a custom way. ### Known limitations[​](#known-limitations "Direct link to Known limitations") The soft assertions service is not supported under Jasmine (e.g. `@wdio/jasmine-framework`) using the global import because Jasmine is already designed to provide similar behavior out of the box. ## Default Options[​](#default-options "Direct link to Default Options") These default options below are connected to the [`waitforTimeout`](https://webdriver.io/docs/options#waitfortimeout) and [`waitforInterval`](https://webdriver.io/docs/options#waitforinterval) options set in the config. Only set the options below if you want to wait for specific timeouts for your assertions. ``` { wait: 2000, // ms to wait for expectation to succeed interval: 100, // interval between attempts } ``` If you like to pick different timeouts and intervals, set these options like this: ``` // wdio.conf.js import { setDefaultOptions } from 'expect-webdriverio' export const config = { // ... before () { setDefaultOptions({ wait: 5000 }) }, // ... } ``` ### Matcher Options[​](#matcher-options "Direct link to Matcher Options") Every matcher can take several options that allows you to modify the assertion: ##### Command Options[​](#command-options "Direct link to Command Options") | Name | Type | Details | | ----------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------- | | `wait` | number | time in ms to wait for expectation to succeed. Default: `2000` | | `interval` | number | interval between attempts. Default: `100` | | `beforeAssertion` | function | function to be called before assertion is made | | `afterAssertion` | function | function to be called after assertion is made containing assertion results, with the same expected value as `beforeAssertion` | | `message` | string | user message to prepend before assertion error | The hooks get `{ matcherName, expectedValue, options }`, and `afterAssertion` also gets `result` (`{ pass, message }`): * `matcherName` is the matcher that you called, also for an alias, e.g. `toBeChecked`, not `toBeSelected`. * `expectedValue` is the value that you gave, before the string options change it. The matchers with a name give the name and the value: `[name, value]` for `toHaveAttribute`, `toHaveElementProperty`, `toHaveCookie`, `toHaveLocalStorageItem` and `toHaveSessionStorageItem`, e.g. `['title', undefined]` for `toHaveAttribute('title')`. The boolean matchers (`toBeDisplayed`, `toExist`…) give no `expectedValue`. ##### String Options[​](#string-options "Direct link to String Options") This option can be applied in addition to the command options when strings are being asserted. | Name | Type | Details | | ------------ | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ignoreCase` | boolean | apply `toLowerCase` to both actual and expected values. A RegExp expected value is matched case-insensitively instead (the `i` flag is applied), since a pattern cannot be lowercased safely. | | `trim` | boolean | apply `trim` to actual value. Default: `true` | | `replace` | Replacer \| Replacer\[] | replace parts of the actual value that match the string/RegExp. The replacer can be a string or a function. | | `containing` | boolean | expect actual value to contain expected value, otherwise strict equal. | | `asString` | boolean | might be helpful to force converting property value to string | | `atStart` | boolean | expect actual value to start with the expected value | | `atEnd` | boolean | expect actual value to end with the expected value | | `atIndex` | number | expect actual value to have the expected value at the given index | Use one position option only: `containing`, `atStart`, `atEnd` or `atIndex`. With 2 or more, the matcher throws at once, also with `.not`: `The string options containing and atStart cannot be used together: use only one of containing, atStart, atEnd and atIndex`. `replace` applies before the position option. In a failure message, `Received` shows the actual value as is (not trimmed, lowercased or replaced), and `Expected` names the string options that alter the actual value before the comparison. The position comes first (`containing`, `startingWith`, `endingWith`, `matchingAtIndex`), then `trimmed`, `ignoringCase` and `replacing`. `trim` is on by default, so `trimmed` is named only when the actual value had spaces at the start or the end; `trim: false` alters nothing, so it is not named. When no option applies, the expected value is printed as is. For one string value, the name is in the label (`Expected (ignoringCase)`), so that Jest's diff still shows the changed characters, or the changed lines of a multiline value. In a list or per-instance values, each expected value has the name (`ignoringCase<"Foo">`). A RegExp is printed with its flags (`ignoreCase` adds `i`), and `expect.oneOf()` adds `OneOf` to the name. An element or a multi-remote instance that passed, also only because of the options, is a line with no change in the diff. When the options changed the actual value, the message also shows the value that the matcher compared: after `Received` for one value, and after each received value that failed in the diff of a list or per-instance values. It is not shown for a multiline value, or when the same received value was compared in 2 ways (e.g. with a string and with a RegExp). ``` await expect($('h1')).toHaveText('Other', { ignoreCase: true, containing: true }) // Expected (containingTrimmedIgnoringCase): "Other" // Received: " Hello World " (compared as "hello world") await expect($$('li')).toHaveText(['Foo', 'Bar'], { ignoreCase: true }) // texts: "foo", " Baz " // Array [ // ignoringCase<"Foo">, // - trimmedIgnoringCase<"Bar">, // + " Baz ", (compared as "baz") // ] ``` ##### Number Matcher[​](#number-matcher "Direct link to Number Matcher") Number matchers (`toHaveWidth`, `toHaveHeight`, `toHaveChildren`, `toBeElementsArrayOfSize`, `toBeRequestedTimes`, and each field of `toHaveSize`) take a number, a `NumberMatcher`, `expect.oneOf()` with numbers, or an asymmetric matcher as the expected value, and the command options as the next argument, e.g. `toHaveWidth({ gte: 32 }, { wait: 0 })`. | Name | Type | Details | | ----- | ------ | ---------------------- | | `eq` | number | equals | | `lte` | number | less then equals | | `gte` | number | greater than or equals | Give `eq` alone, or a range with `gte`, `lte` or both. The types reject `{}` and `eq` with `gte` or `lte`. `expect.oneOf()` with numbers is one of these numbers, which a range cannot say: `toHaveWidth(expect.oneOf(100, 200))` passes for 100 or 200, and fails for 150. An asymmetric matcher compares the number as in `toEqual`, e.g. `expect.closeTo(150.4, 0)` for a size that the browser rounds, and `expect.not.closeTo()`. A list matcher (`expect.arrayContaining()`…) throws, and `expect.multiRemote()` is only for the multi-remote elements and mocks. ##### Deep Equality[​](#deep-equality "Direct link to Deep Equality") Objects are compared with the deep equality of Jest's `toEqual`, the same in every matcher: `toHaveSize`, `toHaveElementProperty` (a property that is not a string), `expect.multiRemote()`, and the asymmetric matchers such as `expect.objectContaining()`. * An asymmetric matcher works anywhere in the value, e.g. `toHaveSize({ width: expect.any(Number), height: 32 })`. * A property that is `undefined` is ignored: `{ a: 1, b: undefined }` equals `{ a: 1 }`. For a strict comparison, use `expect(await elem.getProperty('dataset')).toStrictEqual({ a: 1 })`. * A class instance equals a plain object with the same properties. * URLs, sets, maps, dates and binary data are compared by their content, see [Deep equality of URLs, sets, maps and binary data](https://github.com/webdriverio/expect-webdriverio/blob/main/Migrations.md#deep-equality-of-urls-sets-maps-and-binary-data). * `NaN` equals `NaN`. `+0` and `-0` are not equal. ### Handling HTML Entities[​](#handling-html-entities "Direct link to Handling HTML Entities") An HTML entity is a piece of text (“string”) that begins with an ampersand (`&`) and ends with a semicolon (`;`). Entities are frequently used to display reserved characters (which would otherwise be interpreted as HTML code), and invisible characters (like non-breaking spaces, e.g. ` `). To find or interact with such element use unicode equivalent of the entity. e.g.: ```
Some Text
``` ``` const myElem = await $('div[data="Some\u00a0Value"]') await expect(myElem).toHaveAttribute('data', 'div[Some\u00a0Value') await expect(myElem).toHaveText('Some\u00a0Text') ``` You can find all unicode references in the [HTML spec](https://html.spec.whatwg.org/multipage/named-characters.html#named-character-references). **Note:** unicode is case-insensitive hence both `\u00a0` and `\u00A0` works. To find element in browser inspect, remove `u` from unicode e.g.: `div[data="Some\00a0Value"]` ## Browser Matchers[​](#browser-matchers "Direct link to Browser Matchers") Browser matchers support the multi-remote browser, with a single expected value or one per instance, see [Multi-remote Support](https://github.com/webdriverio/expect-webdriverio/blob/main/MultiRemote.md#browser-matchers). ### Browsing contexts (tab, window, frame)[​](#browsing-contexts-tab-window-frame "Direct link to Browsing contexts (tab, window, frame)") The browser matchers also accept a WebdriverIO v10 browsing context: a tab, a window or a frame that `browser.url()`, `browser.newWindow()`, `browser.browsingContexts()` or `context.frame()` give in a WebDriver BiDi session. They read the document of that context, not the one of the current context of the session. ``` const page = await browser.url('https://webdriver.io/') await expect(page).toHaveTitle(expect.stringContaining('WebdriverIO')) const frame = await page.frame(page.$('iframe')) await expect(frame).toHaveUrl(expect.stringContaining('/embed')) await expect(frame).toHaveLocalStorageItem('key') // the local storage of the frame's origin ``` * A failure message names the browser, the window or the frame, and its URL, e.g. `Expect chrome's frame (https://webdriver.io/embed) to have title`. It is the URL of the last navigation of the context (`context.url`). A frame found by its element has no URL until `navigate()` or `getUrl()`, so the message shows no URL for it. `toHaveUrl` does not show it, because the `Received` line already shows the URL. * The title of a frame document without `` is `''`. * `toHaveClipboardText` sets the clipboard permission for the whole session. In a cross-origin frame, the permissions policy of the page can block `clipboard-read`. * A browsing context is of one browser: there are no per-instance values. ### toHaveUrl[​](#tohaveurl "Direct link to toHaveUrl") Checks if browser is on a specific page. ##### Usage[​](#usage-1 "Direct link to Usage") ``` await browser.url('https://webdriver.io/') await expect(browser).toHaveUrl('https://webdriver.io') ``` ##### Usage[​](#usage-2 "Direct link to Usage") ``` await browser.url('https://webdriver.io/') await expect(browser).toHaveUrl(expect.stringContaining('webdriver')) ``` ### toHaveTitle[​](#tohavetitle "Direct link to toHaveTitle") Checks if website has a specific title. ##### Usage[​](#usage-3 "Direct link to Usage") ``` await browser.url('https://webdriver.io/') await expect(browser).toHaveTitle('WebdriverIO · Next-gen browser and mobile automation test framework for Node.js') await expect(browser).toHaveTitle(expect.stringContaining('WebdriverIO')) ``` ### toHaveClipboardText[​](#tohaveclipboardtext "Direct link to toHaveClipboardText") Checks if the browser has a specific text stored in its clipboard. ##### Usage[​](#usage-4 "Direct link to Usage") ``` import { Key } from 'webdriverio' await browser.keys([Key.Ctrl, 'a']) await browser.keys([Key.Ctrl, 'c']) await expect(browser).toHaveClipboardText('some clipboard text') await expect(browser).toHaveClipboardText(expect.stringContaining('clipboard text')) ``` ### toHaveCookie[​](#tohavecookie "Direct link to toHaveCookie") Checks if the browser has a cookie with this name, and with an optional value. The matcher reads [`getCookies({ name })`](https://webdriver.io/docs/api/browser/getCookies) and compares the value of the cookie as in `toHaveText`, with the [string options](#string-options). With no value, it checks that the cookie exists; with `.not`, that it does not exist. When the cookie does not exist, the failure message shows `Received: no cookie`. It works on a browser, a [browsing context](#browsing-contexts-tab-window-frame) and a multi-remote browser (one value for all the instances, or one per instance with `expect.multiRemote()`). ##### Usage[​](#usage-5 "Direct link to Usage") ``` await expect(browser).toHaveCookie('session') await expect(browser).toHaveCookie('lang', 'en') await expect(browser).toHaveCookie('lang', expect.oneOf('en', 'fr'), { ignoreCase: true }) await expect(browser).not.toHaveCookie('tracking') ``` ### toHaveLocalStorageItem[​](#tohavelocalstorageitem "Direct link to toHaveLocalStorageItem") Checks if browser has a specific item in localStorage with an optional value. With no value, it checks that the item exists; with `.not`, that it does not exist. A missing item never matches, also not a matcher that accepts no value, and the failure message shows `Received: no item`. ##### Usage[​](#usage-6 "Direct link to Usage") ``` await browser.url('https://webdriver.io/') // Check if localStorage item exists await expect(browser).toHaveLocalStorageItem('existingKey') // Check localStorage item with exact value await expect(browser).toHaveLocalStorageItem('someLocalStorageKey', 'someLocalStorageValue') // Check with case insensitive await expect(browser).toHaveLocalStorageItem('key', 'uppercase', { ignoreCase: true }) // Check with trim await expect(browser).toHaveLocalStorageItem('key', 'value', { trim: true }) // Check with containing await expect(browser).toHaveLocalStorageItem('key', 'long', { containing: true }) // Check with regex await expect(browser).toHaveLocalStorageItem('userId', /^user_\d+$/) ``` ### toHaveSessionStorageItem[​](#tohavesessionstorageitem "Direct link to toHaveSessionStorageItem") Checks if browser has a specific item in sessionStorage with an optional value, as [`toHaveLocalStorageItem`](#tohavelocalstorageitem). With no value, it checks that the item exists; with `.not`, that it does not exist. A missing item never matches, also not a matcher that accepts no value, and the failure message shows `Received: no item`. The session storage is of the page of the browser or of the browsing context, and of its origin. ##### Usage[​](#usage-7 "Direct link to Usage") ``` await browser.url('https://webdriver.io/') // Check if sessionStorage item exists await expect(browser).toHaveSessionStorageItem('cartId') // Check sessionStorage item with a value and string options await expect(browser).toHaveSessionStorageItem('theme', 'dark', { ignoreCase: true }) await expect(browser).not.toHaveSessionStorageItem('token') ``` ### toHaveWindowCount[​](#tohavewindowcount "Direct link to toHaveWindowCount") Checks the number of the windows and tabs of the session ([`getWindowHandles`](https://webdriver.io/docs/api/webdriver/#getwindowhandles)), e.g. after a link opens a new tab. The expected value is a number, a number range (`{ gte, lte }`), `expect.oneOf()` with numbers, or an asymmetric matcher. The assertion waits until the count matches, as the other matchers. On a browsing context, it counts the windows of its session. ##### Usage[​](#usage-8 "Direct link to Usage") ``` await $('a[target=_blank]').click() await expect(browser).toHaveWindowCount(2) await expect(browser).toHaveWindowCount({ gte: 2 }) await browser.closeWindow() await expect(browser).toHaveWindowCount(1) ``` ## Element Matchers[​](#element-matchers "Direct link to Element Matchers") ### Matching a subset of element values[​](#matching-a-subset-of-element-values "Direct link to Matching a subset of element values") Use `expect.arrayContaining()` to match values from an element collection in any order, allowing extra elements. This works with `toHaveText`, `toHaveHTML`, `toHaveAttribute`, `toHaveElementProperty`, `toHaveValue`, `toHaveElementClass`, `toHaveComputedLabel`, `toHaveComputedRole`, `toHaveId`, and `toHaveHref` (including their aliases). To compare with `expect.oneOf()`, see [Choosing the expected value](https://github.com/webdriverio/expect-webdriverio/blob/main/MultipleElements.md#choosing-the-expected-value). ``` await expect($$('header a')).toHaveText(expect.arrayContaining(['2', '1'])) await expect($$('form input')).toHaveValue(expect.arrayContaining(['b', 'a'])) await expect($$('a')).toHaveAttribute('href', expect.arrayContaining([expect.stringContaining('two.html')])) await expect($$('button')).not.toHaveComputedLabel(expect.arrayContaining(['Delete'])) ``` The other list matchers also compare the complete array: `expect.arrayOf()` (every value matches) and Jasmine's `jasmine.arrayWithExactContents()` (the same count, and each value in any order; Jasmine does not count a repeated expected value). See the comparison tables for [Jest](https://github.com/webdriverio/expect-webdriverio/blob/main/Framework.md#matching-a-list-of-elements) and [Jasmine](https://github.com/webdriverio/expect-webdriverio/blob/main/Framework.md#matching-a-list-of-elements-1). ``` await expect($$('ul > li')).toHaveText(expect.arrayOf(expect.stringMatching(/^(Tea|Coffee)$/))) await expect($$('ul > li')).toHaveText(jasmine.arrayWithExactContents(['Coffee', 'Tea'])) ``` Each attempt reads one value per element concurrently and applies the asymmetric matcher once to the complete array. Selector-backed collections are refetched on retries. Nested matchers, `.not`, and `expect.not.arrayContaining()` retain their normal matching rules. An empty collection matches `arrayContaining([])`; static empty arrays cannot be retried into a non-empty result. String comparison options such as `trim`, `ignoreCase`, and `containing` do not transform the collected values or nested matchers. Getter options still apply, such as `includeSelectorTag` for HTML and `asString` for properties. Class matching collects each element's complete class attribute, not individual class tokens. This collection comparison does not change boolean assertions or style assertions. With `some()`, a list matcher throws an error, also with `.not` (see [some()](#some)). A list matcher as the expected value of one element also throws an error, also with `.not`: in an array of expected values (`[expect.arrayContaining(['Home']), 'About']`), or in the values of `expect.multiRemote()` on a multi-remote `$()`. `toHaveElementProperty` still compares it with the property of each element, because a property value can be an array. Give the list matcher alone to compare the values of all the elements. On a multi-remote `$$()`, a list matcher in the values of `expect.multiRemote()` compares the values of all the elements of that instance, see [Multi-remote Support](https://github.com/webdriverio/expect-webdriverio/blob/main/MultiRemote.md). On a single element `$()`, a list matcher throws an error, also with `.not`: `toHaveHTML with a list matcher (arrayContaining, arrayWithExactContents or arrayOf) requires an array of elements`. The value of one element is a string, so a list matcher can never match it. Only `toHaveElementProperty` compares a list matcher with the property of a single element, because a property value can be an array. ### toBeDisplayed[​](#tobedisplayed "Direct link to toBeDisplayed") Calls [`isDisplayed`](https://webdriver.io/docs/api/element/isDisplayed/) on given element. ##### Usage[​](#usage-9 "Direct link to Usage") ``` await expect($('#someElem')).toBeDisplayed() ``` ### toExist[​](#toexist "Direct link to toExist") Calls [`isExisting`](https://webdriver.io/docs/api/element/isExisting) on given element. ##### Usage[​](#usage-10 "Direct link to Usage") ``` await expect($('#someElem')).toExist() ``` ### toBePresent[​](#tobepresent "Direct link to toBePresent") Same as `toExist`. ##### Usage[​](#usage-11 "Direct link to Usage") ``` await expect($('#someElem')).toBePresent() ``` ### toBeExisting[​](#tobeexisting "Direct link to toBeExisting") Same as `toExist`. ##### Usage[​](#usage-12 "Direct link to Usage") ``` const elem = await $('#someElem') await expect(elem).toBeExisting() ``` ### toBeFocused[​](#tobefocused "Direct link to toBeFocused") Checks if element has focus. This assertion only works in a web context. ##### Usage[​](#usage-13 "Direct link to Usage") ``` const elem = await $('#someElem') await expect(elem).toBeFocused() ``` ### toBeStable[​](#tobestable "Direct link to toBeStable") Checks if an element is stable: it does not move, e.g. at the end of a CSS animation. The matcher reads [`isStable()`](https://webdriver.io/docs/api/element/isStable) and waits until the element is stable, as long as the `wait` option allows. It works in a browser, not in a native mobile app. In a tab that is not active, `isStable()` throws an error, because the browser stops the animations there. ##### Usage[​](#usage-14 "Direct link to Usage") ``` const menu = await $('.menu') await $('.open-menu').click() await expect(menu).toBeStable() await menu.$('a').click() ``` ### toBeRequired[​](#toberequired "Direct link to toBeRequired") Checks if a form field (`<input />`, `<select>`, `<textarea>`) is required: the matcher reads its `required` property with [`getProperty('required')`](https://webdriver.io/docs/api/element/getProperty). Another element has no such property, so it is not required. For an ARIA widget, use `toHaveAttribute('aria-required', 'true')`. ##### Usage[​](#usage-15 "Direct link to Usage") ``` await expect($('#email')).toBeRequired() await expect($('#nickname')).not.toBeRequired() ``` ### toBeReadOnly[​](#tobereadonly "Direct link to toBeReadOnly") Checks if a form field (`<input />`, `<textarea>`) is read only: the matcher reads its `readOnly` property with [`getProperty('readOnly')`](https://webdriver.io/docs/api/element/getProperty). Another element has no such property, so it is not read only. For an ARIA widget, use `toHaveAttribute('aria-readonly', 'true')`. ##### Usage[​](#usage-16 "Direct link to Usage") ``` await expect($('#order-id')).toBeReadOnly() await expect($('#comment')).not.toBeReadOnly() ``` ### toHaveAttribute[​](#tohaveattribute "Direct link to toHaveAttribute") Checks if an element has a certain attribute with a specific value. A missing attribute never matches, also not a matcher that accepts no value; the failure message shows `Received: no attribute`. With no value, it checks that the attribute exists. ##### Usage[​](#usage-17 "Direct link to Usage") ``` const myInput = await $('.searchinput') await expect(myInput).toHaveAttribute('name', 'searchinput') await expect(myInput).toHaveAttribute('name', expect.stringContaining('search')) ``` Checks if an element has a specific attribute. ##### Usage[​](#usage-18 "Direct link to Usage") ``` const myInput = await $('.searchinput') await expect(myInput).toHaveAttribute('name') // With options await expect(myInput).toHaveAttribute('name', expect.anything(), { wait: 1000 }) ``` Checks if an element does not have the specified attribute. ##### Usage[​](#usage-19 "Direct link to Usage") ``` const myInput = await $('.searchinput') await expect(myInput).not.toHaveAttribute('disabled') // With options await expect(myInput).not.toHaveAttribute('disabled', expect.anything(), { wait: 1000 }) ``` ### toHaveElementClass[​](#tohaveelementclass "Direct link to toHaveElementClass") Checks if one of the classes of an element matches the expected value: a class name, a regular expression or an asymmetric matcher. Each class is compared, also with an asymmetric matcher. To compare the full `class` attribute, use `toHaveAttribute('class', ...)`. ##### Usage[​](#usage-20 "Direct link to Usage") ``` const box = await $('#purplebox') await expect(box).toHaveElementClass('box', { message: 'Not a box!' }) await expect(box).toHaveElementClass(expect.stringContaining('purp'), { message: 'Not a purple box!' }) // has any of the classes await expect(box).toHaveElementClass(expect.oneOf('purple', 'red')) // has all the classes: 1 assertion for each class await expect(box).toHaveElementClass('box') await expect(box).toHaveElementClass('purple') ``` An array of expected values works only with `$$()`: one expected value for each element. On a single element, it fails the assertion. ### toHaveElementProperty[​](#tohaveelementproperty "Direct link to toHaveElementProperty") Checks if an element has a certain property and value. A string property is compared with the [string options](#string-options). Another property (a number, a boolean, an object) is compared with [deep equality](#deep-equality), also with an asymmetric matcher in it, or with `expect.oneOf()` with numbers. A missing property (`null` or `undefined`) never matches, also not a matcher that accepts no value, except an expected `null` for one element of `$$()`; the failure message shows `Received: no property`. ##### Usage[​](#usage-21 "Direct link to Usage") ``` const elem = await $('#elem') await expect(elem).toHaveElementProperty('height', 23) await expect(elem).not.toHaveElementProperty('height', 0) await expect(elem).toHaveElementProperty('checked', true) await expect(elem).toHaveElementProperty('dataset', { id: '1', count: expect.any(String) }) ``` Checks if an element has a certain property. ##### Usage[​](#usage-22 "Direct link to Usage") ``` const elem = await $('#elem') await expect(elem).toHaveElementProperty('height') // With options await expect(elem).toHaveElementProperty('height', expect.anything(), { wait : 1 }) // Does not have height property await expect(elem).not.toHaveElementProperty('height') // With options await expect(elem).not.toHaveElementProperty('height', expect.anything(), { wait : 1 }) ``` ### toHaveValue[​](#tohavevalue "Direct link to toHaveValue") Checks if an input element has a certain value. ##### Usage[​](#usage-23 "Direct link to Usage") ``` const myInput = await $('.waitForValueEnabled') await expect(myInput).toHaveValue('Some Content', { ignoreCase: true }) await expect(myInput).toHaveValue(expect.stringContaining('Content'), { ignoreCase: true }) ``` ### toBeClickable[​](#tobeclickable "Direct link to toBeClickable") Checks if an element can be clicked by calling [`isClickable`](https://webdriver.io/docs/api/element/isClickable) on the element. ##### Usage[​](#usage-24 "Direct link to Usage") ``` await expect($('#elem')).toBeClickable() ``` ### toBeDisabled[​](#tobedisabled "Direct link to toBeDisabled") Checks if an element is disabled by calling [`isEnabled`](https://webdriver.io/docs/api/element/isEnabled) on the element. ##### Usage[​](#usage-25 "Direct link to Usage") ``` const elem = await $('#elem') await expect(elem).toBeDisabled() // same as await expect(elem).not.toBeEnabled() ``` ### toBeEnabled[​](#tobeenabled "Direct link to toBeEnabled") Checks if an element is enabled by calling [`isEnabled`](https://webdriver.io/docs/api/element/isEnabled) on the element. ##### Usage[​](#usage-26 "Direct link to Usage") ``` const elem = await $('#elem') await expect(elem).toBeEnabled() // same as await expect(elem).not.toBeDisabled() ``` ### toBeSelected[​](#tobeselected "Direct link to toBeSelected") Checks if an element is enabled by calling [`isSelected`](https://webdriver.io/docs/api/element/isSelected) on the element. ##### Usage[​](#usage-27 "Direct link to Usage") ``` await expect($('#elem')).toBeSelected() ``` ### toBeChecked[​](#tobechecked "Direct link to toBeChecked") Same as `toBeSelected`. ##### Usage[​](#usage-28 "Direct link to Usage") ``` await expect($('#elem')).toBeChecked() ``` ### toHaveComputedLabel[​](#tohavecomputedlabel "Direct link to toHaveComputedLabel") Checks if element has a specific computed WAI-ARIA label. Use `expect.oneOf()` when the element can have different labels. ##### Usage[​](#usage-29 "Direct link to Usage") ``` await browser.url('https://webdriver.io/') const elem = await $('a.navbar__link.header-github-link') await expect(elem).toHaveComputedLabel('GitHub repository') await expect(elem).toHaveComputedLabel(expect.stringContaining('repository')) ``` ##### Usage[​](#usage-30 "Direct link to Usage") ``` await browser.url('https://webdriver.io/') const elem = await $('a.navbar__link.header-github-link') await expect(elem).toHaveComputedLabel(expect.oneOf('GitHub repository', 'Private repository')) await expect(elem).toHaveComputedLabel(expect.oneOf(expect.stringContaining('GitHub'), expect.stringContaining('Private'))) ``` ### toHaveComputedRole[​](#tohavecomputedrole "Direct link to toHaveComputedRole") Checks if element has a specific computed WAI-ARIA role. Use `expect.oneOf()` when the element can have different roles. ##### Usage[​](#usage-31 "Direct link to Usage") ``` await browser.url('https://webdriver.io/') const elem = await $('[aria-label="Skip to main content"]') await expect(elem).toHaveComputedRole('region') await expect(elem).toHaveComputedRole(expect.stringContaining('ion')) ``` ##### Usage[​](#usage-32 "Direct link to Usage") ``` await browser.url('https://webdriver.io/') const elem = await $('[aria-label="Skip to main content"]') await expect(elem).toHaveComputedRole(expect.oneOf('region', 'section')) await expect(elem).toHaveComputedRole(expect.oneOf(expect.stringContaining('reg'), expect.stringContaining('sec'))) ``` ### toHaveTagName[​](#tohavetagname "Direct link to toHaveTagName") Checks if element has a specific tag name, the value of [`getTagName()`](https://webdriver.io/docs/api/element/getTagName). The value is compared as in `toHaveText`, with the [string options](#string-options). In an HTML page, the browser gives the tag name in lowercase, e.g. `button`; use `ignoreCase` for another case. ##### Usage[​](#usage-33 "Direct link to Usage") ``` const elem = await $('#submit') await expect(elem).toHaveTagName('button') await expect(elem).toHaveTagName(expect.oneOf('button', 'input')) await expect($$('nav > *')).toHaveTagName(expect.arrayContaining(['a'])) ``` ### toHaveHref[​](#tohavehref "Direct link to toHaveHref") Checks if link element has a specific link target. ##### Usage[​](#usage-34 "Direct link to Usage") ``` const link = await $('#githubRepo') await expect(link).toHaveHref('https://github.com') await expect(link).toHaveHref(expect.stringContaining('github.com')) ``` ### toHaveLink[​](#tohavelink "Direct link to toHaveLink") Same as `toHaveHref`. ##### Usage[​](#usage-35 "Direct link to Usage") ``` const link = await $('#githubRepo') await expect(link).toHaveLink('https://github.com') await expect(link).toHaveLink(expect.stringContaining('github.com')) ``` ### toHaveId[​](#tohaveid "Direct link to toHaveId") Checks if element has a specific `id` attribute. ##### Usage[​](#usage-36 "Direct link to Usage") ``` await expect($('#elem')).toHaveId('elem') ``` ### toHaveStyle[​](#tohavestyle "Direct link to toHaveStyle") Checks if an element has specific `CSS` properties. By default, values must match exactly. Only the `CSS` properties you specify are validated; other properties on the element are ignored. Each value is compared as in `toHaveText`: the [string options](#string-options) apply to each value (`trim` removes surrounding spaces from the actual value only and leaves the expected value unchanged), and a value can be a RegExp, an asymmetric matcher or `expect.oneOf()`. The failure message shows each CSS value as is, and the value that the matcher compared. The actual value is the one of [`getCSSProperty()`](https://webdriver.io/docs/api/element/getCSSProperty), which WebdriverIO normalizes: lowercase and trimmed, a color as `rgba(r,g,b,a)` with no spaces (not `white`, `#fff` or `rgb(255, 255, 255)`), and only the first font of `font-family`. A value without unit is a number, compared as its text: `font-weight: '700'`, `opacity: '0'`. Write the expected value in this form, or use `ignoreCase` for the case. As in `toHaveText`, `replace` applies first, then `ignoreCase` and the position option. On `$$()`, give one style for all the elements, or an array with one style for each element. A list matcher (`expect.arrayContaining()`, `expect.arrayOf()`, `jasmine.arrayWithExactContents()`) throws an error, also with `.not`: the matcher reads only the CSS properties that the expected value names, and a list matcher names none. ##### Usage[​](#usage-37 "Direct link to Usage") ``` // The <h1> of a page: color `rgb(255, 255, 255)`, font-family `"Helvetica Neue", Helvetica, Arial` await expect($('h1')).toHaveStyle({ 'color': 'rgba(255,255,255,1)', 'font-family': 'helvetica neue', 'font-weight': '700', 'font-size': '16px', }) await expect($('h1')).toHaveStyle({ 'font-family': 'Helvetica Neue' }, { ignoreCase: true }) await expect($('h1')).toHaveStyle({ 'color': expect.oneOf('rgba(0,0,0,1)', 'rgba(255,255,255,1)'), 'font-size': /^1[0-9]px$/, }) ``` ### toHaveText[​](#tohavetext "Direct link to toHaveText") Checks if an element matches a specific text exactly. You can also pass an asymmetric matcher like `expect.stringContaining()` for partial matches, or use `expect.oneOf()` if the element can have different possible texts. **Note:** An array of expected values is for multiple elements `$$()` only, one value per element. On a single element, it fails the assertion: use `expect.oneOf()`. ##### Usage[​](#usage-38 "Direct link to Usage") ``` await browser.url('https://webdriver.io/') const elem = await $('.hero__subtitle') // Exact match assertion await expect(elem).toHaveText('Next-gen browser and mobile automation test framework for Node.js') // Partial match assertion using stringContaining await expect(elem).toHaveText(expect.stringContaining('test framework for Node.js')) // Succeeds if one of the text options matches (v6.0.0+) await expect(elem).toHaveText(expect.oneOf('Next-gen browser and mobile automation test framework for Node.js', 'Get Started')) await expect(elem).toHaveText(expect.oneOf(expect.stringContaining('test framework for Node.js'), expect.stringContaining('Started'))) ``` If you have a list of elements like the HTML structure below: ``` <ul> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ul> ``` You can assert all of them at once using an array: ``` // Index-based: each element must match the value at its index await expect($$('ul > li')).toHaveText(['Coffee', 'Tea', 'Milk']) ``` Use `expect.arrayContaining()` to check for a subset of texts in any order. Extra elements are allowed. See [Matching a subset of element values](#matching-a-subset-of-element-values) for retry behavior, options, and other supported matchers. ``` await expect($$('ul > li')).toHaveText(expect.arrayContaining(['Tea', 'Coffee'])) await expect($$('ul > li')).toHaveText(expect.arrayContaining([expect.stringContaining('Coff')])) await expect($$('ul > li')).not.toHaveText(expect.arrayContaining(['Juice'])) ``` ### toHaveHTML[​](#tohavehtml "Direct link to toHaveHTML") Checks if an element matches a specific text exactly. You can also pass an asymmetric matcher like `expect.stringContaining()` for partial matches, or use `expect.oneOf()` if the element can have different possible texts. **Note:** An array of expected values is for multiple elements `$$()` only, one value per element. On a single element, it fails the assertion: use `expect.oneOf()`. ##### Usage[​](#usage-39 "Direct link to Usage") ``` await browser.url('https://webdriver.io/') const elem = await $('.hero__subtitle') await expect(elem).toHaveHTML('<p class="hero__subtitle">Next-gen browser and mobile automation test framework for Node.js</p>') await expect(elem).toHaveHTML(expect.stringContaining('Next-gen browser and mobile automation test framework for Node.js')) await expect(elem).toHaveHTML('Next-gen browser and mobile automation test framework for Node.js', { includeSelectorTag: false }) ``` ##### Usage[​](#usage-40 "Direct link to Usage") ``` await browser.url('https://webdriver.io/') const elem = await $('.hero__subtitle') await expect(elem).toHaveHTML(expect.oneof('Next-gen browser and mobile automation test framework for Node.js', 'Get Started'), { includeSelectorTag: false }) await expect(elem).toHaveHTML(expect.oneof(expect.stringContaining('automation test framework for Node.js'), expect.stringContaining('Started')), { includeSelectorTag: false }) ``` ### toBeDisplayedInViewport[​](#tobedisplayedinviewport "Direct link to toBeDisplayedInViewport") Checks if an element is within the viewport by calling [`isDisplayedInViewport`](https://webdriver.io/docs/api/element/isDisplayedInViewport) on the element. ##### Usage[​](#usage-41 "Direct link to Usage") ``` await expect($('#elem')).toBeDisplayedInViewport() ``` ### toHaveChildren[​](#tohavechildren "Direct link to toHaveChildren") Checks amount of the fetched element's children by calling `element.$('./*')` command. ##### Usage[​](#usage-42 "Direct link to Usage") ``` const list = await $('#selectbox') await expect(list).toHaveChildren() // the list has at least one option // same as await expect(list).toHaveChildren({ gte: 1 }) await expect(list).toHaveChildren(3) // the list has 3 options // same as await expect(list).toHaveChildren({ eq: 3 }) ``` ### toHaveWidth[​](#tohavewidth "Direct link to toHaveWidth") Checks if element has a specific width. ##### Usage[​](#usage-43 "Direct link to Usage") ``` await browser.url('http://github.com') const logo = await $('[aria-label="Homepage"] .octicon-mark-github') await expect(logo).toHaveWidth(32) // Same as await expect(logo).toHaveWidth({ eq: 32 }) // Greater/Less than equals or in between await expect(logo).toHaveWidth({ gte: 32 }) await expect(logo).toHaveWidth({ lte: 34 }) await expect(logo).toHaveWidth({ gte: 32, lte: 34 }) // One of these widths, and nothing between await expect(logo).toHaveWidth(expect.oneOf(32, 64)) // A width that the browser rounds await expect(logo).toHaveWidth(expect.closeTo(32.4, 0)) ``` ### toHaveHeight[​](#tohaveheight "Direct link to toHaveHeight") Checks if element has a specific height. ##### Usage[​](#usage-44 "Direct link to Usage") ``` await browser.url('http://github.com') const logo = await $('[aria-label="Homepage"] .octicon-mark-github') await expect(logo).toHaveHeight(32) // Same as await expect(logo).toHaveHeight({ eq: 32 }) // Greater/Less than equals or in between await expect(logo).toHaveHeight({ gte: 32 }) await expect(logo).toHaveHeight({ lte: 34 }) await expect(logo).toHaveHeight({ gte: 32, lte: 34 }) ``` ### toHaveSize[​](#tohavesize "Direct link to toHaveSize") Checks if element has a specific size, with [deep equality](#deep-equality). Each field is a [number matcher](#number-matcher) value: a number, a `NumberMatcher` (`{ gte: 30 }`), `expect.oneOf()` with numbers, or an asymmetric matcher (`expect.closeTo(150.4, 0)`). The size can also be an asymmetric matcher, e.g. `expect.objectContaining()` to check one field only. An invalid field value throws, as in `toHaveWidth`, e.g. `{}`, `gte` greater than `lte`, a string, `NaN` or a list matcher. On `$$()`, a list matcher compares the list of the sizes, e.g. `expect.arrayContaining([{ width: 100, height: 50 }])`, as `toHaveText` compares the list of the texts; on one element, it throws. A range is converted only in the fields of the size, not inside an asymmetric matcher: for one field with a range, write `{ width: { gte: 30 }, height: expect.any(Number) }`. ##### Usage[​](#usage-45 "Direct link to Usage") ``` await browser.url('http://github.com') const logo = await $('[aria-label="Homepage"] .octicon-mark-github') await expect(logo).toHaveSize({ width: 32, height: 32 }) await expect(logo).toHaveSize({ width: { gte: 30, lte: 34 }, height: expect.oneOf(32, 64) }) await expect(logo).toHaveSize(expect.objectContaining({ width: 32 })) ``` ### toBeElementsArrayOfSize[​](#tobeelementsarrayofsize "Direct link to toBeElementsArrayOfSize") Checks amount of fetched elements using [`$$`](https://webdriver.io/docs/api/element/$) command. **Note:** This matcher will update the passed array with the latest elements if the assertion passes. However, if you've reassigned the variable, you'll need to fetch the elements again. ##### Usage[​](#usage-46 "Direct link to Usage") ``` const listItems = await $$('.box') await expect(listItems).toBeElementsArrayOfSize(5) // 5 boxes // Greater/Less then await expect(listItems).toBeElementsArrayOfSize({ lte: 10 }) // same as assert.ok(listItems.length <= 10) await expect(listItems).toBeElementsArrayOfSize({ gte: 5 }) // In between await expect(listItems).toBeElementsArrayOfSize({ gte: 5, lte: 5 }) ``` With [multi-remote](https://github.com/webdriverio/expect-webdriverio/blob/main/MultiRemote.md), the size is checked per browser instance. Pass a single size that every instance must match, or one size per instance (every instance must be listed): ``` const listItems = await multiRemoteBrowser.$$('.box') await expect(listItems).toBeElementsArrayOfSize(5) // 5 boxes in every browser await expect(listItems).toBeElementsArrayOfSize(expect.multiRemote({ chrome: 5, firefox: { gte: 3 } })) ``` ### Multiple Elements Support[​](#multiple-elements-support "Direct link to Multiple Elements Support") All element matchers support arrays of elements returned from `$$()`: * **Standard Behavior:** Every element must pass. One failure fails the assertion. * **Using `.not`:** Every element must *not* meet the matcher condition. One match fails the assertion. * **Empty Arrays:** Empty element arrays will fail the assertion by default. <!-- --> * *Note:* Only the `toExist`, `toBeExisting`, and `toBePresent` matchers succeed when using `.not` on an empty element array. * **Retry / Array Refresh:** On failure or stale references, the element array is automatically re-fetched until the matcher passes or times out. * **Multi-remote:** The same rules apply per browser instance, each on its own elements, see [Multi-remote Support](https://github.com/webdriverio/expect-webdriverio/blob/main/MultiRemote.md#multiple-elements-). * See [MultipleElements.md](https://github.com/webdriverio/expect-webdriverio/blob/main/MultipleElements.md) for more details. #### Usage[​](#usage-47 "Direct link to Usage") ##### `toBe` matchers[​](#tobe-matchers "Direct link to tobe-matchers") ``` // Elements awaited selector syntax const elements = await $$('#someElements') await expect(elements).toBeDisplayed() // Elements non-awaited await expect($$('#someElements')).toBeDisplayed() // Works with filtered elemnts array await expect($$('#someElements').filter((t) => t.isExisting())).toBeDisplayed() // Using the .not modifier (Asserts NO elements are displayed) await expect($$('#someElements')).not.toBeDisplayed() ``` ##### `toHave` matchers[​](#tohave-matchers "Direct link to tohave-matchers") ``` const elements = await $$('#someElem') // Single value: checked against every element await expect(elements).toHaveAttribute('class', 'form-control') // One of: checked against every element and succeed if one of the expected text matches await expect(elements).toHaveAttribute('class', expect.oneOf('form-control1', 'form-control2')) // Array: each value checked at corresponding element index (must match length) await expect(elements).toHaveAttribute('class', ['control1', 'control2']) // Use asymmetric matchers for flexible matching await expect(elements).toHaveAttribute('class', [expect.stringContaining('control1'), 'control2']) // Use RegEx `i` for case insensitive await expect(elements).toHaveAttribute('class', [/Control1/i, 'control2']) // Use RegEx with `|` to mimic contains await expect(elements).toHaveAttribute('class', /Control1|Control2/) await expect(elements).toHaveAttribute('class', [/Control1|Control2/, 'control3']) // Elements non-awaited await expect($$('#someElem')).toHaveAttribute('class', 'form-control') // Works with filtered elements array too await expect($$('#someElem').filter(el => el.isExisting())).toHaveAttribute('class', ['control1', 'control2']) ``` ## Network Matchers[​](#network-matchers "Direct link to Network Matchers") Network matchers also support the mocks of a multi-remote `mock()`, with one expected value for every browser instance or, with `expect.multiRemote()`, one per instance, see [Multi-remote Support](https://github.com/webdriverio/expect-webdriverio/blob/main/MultiRemote.md#network-matchers). ### toBeRequested[​](#toberequested "Direct link to toBeRequested") Checks that mock was called ##### Usage[​](#usage-48 "Direct link to Usage") ``` const mock = browser.mock('**/api/todo*') await expect(mock).toBeRequested() ``` ### toBeRequestedTimes[​](#toberequestedtimes "Direct link to toBeRequestedTimes") Checks that mock was called for the expected amount of times ##### Usage[​](#usage-49 "Direct link to Usage") ``` const mock = browser.mock('**/api/todo*') await expect(mock).toBeRequestedTimes(2) // same as await expect(mock).toBeRequestedTimes({ eq: 2 }) // request called at least 5 times but less than 11 await expect(mock).toBeRequestedTimes({ gte: 5, lte: 10 }) ``` ### toBeRequestedWith[​](#toberequestedwith "Direct link to toBeRequestedWith") Checks that mock was called according to the expected options. Most of the options supports expect/jasmine partial matchers like [expect.objectContaining](https://jestjs.io/docs/expect#expectobjectcontainingobject) ##### Usage[​](#usage-50 "Direct link to Usage") ``` const mock = browser.mock('**/api/todo*', { method: 'POST' }) await expect(mock).toBeRequestedWith({ url: 'http://localhost:8080/api/todo', // [optional] string | function | custom matcher method: 'POST', // [optional] string | array statusCode: 200, // [optional] number | array requestHeaders: { Authorization: 'foo' }, // [optional] object | function | custom matcher responseHeaders: { Authorization: 'bar' }, // [optional] object | function | custom matcher postData: { title: 'foo', description: 'bar' }, // [optional] object | function | custom matcher response: { success: true }, // [optional] object | function | custom matcher }) await expect(mock).toBeRequestedWith({ url: expect.stringMatching(/.*\/api\/.*/i), method: ['POST', 'PUT'], // either POST or PUT statusCode: [401, 403], // either 401 or 403 requestHeaders: headers => headers.Authorization.startsWith('Bearer '), postData: expect.objectContaining({ released: true, title: expect.stringContaining('foobar') }), response: r => Array.isArray(r) && r.data.items.length === 20 }) ``` > **Note on `postData`/`response` timing:** unlike the other options, the request/response body is collected asynchronously (an extra round-trip after the request/response headers are already available), so it may not be attached to a call yet at the very first check. Regular assertions retry within their `wait` timeout and pick it up once it arrives. `.not.toBeRequestedWith({ postData / response })` also retries within `wait` - but only while there's a call that already matches every other criterion and is just waiting on its body to attach; if nothing matches at all (wrong URL, no call made, etc.) it still resolves immediately, same as any other `.not` assertion. The one residual case this can't close: if the body genuinely takes longer to arrive than your configured `wait`, a `.not` assertion can still report a false pass. If you rely on `.not` with `postData`/`response` and see intermittent false passes, increase `wait` (or await a signal that the request has fully completed) before asserting. ## Snapshot Matcher[​](#snapshot-matcher "Direct link to Snapshot Matcher") WebdriverIO supports basic snapshot tests as well as DOM snapshot testing. The snapshot matchers need the snapshot service: it knows the current test, and it writes the snapshot files. The WebdriverIO testrunner runs it by itself. Without the testrunner, for example in a Node.js script with `remote()`, the matchers throw `Snapshot service is not initialized`. Then call the hooks of the service yourself: `beforeTest()` before each test, with the file of the snapshots and the name of the test, and `after()` after the tests of the file, to write the snapshot file. ``` import { fileURLToPath } from 'node:url' import { remote } from 'webdriverio' import { expect, SnapshotService } from 'expect-webdriverio' const snapshotService = SnapshotService.initiate() const browser = await remote({ capabilities: { browserName: 'chrome' } }) try { // The snapshots go to `__snapshots__/<file name>.snap`, next to the file, under the name `My page > has a button 1` await snapshotService.beforeTest({ file: fileURLToPath(import.meta.url), parent: 'My page', title: 'has a button' }) await browser.url('https://example.com') await expect(browser.$('h1')).toMatchSnapshot() } finally { // Also when an assertion fails: write the snapshot file, then close the browser try { await snapshotService.after() } finally { await browser.deleteSession() } } ``` `SnapshotService.initiate()` takes the options of the service, e.g. `{ updateState: 'all' }` to update the snapshots, or `resolveSnapshotPath`. With Jest or Mocha, call `beforeTest()` in `beforeEach`, and `after()` in `afterAll` (or `after`). ### toMatchSnapshot[​](#tomatchsnapshot "Direct link to toMatchSnapshot") Checks if any arbitrary object matches a certain value. If you pass in an [`WebdriverIO.Element`](https://webdriver.io/docs/api/element) it will automatically snapshot the [`outerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML) state of it. ##### Usage[​](#usage-51 "Direct link to Usage") ``` // snapshot arbitrary objects (no "await" needed here) expect({ foo: 'bar' }).toMatchSnapshot() // snapshot `outerHTML` of WebdriverIO.Element (DOM snapshot, requires "await") await expect($('elem')).toMatchSnapshot() // snapshot `outerHTML` of multi-remote elements, $() or $$(): shared by every instance, else keyed by instance name (requires "await") await expect(multiRemoteBrowser.$('elem')).toMatchSnapshot() await expect(multiRemoteBrowser.$$('.box')).toMatchSnapshot() // snapshot `outerHTML` of every element of $$() as an array (requires "await") await expect($$('.box')).toMatchSnapshot() // snapshot result of element command await expect($('elem').getCSSProperty('background-color')).toMatchSnapshot() ``` ### toMatchInlineSnapshot[​](#tomatchinlinesnapshot "Direct link to toMatchInlineSnapshot") Similarly, you can use the `toMatchInlineSnapshot()` to store the snapshot inline within the test file. For example, given: ``` await expect($('#secondPageLink')).toMatchInlineSnapshot() ``` Instead of creating a snapshot file, WebdriverIO will modify the test file directly to update the snapshot as a string: ``` await expect($('#secondPageLink')).toMatchInlineSnapshot(`"<a href="./two.html" id="secondPageLink">two</a>"`) ``` With `$$()`, the snapshot is the `outerHTML` of every element as an array: ``` await expect($$('header a')).toMatchInlineSnapshot(` [ "<a href="pointer.html">3</a>", "<a href="gestureTest.html">2</a>", "<a href="index.html">1</a>", ] `) ``` ## Visual Snapshot Matchers[​](#visual-snapshot-matchers "Direct link to Visual Snapshot Matchers") The following matcher are implemented as part of the `@wdio/visual-service` plugin and only available when the service is set up. Make sure you follow the [set-up instructions](https://webdriver.io/docs/visual-testing) accordingly. ### toMatchElementSnapshot[​](#tomatchelementsnapshot "Direct link to toMatchElementSnapshot") Checks that if given element matches with snapshot of baseline. ##### Usage[​](#usage-52 "Direct link to Usage") ``` await expect($('#purplebox')).toMatchElementSnapshot('purpleBox', 0, { // options }) ``` The expected result is by default `0`, so you can write the same assertion as: ``` await expect($('#purplebox')).toMatchElementSnapshot('purpleBox', { // options }) ``` or not pass in any options at all: ``` await expect($('#purplebox')).toMatchElementSnapshot() ``` ### toMatchScreenSnapshot[​](#tomatchscreensnapshot "Direct link to toMatchScreenSnapshot") Checks that if current screen matches with snapshot of baseline. ##### Usage[​](#usage-53 "Direct link to Usage") ``` await expect(browser).toMatchScreenSnapshot('partialPage', 0, { // options }) ``` The expected result is by default `0`, so you can write the same assertion as: ``` await expect(browser).toMatchScreenSnapshot('partialPage', { // options }) ``` or not pass in any options at all: ``` await expect(browser).toMatchScreenSnapshot('partialPage') ``` ### toMatchFullPageSnapshot[​](#tomatchfullpagesnapshot "Direct link to toMatchFullPageSnapshot") Checks that if the full page screenshot matches with snapshot of baseline. ##### Usage[​](#usage-54 "Direct link to Usage") ``` await expect(browser).toMatchFullPageSnapshot('fullPage', 0, { // options }) ``` The expected result is by default `0`, so you can write the same assertion as: ``` await expect(browser).toMatchFullPageSnapshot('fullPage', { // options }) ``` or not pass in any options at all: ``` await expect(browser).toMatchFullPageSnapshot('fullPage') ``` ### toMatchTabbablePageSnapshot[​](#tomatchtabbablepagesnapshot "Direct link to toMatchTabbablePageSnapshot") Checks that if the full page screenshot including tab marks matches with snapshot of baseline. ##### Usage[​](#usage-55 "Direct link to Usage") ``` await expect(browser).toMatchTabbablePageSnapshot('tabbable', 0, { // options }) ``` The expected result is by default `0`, so you can write the same assertion as: ``` await expect(browser).toMatchTabbablePageSnapshot('tabbable', { // options }) ``` or not pass in any options at all: ``` await expect(browser).toMatchTabbablePageSnapshot('tabbable') ``` ## Using regular expressions[​](#using-regular-expressions "Direct link to Using regular expressions") You can also directly use regular expressions for all matchers that do text comparison. ##### Usage[​](#usage-56 "Direct link to Usage") ``` await browser.url('https://webdriver.io/') const elem = await $('.hero__subtitle') await expect(elem).toHaveText(/node\.js/i) await expect(elem).toHaveText(expect.oneOf(/node\.js/i, 'Get Started')) await expect(browser).toHaveTitle(/webdriverio/i) await expect(browser).toHaveUrl(/webdriver\.io/) await expect(elem).toHaveElementClass(/Hero__Subtitle/i) ``` ## Default Matchers[​](#default-matchers "Direct link to Default Matchers") In addition to the WebdriverIO matchers, `expect-webdriverio` also provides basic matchers from Jest's [expect](https://jestjs.io/docs/expect) library. ``` // Equality expect(2 + 2).toBe(4); expect({a: 1}).toEqual({a: 1}); expect([1, 2, 3]).toStrictEqual([1, 2, 3]); expect(2 + 2).not.toBe(5); // Truthiness expect(null).toBeNull(); expect(undefined).toBeUndefined(); expect(0).toBeFalsy(); expect(1).toBeTruthy(); expect(NaN).toBeNaN(); // Numbers expect(4).toBeGreaterThan(3); expect(4).toBeGreaterThanOrEqual(4); expect(4).toBeLessThan(5); expect(4).toBeLessThanOrEqual(4); expect(0.2 + 0.1).toBeCloseTo(0.3, 5); // Strings expect('team').toMatch(/team/); expect('Christoph').toContain('stop'); // Arrays and iterables expect([1, 2, 3]).toContain(2); expect([{a: 1}, {b: 2}]).toContainEqual({a: 1}); expect([1, 2, 3]).toHaveLength(3); // Objects expect({a: 1, b: 2}).toHaveProperty('a'); expect({a: {b: 2}}).toHaveProperty('a.b', 2); // Errors expect(() => { throw new Error('error!') }).toThrow('error!'); expect(() => { throw new TypeError('wrong type') }).toThrow(TypeError); // Asymmetric matchers expect({foo: 'bar', baz: 1}).toEqual(expect.objectContaining({foo: expect.any(String)})); expect([1, 2, 3]).toEqual(expect.arrayContaining([2])); expect('abc').toEqual(expect.stringContaining('b')); expect('abc').toEqual(expect.stringMatching(/b/)); expect(123).toEqual(expect.any(Number)); // Others expect(new Set([1, 2, 3])).toContain(2); // .resolves / .rejects (async) await expect(Promise.resolve(42)).resolves.toBe(42); await expect(Promise.reject(new Error('fail'))).rejects.toThrow('fail'); ``` ### Jasmine[​](#jasmine "Direct link to Jasmine") For Jasmine, see the official documentation for [expect/expectAsync](https://jasmine.github.io/api/edge/global.html#expect), [matchers](https://jasmine.github.io/tutorials/your_first_suite#section-Matchers), and [async-matchers](https://jasmine.github.io/api/edge/async-matchers.html). **Note:** * With the global `expect` of `@wdio/jasmine-framework`, the Jasmine synchronous matchers stay synchronous. The WebdriverIO matchers and the Jasmine async matchers return a promise. See [Jasmine](https://github.com/webdriverio/expect-webdriverio/blob/main/Framework.md#jasmine). * Default matchers are still available if you import `expect` directly from `expect-webdriverio` instead of using the global. ## Modifiers[​](#modifiers "Direct link to Modifiers") ### .not[​](#not "Direct link to .not") WebdriverIO supports usage of modifiers as `.not` and it will wait until the reverse condition is meet ``` // Wait until the element is no longer present await expect($('element')).not.toBeDisplayed() // Wait until the text is no more 'some title' await expect(browser).not.toHaveTitle('some title') ``` In case immediate assertion is required, use `{ wait: 0 }` ``` // Ensure element is not present right now await expect($('element')).not.toBeDisplayed({ wait: 0 }) // Ensure the text is not 'some title' right now await expect(browser).not.toHaveTitle('some title', { wait: 0 }) ``` **Note:** You can pair `.not` with asymmetric matchers, but to enable the wait-until behavior, `.not` must be used directly on the `expect()` call. ### some()[​](#some "Direct link to some()") since: v6.0.0 The custom `some()` function (distinct syntax compared to `.not`) allows you to assert that at least one element from multiple elements meets the assertion. ``` import { some } from 'expect-webdriverio/api' // Allow to succeed only if one element matches (or not match) // Succeeds if at least one element matches either 'optionA' or 'optionB' await expect(some($$('elements'))).toHaveText(expect.oneOf('optionA', 'optionB')); // Succeeds if at least one element does not matches either 'forbiddenTextA' or 'forbiddenTextB' await expect(some($$('elements'))).not.toHaveText(/forbiddenTextA|forbiddenTextB/); // Succeeds if the first element matches 'valueForIndex0' OR the second matches 'valueForIndex1' await expect(some($$('elements'))).toHaveText(['valueForIndex0', 'valueForIndex1']); ``` A list matcher (`expect.arrayContaining()`, `expect.arrayOf()`, `jasmine.arrayWithExactContents()`) throws an error with `some()`, also with `.not`, and also in an array of expected values or in the values of `expect.multiRemote()`: `some()` checks each element alone, and the value of one element is not a list. Use the list matcher without `some()`: on `$$()`, it compares the values of all the elements, so `expect.arrayContaining(['Home'])` passes when one element has the value `Home`. Only `toHaveElementProperty` compares a list matcher with the property of each element, because a property value can be an array. **Note**: With [multi-remote](https://github.com/webdriverio/expect-webdriverio/blob/main/MultiRemote.md), `some()` requires at least one matching element in **every** browser instance. ## Asymmetric Matchers[​](#asymmetric-matchers "Direct link to Asymmetric Matchers") WebdriverIO supports usage of asymmetric matchers wherever you compare text values, e.g.: ``` await expect(browser).toHaveTitle(expect.stringContaining('some title')) ``` or ``` await expect(browser).toHaveTitle(expect.not.stringContaining('some title')) ``` ### expect.multiRemote()[​](#expectmultiremote "Direct link to expect.multiRemote()") With [multi-remote](https://github.com/webdriverio/expect-webdriverio/blob/main/MultiRemote.md), passes one expected value per browser instance, keyed by instance name. Every instance must be listed. ``` await expect(multiRemoteBrowser).toHaveTitle(expect.multiRemote({ chrome: 'WebdriverJS Testpage', firefox: expect.stringContaining('Testpage') })) await expect(multiRemoteBrowser.$('header h1')).toHaveStyle(expect.multiRemote({ chrome: { color: 'red' }, firefox: { color: 'blue' } })) ``` See [Expected Values](https://github.com/webdriverio/expect-webdriverio/blob/main/MultiRemote.md#expected-values) for the plain object shorthand. ### Jasmine[​](#jasmine-1 "Direct link to Jasmine") Under `@wdio/jasmine-framework`, some Jasmine asymmetric matchers now work with WebdriverIO matchers and the global import. ``` // Jasmine's stringContaining works just like the one from expect await expect(browser).toHaveTitle(jasmine.stringContaining('some title')) await expect(browser).toHaveTitle(expect.stringContaining('some title')) // Jasmine's stringMatching works await expect(browser).toHaveUrl(jasmine.stringMatching('/WebdriverIO/')) // Jasmine's any & anything works await expect(browser).toHaveUrl(jasmine.any(String)) await expect(browser).toHaveUrl(jasmine.anything()) // Jasmine's objectContaining works with Network Matchers await expect(mock).toBeRequestedWith({ method: 'POST', requestHeaders: expect.objectContaining({ Authorization: 'foo' }), }) // Jasmine's any & anything works with Network Matchers await expect(mock).toBeRequestedWith({ method: 'POST', url: jasmine.any(String), requestHeaders: jasmine.anything(), }) ``` `jasmine.arrayContaining()` and `jasmine.arrayWithExactContents()` are also supported for [element collection values](#matching-a-subset-of-element-values), including nested Jasmine matchers. Limitations with Jasmine collection and object matchers may still apply in other assertion contexts. ## Types Definition[​](#types-definition "Direct link to Types Definition") ### TypeScript[​](#typescript "Direct link to TypeScript") If you are using the [WDIO Testrunner](https://webdriver.io/docs/clioptions) everything will be automatically setup. Just follow the [setup guide](https://webdriver.io/docs/typescript#framework-setup) from the docs. However if you run WebdriverIO with a different testrunner or in a simple Node.js script you will need to add `expect-webdriverio` to `types` in the `tsconfig.json`. * `"expect-webdriverio"` for everyone except Jasmine/Jest users. * `"expect-webdriverio/jasmine"` for [Jasmine](https://jasmine.github.io/) without `@wdio/jasmine-framework` * `"expect-webdriverio/jest"` for [Jest](https://jestjs.io/) * `"expect-webdriverio/expect-global"` // Optional, if you wish to use expect of `expect-webdriverio` globally without explicit import ### JavaScript (VSCode)[​](#javascript-vscode "Direct link to JavaScript (VSCode)") It's required to create [`jsconfig.json`](https://code.visualstudio.com/docs/languages/jsconfig) in project root and refer to the type definitions to make autocompletion work in vanilla js. ``` { "include": [ "**/*.js", "**/*.json", "node_modules/expect-webdriverio" ] } ``` ### Jasmine[​](#jasmine-2 "Direct link to Jasmine") * With [`@wdio/jasmine-framework`](https://www.npmjs.com/package/@wdio/jasmine-framework): add `"@wdio/jasmine-framework"` to `types`, after `"@wdio/globals/types"`. It types its hybrid global `expect`: the Jasmine matchers stay synchronous, and the WebdriverIO matchers return a promise. Do not add `"expect-webdriverio/jasmine"`. * With Jasmine alone: add `"expect-webdriverio/jasmine"`. It types the WebdriverIO matchers on `expectAsync`, which you register yourself. See [Framework.md](https://github.com/webdriverio/expect-webdriverio/blob/main/Framework.md#jasmine) for the details. ### Custom matchers[​](#custom-matchers "Direct link to Custom matchers") See [TypeScript](https://github.com/webdriverio/expect-webdriverio/blob/main/CustomMatchers.md#typescript) in Custom Matchers to type your own matchers. ## Framework Integration[​](#framework-integration "Direct link to Framework Integration") `expect-webdriverio` extends Jest's [`expect`](https://www.npmjs.com/package/expect) API with WebDriverIO-specific enhancements. It can be used standalone or within other testing environments. ### Compatibility[​](#compatibility "Direct link to Compatibility") It is highly recommended to use this package with the [WDIO Testrunner](https://webdriver.io/docs/clioptions) and a compatible framework adapter, which together provide a plug-and-play experience. Pair it with your preferred framework using the appropriate adapter: * **[Mocha](https://mochajs.org/):** Use [`@wdio/mocha-framework`](https://www.npmjs.com/package/@wdio/mocha-framework) * **[Cucumber](https://www.npmjs.com/package/@cucumber/cucumber):** Use [`@wdio/cucumber-framework`](https://www.npmjs.com/package/@wdio/cucumber-framework) * **[Jasmine](https://jasmine.github.io/):** Use [`@wdio/jasmine-framework`](https://www.npmjs.com/package/@wdio/jasmine-framework) * **[Jest](https://jestjs.io/):** Works (no framework exists; requires manual configuration—see note below) > **Note:** When using **Jest**, or when running **outside of the WDIO Testrunner without a compatible framework adapter**, additional manual configuration may be required, such as adding types to your [`tsconfig.json`](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) and configuring WDIO matchers, soft assertions, and the snapshot service. #### Playgrounds[​](#playgrounds "Direct link to Playgrounds") Example playgrounds are available, though their `tsconfig.json` files may use modified configurations for development purposes. * See Mocha, Jasmine, and Jest [examples here](https://github.com/webdriverio/expect-webdriverio/tree/main/playgrounds). #### Mocha[​](#mocha "Direct link to Mocha") When pairing with [Mocha](https://mochajs.org/), you can use `expect-webdriverio` directly or combine it with [`chai`](https://www.chaijs.com/) (or any other assertion library). * It is strongly recommended to leverage `@wdio/mocha-framework` for automatic configuration and a plug-and-play experience. * See [Mocha playground example here](https://github.com/webdriverio/expect-webdriverio/tree/main/playgrounds/mocha) ##### Standalone[​](#standalone "Direct link to Standalone") No import is required; everything is set globally. ``` describe('My tests', async () => { it('should verify my browser to have the expected url', async () => { await expect(browser).toHaveUrl('https://example.com') }) }) ``` Minimum types expected in `tsconfig.json`: When depending on `@wdio/mocha-framework` ``` { "compilerOptions": { "types": [ "@wdio/mocha-framework", "@wdio/globals/types" ] } } ``` When not depending on `@wdio/mocha-framework` ``` { "compilerOptions": { "types": [ "@types/mocha", "expect-webdriverio/expect-global" ] } } ``` ##### Chai[​](#chai "Direct link to Chai") `expect-webdriverio` can coexist with the [Chai](https://www.chaijs.com/) assertion library by importing both libraries explicitly. See also this [documentation](https://webdriver.io/docs/assertion/#migrating-from-chai). #### Jest[​](#jest "Direct link to Jest") You can use `expect-webdriverio` with [Jest](https://jestjs.io/) by leveraging either [`@types/jest`](https://www.npmjs.com/package/@types/jest) (which provides global ambient support) or [`@jest/globals`](https://www.npmjs.com/package/@jest/globals) alone. * Note: Jest maintainers do not officially support [`@types/jest`](https://www.npmjs.com/package/@types/jest). Should this package become outdated or experience issues, support may be dropped. * Note: With Jest, the matchers `toMatchSnapshot` and `toMatchInlineSnapshot` are overloaded. To resolve the types correctly, `expect-webdriverio/jest` must be listed last. * Note: WebdriverIO does not provide a compatible framework adapter for Jest; manual configuration is required. ##### With `@types/jest`[​](#with-typesjest "Direct link to with-typesjest") When paired with [`@types/jest`](https://www.npmjs.com/package/@types/jest), no imports are required in your test files. Global ambient types are already defined correctly, allowing you to use Jest's `expect` directly after some manual configuration. * Note: `jest` and `ts-jest` are also required. * See the [Jest with `@types/jest` playground example](https://github.com/webdriverio/expect-webdriverio/tree/main/playgrounds/jest). Since no WDIO Testrunner and framework adapter are used, additional prerequisite configuration is required. ###### Option 1: Replace the global expect with the `expect-webdriverio` instance:[​](#option-1-replace-the-global-expect-with-the-expect-webdriverio-instance "Direct link to option-1-replace-the-global-expect-with-the-expect-webdriverio-instance") ``` import { expect } from "expect-webdriverio"; (globalThis as any).expect = expect; ``` ###### Option 2: Extend Jest's global `expect` with custom matchers and soft assertions:[​](#option-2-extend-jests-global-expect-with-custom-matchers-and-soft-assertions "Direct link to option-2-extend-jests-global-expect-with-custom-matchers-and-soft-assertions") If not already set, define a file path for `setupFilesAfterEnv` in your Jest configuration: ``` setupFilesAfterEnv: ['./jest.setup.after-env.ts'], ``` Then, add the following configuration to your `jest.setup.after-env.ts` file: ``` import { expect } from "@jest/globals"; import { wdioCustomMatchers } from "expect-webdriverio"; beforeAll(async () => { // Extend the imported Jest expect instance with WDIO matchers expect.extend(wdioCustomMatchers); }); ``` ###### Optional: For soft assertions, copy them from the `expect-webdriverio` instance:[​](#optional-for-soft-assertions-copy-them-from-the-expect-webdriverio-instance "Direct link to optional-for-soft-assertions-copy-them-from-the-expect-webdriverio-instance") ``` import { expect } from "@jest/globals"; import { expect as wdioExpect } from "expect-webdriverio"; beforeAll(async () => { for (const name of ["soft", "getSoftFailures", "assertSoftFailures", "clearSoftFailures"] as const) { Object.defineProperty(expect, name, { value: wdioExpect[name] }); } }); ``` Then, as shown below, no imports are required and we can use WDIO matchers directly on Jest's `expect`: ``` describe('My tests', async () => { it('should verify my browser to have the expected url', async () => { await expect(browser).toHaveUrl('https://example.com') }) }) ``` Expected in `tsconfig.json`: ``` { "compilerOptions": { "types": [ "@types/jest", "expect-webdriverio/jest" // Must be last for overloaded matchers `toMatchSnapshot` and `toMatchInlineSnapshot` ] } } ``` ##### With Only `@jest/globals`[​](#with-only-jestglobals "Direct link to with-only-jestglobals") When using [`@jest/globals`](https://www.npmjs.com/package/@jest/globals) directly instead of global ambient types, you explicitly import Jest's utilities. To use `expect-webdriverio` you have two approaches: * Note: No example playground available ###### Option 1: Explicit Imports[​](#option-1-explicit-imports "Direct link to Option 1: Explicit Imports") ``` import { expect } from 'expect-webdriverio' import { describe, it, expect as jestExpect } from '@jest/globals' describe('My tests', async () => { it('should verify my browser to have the expected url', async () => { await expect(browser).toHaveUrl('https://example.com') // Jest's native expect is still usable jestExpect(myFunction).toHaveBeenCalled() }) }) ``` No `types` are expected in `tsconfig.json`. ###### Option 2: Global Type Definition[​](#option-2-global-type-definition "Direct link to Option 2: Global Type Definition") To avoid explicitly importing `expect` from `expect-webdriverio` in every test file, add the global entry point to your `tsconfig.json`: ``` { "compilerOptions": { "types": ["expect-webdriverio/expect-global"] } } ``` ###### Augmenting `@jest/globals` JestMatchers[​](#augmenting-jestglobals-jestmatchers "Direct link to augmenting-jestglobals-jestmatchers") Unlike `@types/jest`, `@jest/globals` does not export a global namespace that can be easily extended. While module augmentation is possible, it does not support inheriting matchers via the extends keyword. Supporting it would require manually duplicating all expect-webdriverio matcher interfaces inside the module declaration. This limitation is a known [upstream issue](https://github.com/jestjs/jest/issues/12424) tracked in Jest. ##### Matching a list of elements[​](#matching-a-list-of-elements "Direct link to Matching a list of elements") On `$$()`, the expected value decides how the texts (or other values) of the elements are compared. These are the matchers of the `expect` package, so they are the same with Mocha. Results with `toHaveText` on `$$('li')`: | Expected value | Passes when | Order | Other elements | String options (`trim`, `ignoreCase`…) | | ---------------------------------------------------------- | -------------------------------------------------------------- | ----- | -------------- | -------------------------------------- | | `['Coffee', 'Tea']` | each element has the text at its index | fixed | no: same count | applied | | `'Tea'` | every element has the text | - | no | applied | | `expect.oneOf('Tea', 'Coffee')` | each element has one of the texts; a text can be missing | any | no | applied | | `expect.arrayContaining(['Tea', 'Coffee'])` | each text is on at least one element | any | allowed | not applied | | `expect.not.arrayContaining(['Milk'])` | at least one of the texts is on no element | any | allowed | not applied | | `expect.arrayOf(expect.stringMatching(/^(Tea\|Coffee)$/))` | every element matches the matcher; also passes with no element | any | no | not applied | | `some($$('li'))` with `'Tea'` | at least one element has the text | any | allowed | applied | A list matcher (`arrayContaining`, `arrayOf`) compares the raw values of all the elements at once. The string options do not change these values: use a nested matcher, e.g. `expect.stringMatching(/tea/i)`. A list matcher throws an error with `some()`, which checks each element alone. ``` // <li>Coffee</li> <li>Tea</li> await expect($$('li')).toHaveText(['Coffee', 'Tea']) // passes await expect($$('li')).toHaveText(['Tea', 'Coffee']) // fails: the order is different await expect($$('li')).toHaveText(expect.oneOf('Tea', 'Coffee')) // passes await expect($$('li')).toHaveText(expect.arrayContaining(['Tea'])) // passes: Coffee is allowed await expect($$('li')).toHaveText(expect.not.arrayContaining(['Milk'])) // passes await expect($$('li')).toHaveText(expect.arrayOf(expect.stringMatching(/^(Tea|Coffee)$/))) // passes await expect(some($$('li'))).toHaveText('Tea') // passes // <li>Tea</li> <li>Tea</li> await expect($$('li')).toHaveText(expect.arrayContaining(['Tea', 'Coffee'])) // fails: Coffee is missing // <li> Coffee </li> <li> Tea </li> await expect($$('li')).toHaveText(['Coffee', 'Tea']) // passes: the default trim applies await expect($$('li')).toHaveText(expect.arrayContaining(['Coffee'])) // fails: the value is " Coffee " ``` #### Jasmine[​](#jasmine-3 "Direct link to Jasmine") When paired with [Jasmine](https://jasmine.github.io/), [`@wdio/jasmine-framework`](https://www.npmjs.com/package/@wdio/jasmine-framework) is required to ensure proper runtime configuration. The adapter registers the WDIO matchers with `addAsyncMatchers` and sets a hybrid global `expect`: * Jasmine synchronous matchers (`toBe`, `toEqual`, ...) stay synchronous and return `void`. * WDIO matchers and Jasmine async matchers (`toBeResolved`, ...) go to `expectAsync` and return a promise: always `await` them. Jasmine collects the failures until the spec ends (built-in soft assertions), so the `expect-webdriverio` SoftAssertion service is neither required nor supported. ##### Global `expect` with `@wdio/jasmine-framework`[​](#global-expect-with-wdiojasmine-framework "Direct link to global-expect-with-wdiojasmine-framework") `@wdio/jasmine-framework` v10 has the types of its hybrid `expect`. * See [example playgrounds](https://github.com/webdriverio/expect-webdriverio/tree/main/playgrounds/jasmine/test/specs/globalImport) ``` describe('My tests', async () => { it('should verify my browser to have the expected url', async () => { await expect(browser).toHaveUrl('https://example.com') // Jasmine synchronous matcher expect(true).toBe(true) }) }) ``` Expected in `tsconfig.json`: ``` { "compilerOptions": { "types": [ "@types/jasmine", "@wdio/globals/types", "@wdio/jasmine-framework" ] } } ``` `expectAsync` also has the WDIO matchers, e.g. `await expectAsync(browser).toHaveUrl('https://example.com')`, typed since `@wdio/jasmine-framework` 10.0.2. Since `@wdio/jasmine-framework` 10.0.2, `expect.extend()` adds custom matchers to the global `expect`. Call it before the tests run: at the top level of a spec file, or in the `before` hook of the configuration, not in a `beforeAll()`, because the framework reads the matchers before the first `beforeAll()` of the specs. The matchers become Jasmine async matchers, so `await` them. The types of the global `expect` have `extend()` since `@wdio/jasmine-framework` 10.1.0 ([webdriverio#15982](https://github.com/webdriverio/webdriverio/pull/15982)). With 10.0.2, call it on `import { expect } from '@wdio/globals'`, which has the type and adds the matchers to the same global `expect`. See [Custom Matchers](https://webdriver.io/docs/custommatchers) and the [playground spec](https://github.com/webdriverio/expect-webdriverio/tree/main/playgrounds/jasmine/test/specs/globalImport/custom-matchers.test.ts). > Note: When using Jasmine, Jest's expect matchers are not leveraged, meaning standard Jest-specific assertion matchers are unavailable. ##### Jasmine without `@wdio/jasmine-framework`[​](#jasmine-without-wdiojasmine-framework "Direct link to jasmine-without-wdiojasmine-framework") With Jasmine 6 alone, register the WDIO matchers on `expectAsync` yourself, and add `expect-webdriverio/jasmine` to `types`. Do not use `expect-webdriverio/jasmine` with `@wdio/jasmine-framework`, which has its own types. ``` describe('My tests', async () => { it('should verify my browser to have the expected url', async () => { await expectAsync(browser).toHaveUrl('https://example.com') // Standard Jasmine async matchers work as expected await expectAsync(Promise.resolve(true)).toBeResolvedTo(true) }) }) ``` Expected in `tsconfig.json`: ``` { "compilerOptions": { "types": [ "@types/jasmine", "expect-webdriverio/jasmine" ] } } ``` ##### Use `expect` from `expect-webdriverio`[​](#use-expect-from-expect-webdriverio "Direct link to use-expect-from-expect-webdriverio") The `expect` export from `expect-webdriverio` remains available under Jasmine if you prefer an explicit import strategy. See the [playground example](https://github.com/webdriverio/expect-webdriverio/tree/main/playgrounds/jasmine/test/specs/expect-wdioImport). ``` import { expect as wdioExpect } from 'expect-webdriverio' describe('My tests', async () => { it('should verify my browser to have the expected url', async () => { await wdioExpect(browser).toHaveUrl('https://example.com') // Does not require await wdioExpect(true).toBe(true) }) }) ``` > Since `@wdio/jasmine-framework` 10.0.2, the types of this `expect` keep the Jest matchers, as at runtime. ##### Asymmetric matchers[​](#asymmetric-matchers-1 "Direct link to Asymmetric matchers") * `jasmine.any(Type)`, `jasmine.anything()`, `jasmine.is()`, `jasmine.stringContaining()`, `jasmine.stringMatching()`, `jasmine.truthy()`, `jasmine.falsy()`, `jasmine.empty()` and `jasmine.notEmpty()` work in the element matchers, also in an array of expected values on `$$()`. * On `$$()`, `jasmine.arrayContaining()` and `jasmine.arrayWithExactContents()` compare the values of all the elements at once, see [Matching a subset of element values](https://github.com/webdriverio/expect-webdriverio/blob/main/API.md#matching-a-subset-of-element-values). * Network matchers support `jasmine.objectContaining()`. * WDIO asymmetric matchers also work properly. ``` import { expect as wdioExpect } from 'expect-webdriverio' describe('My tests', async () => { it('should verify my browser to have the expected url', async () => { // Working Jasmine asymmetric matchers await expectAsync(browser).toHaveUrl(jasmine.stringContaining('WebdriverIO')) await expectAsync(browser).toHaveUrl(jasmine.stringMatching('/WebdriverIO/')) await expectAsync(browser).toHaveUrl(jasmine.any(String)) await expectAsync(browser).toHaveUrl(jasmine.anything()) // Working WDIO asymmetric matcher await expectAsync(browser).toHaveUrl(wdioExpect.stringContaining('WebdriverIO')) }) }) ``` ##### Matching a list of elements[​](#matching-a-list-of-elements-1 "Direct link to Matching a list of elements") On `$$()`, Jasmine's list matchers compare the values of all the elements at once. Results with `toHaveText` on `$$('li')`: | Expected value | Passes when | Order | Other elements | String options (`trim`, `ignoreCase`…) | | --------------------------------------------------- | ---------------------------------------------------- | ----- | -------------- | -------------------------------------- | | `['Coffee', 'Tea']` | each element has the text at its index | fixed | no: same count | applied | | `jasmine.arrayContaining(['Tea', 'Coffee'])` | each text is on at least one element | any | allowed | not applied | | `jasmine.arrayWithExactContents(['Tea', 'Coffee'])` | same count, and each text is on at least one element | any | no | not applied | `jasmine.arrayWithExactContents()` does not count a text that it has 2 times: `['Tea', 'Tea']` passes on `Coffee`, `Tea`, because the count is the same and `Tea` is in the list. This is how Jasmine compares. For an exact list with repeated texts, use an array in the order of the elements. The other list matchers of [Jest](#matching-a-list-of-elements), e.g. `expect.arrayOf()`, are on the `expect` of `expect-webdriverio`. ``` // <li>Coffee</li> <li>Tea</li> await expect($$('li')).toHaveText(['Coffee', 'Tea']) // passes await expect($$('li')).toHaveText(['Tea', 'Coffee']) // fails: the order is different await expect($$('li')).toHaveText(jasmine.arrayWithExactContents(['Tea', 'Coffee'])) // passes: any order await expect($$('li')).toHaveText(jasmine.arrayContaining(['Tea'])) // passes: Coffee is allowed await expect($$('li')).toHaveText(jasmine.arrayWithExactContents(['Tea'])) // fails: Coffee is not expected await expect($$('li')).toHaveText(jasmine.arrayWithExactContents(['Tea', 'Tea'])) // passes: see above // <li> Coffee </li> <li> Tea </li> await expect($$('li')).toHaveText(jasmine.arrayWithExactContents(['Tea', 'Coffee'])) // fails: the values are " Coffee " and " Tea " ``` #### Cucumber[​](#cucumber "Direct link to Cucumber") More details to come. In short, when paired with [`@wdio/cucumber-framework`](https://www.npmjs.com/package/@wdio/cucumber-framework), you can use WebDriverIO's `expect` library seamlessly within your Cucumber step definitions and [Gherkin-based](https://www.npmjs.com/package/@cucumber/gherkin) tests. #### Browser Runner[​](#browser-runner "Direct link to Browser Runner") Browser Runner ([@wdio/browser-runner](https://www.npmjs.com/package/@wdio/browser-runner)) allows you to leverage component frameworks like React, Preact, Vue.js, Svelte, and SolidJS. It relies on the Jest's standard `expect` library and only registers core `expect-webdriverio` matchers. Because it runs within a browser environment rather than fully embedding `expect-webdriverio`, global features like `DefaultOption` and `SoftAssertion` are currently unsupported. ##### OneOf & Some[​](#oneof--some "Direct link to OneOf & Some") The asymmetric matcher `expect.oneOf` and the modifier `some` have been adapted to work in Browser Runner: * `expect.oneOf`: Works standard out of the box. * `expect.some`: Reimplemented to integrate with Jest's native expect runner and exposed directly via `expect.some`. **Note:** Importing `some` from `expect-webdriverio/api` will not work in Browser Runner mode. Always access it through `expect.some` ``` it('some elements are displayed', async () => { // `expect.some` uses global export. Ignore TypeScript errors on `expect.some` until proper typings are provided. await expect(expect.some($$('p=Times clicked: 1'))).toBeDisplayed() }) ``` ##### Multiple Elements & Multi-remote[​](#multiple-elements--multi-remote "Direct link to Multiple Elements & Multi-remote") * `$$()` is supported, awaited or not, and filtered (`Element[]`), including by the snapshot matchers. * [Multi-remote](https://github.com/webdriverio/expect-webdriverio/blob/main/MultiRemote.md) is not supported: the Browser Runner runs tests in a single browser session, and stops with `No "browserName" defined in capability object` when given multi-remote capabilities. Use a Node.js runner framework instead, such as Mocha, Jasmine or Cucumber. #### Matcher names for adapters and tools[​](#matcher-names-for-adapters-and-tools "Direct link to Matcher names for adapters and tools") A framework adapter, a lint rule or a runner that must know the matchers before `expect` exists can import their names from `expect-webdriverio/api`, instead of a copy of the list: ``` import { wdioCustomMatcherNames, asymmetricMatcherNames, inverseAsymmetricMatcherNames } from 'expect-webdriverio/api' wdioCustomMatcherNames // ['toBeChecked', ..., 'toMatchSnapshot']: the names of `wdioCustomMatchers`, not the matchers of the `expect` package asymmetricMatcherNames // ['any', ..., 'oneOf', 'multiRemote']: the asymmetric matchers of the `expect` package and of expect-webdriverio inverseAsymmetricMatcherNames // ['arrayContaining', ..., 'stringMatching']: the same, on `expect.not` ``` Each matcher returns a promise, except `toMatchSnapshot` and `toMatchInlineSnapshot` when the received value is not an element, a list of elements or a promise. The lists do not have the matchers that you add with `expect.extend()`, or the `some` modifier. `expect.extend()` also adds each matcher to `expect` and `expect.not` as an asymmetric matcher, and the asymmetric lists do not have these. The asymmetric form of the matchers of `wdioCustomMatcherNames` does not work, so do not add them to the asymmetric lists: the matchers are async (`expect.toHaveTitle('x').asymmetricMatch(browser)` gives `undefined`), except `toMatchSnapshot` and `toMatchInlineSnapshot`, which compare or write a snapshot of the current test, not an equality. A sync matcher that you add with `expect.extend()` works as an asymmetric matcher. ## Custom Matchers[​](#custom-matchers-1 "Direct link to Custom Matchers") `expect-webdriverio` registers WebdriverIO custom matchers out of the box for a seamless experience. To use WebdriverIO custom matchers (except asymmetric matchers) directly in: * **Jest**: Register matchers manually with `expect.extend`. * **Jasmine**: Using `@wdio/jasmine-framework` provides an out-of-the-box experience. <!-- --> * Else, register matchers manually with `jasmine.addAsyncMatchers`, then they will be available on `expectAsync`. * **Types**: Type augmentation for custom matchers is provided. See [Types.md](https://github.com/webdriverio/expect-webdriverio/blob/main/Types.md) for details. ### Adding your own matchers[​](#adding-your-own-matchers "Direct link to Adding your own matchers") Similar to how `expect-webdriverio` provide custom matchers it's possible to add your own custom matchers. * [Jasmine](https://jasmine.github.io/) see [custom matchers](https://jasmine.github.io/tutorials/custom_matchers) doc * Everyone else see [Jest's expect.extend](https://jestjs.io/docs/expect#expectextendmatchers) Custom matchers should be added in wdio `before` hook ``` // wdio.conf.js { async before () { const { addCustomMatchers } = await import('./myMatchers') addCustomMatchers() } } ``` ``` // myMatchers.js - Jest example export function addCustomMatchers () { expect.extend({ myMatcher (actual, expected) { return { pass: actual === expected, message: () => 'some message' } } }) } ``` ### TypeScript[​](#typescript-1 "Direct link to TypeScript") Add the types of your matchers to the `ExpectWebdriverIO` namespace. It works with every framework: the types of `expect-webdriverio/jest` and of `expect-webdriverio/jasmine` (and `@wdio/jasmine-framework`) extend it, also for `expect.soft()`. ``` // my-matchers.d.ts, or any .ts file of your project declare global { namespace ExpectWebdriverIO { interface Matchers<R, T> { // A matcher for any value toBeWithinRange(floor: number, ceiling: number): R // An async matcher for elements only: `never` blocks it on other values toHaveDataState: T extends ChainablePromiseElement | WebdriverIO.Element ? (state: string | ExpectWebdriverIO.PartialMatcher<string>, options?: ExpectWebdriverIO.CommandOptions) => Promise<R> : never } interface AsymmetricMatchers { // The asymmetric form: `expect.toBeWithinRange(1, 10)` toBeWithinRange(floor: number, ceiling: number): ExpectWebdriverIO.PartialMatcher<number> } } } export {} ``` * `Matchers` takes both type parameters, `<R, T>`, as in `expect-webdriverio`: `R` is the return type of the assertion, and `T` is the type of the value given to `expect()`. With `Matchers<R>` only, TypeScript fails: `All declarations of 'Matchers' must have identical type parameters`. * An async matcher, which waits for the element, returns `Promise<R>`. A matcher that compares a value at once returns `R`. * `ExpectWebdriverIO.PartialMatcher` takes the type of the value, e.g. `PartialMatcher<string>`. * In a file with an `import` or an `export` (a module), put the namespace in `declare global { … }`, and end with `export {}` when the file has no other export. In a `.d.ts` file with no `import` and no `export`, write `declare namespace ExpectWebdriverIO { … }` directly. * Use the public types: `ExpectWebdriverIO.*` (also as named exports of `expect-webdriverio`), `WebdriverIO.Element`, and the 2 global names `ChainablePromiseElement` and `ChainablePromiseArray` (the types of a not-awaited `$()` and `$$()`, from `webdriverio`). The other helper types of `expect-webdriverio` are not global. * With Jest, you can also add the types to the `expect` module (`declare module 'expect' { interface Matchers<R, T> { … } }`), or to the `jest` namespace. The `jest` namespace does not type `expect.soft()`. ## Examples[​](#examples "Direct link to Examples") ``` describe('suite', () => { before(async () => { await browser.url('https://github.com/webdriverio/expect-webdriverio') await expect(browser).toHaveUrl('https://github.com/webdriverio/expect-webdriverio') await expect(browser).toHaveTitle('expect-webdriverio', { containing: true }) }) it('find elements', async () => { const formInputs = await $$('form input') // make sure every form element is enabled // waits automatically for formInputs to have at least one element await expect(formInputs).toBeEnabled({ wait: 5000 }) const selectOptions = await $$('form select>option') // make sure there is at least one option in select await expect(selectOptions).toBeElementsArrayOfSize({ gte: 1 }) // or pass in an element directly await expect($$('button')).toBeElementsArrayOfSize(3) }) it('checks text values', async () => { // assert certain text accurate const repoTitle = await $('expect-webdriverio') await expect(repoTitle).toHaveText('expect-webdriverio') }) it('advanced', async () => { const myInput = await $('#username') await expect(myInput).toHaveElementClass('form-control', { message: 'Not a form control!', }) await expect(myInput).toHaveAttribute('class', 'form-control') await expect(myInput).toHaveValue('user', { containing: true, ignoreCase: true }) // Simply invert assertions await expect(myInput).not.toHaveElementProperty('height', 0) }) }) ``` ## Boilerplate Projects[​](#boilerplate-projects "Direct link to Boilerplate Projects") WebdriverIO test runner * Mocha <https://github.com/mgrybyk/webdriverio-devtools> * Cucumber <https://gitlab.com/bar_foo/wdio-cucumber-typescript> * Jasmine <https://github.com/webdriverio/jasmine-boilerplate> Standalone * Jest <https://github.com/erwinheitzman/jest-webdriverio-standalone-boilerplate> more boilerplate projects coming soon, feel free to propose yours! ## Playgrounds[​](#playgrounds-1 "Direct link to Playgrounds") Additional examples are available as internal playgrounds to the project. See [playgrounds folder](https://github.com/webdriverio/expect-webdriverio/blob/main/../playgrounds), including [multi-remote examples](https://github.com/webdriverio/expect-webdriverio/blob/main/../playgrounds/mocha/test/multi-remote-specs). --- Source: https://webdriver.io/docs/api/globals.md # Globals In your test files, WebdriverIO puts each of these methods and objects into the global environment. You don't have to import anything to use them. However, if you prefer explicit imports, you can do `import { browser, $, $$, expect } from '@wdio/globals'` and set `injectGlobals: false` in your WDIO configuration. The following global objects are set if not configured otherwise: * `browser`: WebdriverIO [Browser object](https://webdriver.io/docs/api/browser) * `driver`: alias to `browser` (used when running mobile tests) * `multiRemoteBrowser`: alias to `browser` or `driver` but only set for [multi-remote](/docs/multiremote.md) sessions * `$`: command to fetch an element (see more in [API docs](/docs/api/browser/$.md)) * `$$`: command to fetch elements (see more in [API docs](/docs/api/browser/$$.md)) * `expect`: assertion framework for WebdriverIO (see [API docs](/docs/api/expect-webdriverio.md)) **Note:** WebdriverIO has no control of used frameworks (e.g. Mocha or Jasmine) setting global variables when bootstrapping their environment. --- Source: https://webdriver.io/docs/api/environment.md # Environment Variables WebdriverIO sets the following environment variables within every worker: ## `NODE_ENV`[​](#node_env "Direct link to node_env") Set to `'test'` if it's not already set to something else. ## `WDIO_LOG_LEVEL`[​](#wdio_log_level "Direct link to wdio_log_level") Can be set to values `trace`, `debug`, `info`, `warn`, `error`, `silent` to write logs with corresponding details. Has priority over the passed `logLevel` value. ## `WDIO_WORKER_ID`[​](#wdio_worker_id "Direct link to wdio_worker_id") An unique id that helps identify the worker process. It has format of `{number}-{number}` where the first number identifies the capability and the second the spec file that capability is running, e.g. `0-5` indicates a worker the first running the 6th spec file for the first capability. --- Source: https://webdriver.io/docs/api/modules.md # Modules WebdriverIO publishes various modules to NPM and other registries that you can use to build your own automation framework. See more documentation on WebdriverIO setup types [here](/docs/setuptypes.md). ## `webdriver` and `devtools`[​](#webdriver-and-devtools "Direct link to webdriver-and-devtools") The protocol packages ([`webdriver`](https://www.npmjs.com/package/webdriver) and [`devtools`](https://www.npmjs.com/package/devtools)) expose a class with the following static functions attached that allow you to initiate sessions: #### `newSession(options, modifier, userPrototype, customCommandWrapper)`[​](#newsessionoptions-modifier-userprototype-customcommandwrapper "Direct link to newsessionoptions-modifier-userprototype-customcommandwrapper") Starts a new session with specific capabilities. Based on the session response commands from different protocols will be provided. ##### Paramaters[​](#paramaters "Direct link to Paramaters") * `options`: [WebDriver Options](/docs/configuration.md#webdriver-options) * `modifier`: function that allows to modify the client instance before it is being returned * `userPrototype`: properties object that allows to extend the instance prototype * `customCommandWrapper`: function that allows to wrap functionality around function calls ##### Returns[​](#returns "Direct link to Returns") * [Browser](/docs/api/browser.md) object ##### Example[​](#example "Direct link to Example") ``` const client = await WebDriver.newSession({ capabilities: { browserName: 'chrome' } }) ``` #### `attachToSession(attachInstance, modifier, userPrototype, customCommandWrapper)`[​](#attachtosessionattachinstance-modifier-userprototype-customcommandwrapper "Direct link to attachtosessionattachinstance-modifier-userprototype-customcommandwrapper") Attaches to a running WebDriver or DevTools session. ##### Paramaters[​](#paramaters-1 "Direct link to Paramaters") * `attachInstance`: instance to attach a session to or at least an object with a property `sessionId` (e.g. `{ sessionId: 'xxx' }`) * `modifier`: function that allows to modify the client instance before it is being returned * `userPrototype`: properties object that allows to extend the instance prototype * `customCommandWrapper`: function that allows to wrap functionality around function calls ##### Returns[​](#returns-1 "Direct link to Returns") * [Browser](/docs/api/browser.md) object ##### Example[​](#example-1 "Direct link to Example") ``` const client = await WebDriver.newSession({...}) const clonedClient = await WebDriver.attachToSession(client) ``` #### `reloadSession(instance)`[​](#reloadsessioninstance "Direct link to reloadsessioninstance") Reloads a session given provided instance. ##### Paramaters[​](#paramaters-2 "Direct link to Paramaters") * `instance`: package instance to reload ##### Example[​](#example-2 "Direct link to Example") ``` const client = await WebDriver.newSession({...}) await WebDriver.reloadSession(client) ``` ## `webdriverio`[​](#webdriverio "Direct link to webdriverio") Similar as to the protocol packages (`webdriver` and `devtools`) you can also use the WebdriverIO package APIs to manage sessions. The APIs can be imported using `import { remote, attach, multiRemote } from 'webdriverio` and contain the following functionality: #### `remote(options, modifier)`[​](#remoteoptions-modifier "Direct link to remoteoptions-modifier") Starts a WebdriverIO session. The instance contains all commands as the protocol package but with additional higher order functions, see [API docs](/docs/api.md). ##### Paramaters[​](#paramaters-3 "Direct link to Paramaters") * `options`: [WebdriverIO Options](/docs/configuration.md#webdriverio) * `modifier`: function that allows to modify the client instance before it is being returned ##### Returns[​](#returns-2 "Direct link to Returns") * [Browser](/docs/api/browser.md) object ##### Example[​](#example-3 "Direct link to Example") ``` import { remote } from 'webdriverio' const browser = await remote({ capabilities: { browserName: 'chrome' } }) ``` #### `attach(attachOptions)`[​](#attachattachoptions "Direct link to attachattachoptions") Attaches to a running WebdriverIO session. ##### Paramaters[​](#paramaters-4 "Direct link to Paramaters") * `attachOptions`: instance to attach a session to or at least an object with a property `sessionId` (e.g. `{ sessionId: 'xxx' }`) ##### Returns[​](#returns-3 "Direct link to Returns") * [Browser](/docs/api/browser.md) object ##### Example[​](#example-4 "Direct link to Example") ``` import { remote, attach } from 'webdriverio' const browser = await remote({...}) const newBrowser = await attach(browser) ``` #### `multiRemote(multiRemoteOptions)`[​](#multiremotemultiremoteoptions "Direct link to multiremotemultiremoteoptions") Initiates a multi-remote instance which allows you to control multiple session within a single instance. Checkout our [multi-remote examples](https://github.com/webdriverio/webdriverio/tree/main/examples/multiremote) for concrete use cases. ##### Paramaters[​](#paramaters-5 "Direct link to Paramaters") * `multiRemoteOptions`: an object with keys representing the browser name and their [WebdriverIO Options](/docs/configuration.md#webdriverio). ##### Returns[​](#returns-4 "Direct link to Returns") * [Browser](/docs/api/browser.md) object ##### Example[​](#example-5 "Direct link to Example") ``` import { multiRemote } from 'webdriverio' const matrix = await multiRemote({ myChromeBrowser: { capabilities: { browserName: 'chrome' } }, myFirefoxBrowser: { capabilities: { browserName: 'firefox' } } }) await matrix.url('http://json.org') await matrix.getInstance('browserA').url('https://google.com') console.log(await matrix.getTitle()) // returns ['Google', 'JSON'] ``` #### `Key`[​](#key "Direct link to key") An object containing special character constants for use with the [`browser.keys`](/docs/api/browser/keys.md) command. These constants represent special keys that can be sent to the browser, such as `Enter`, `Tab`, `Escape`, arrow keys, function keys, and more. ##### Example[​](#example-6 "Direct link to Example") ``` import { Key } from 'webdriverio' // Press Enter key await browser.keys(Key.Enter) // Use Ctrl+A to select all (works cross-platform) await browser.keys([Key.Ctrl, 'a']) // Navigate with arrow keys await browser.keys([Key.ArrowDown, Key.ArrowDown, Key.Enter]) ``` ##### Available Keys[​](#available-keys "Direct link to Available Keys") The following special keys are available via the `Key` object: **Modifier Keys:** | Constant | Description | | ------------- | --------------------------------------------------------------------- | | `Key.Ctrl` | Cross-platform control key (Command on Mac, Control on Windows/Linux) | | `Key.Control` | Control key | | `Key.Shift` | Shift key | | `Key.Alt` | Alt key | | `Key.Command` | Command key (Mac) | | `Key.NULL` | Null/release key — releases all currently held modifier keys | **Navigation Keys:** | Constant | Description | | ---------------- | --------------- | | `Key.Cancel` | Cancel key | | `Key.Help` | Help key | | `Key.Backspace` | Backspace key | | `Key.Tab` | Tab key | | `Key.Clear` | Clear key | | `Key.Return` | Return key | | `Key.Enter` | Enter key | | `Key.Pause` | Pause key | | `Key.Escape` | Escape key | | `Key.Space` | Space key | | `Key.PageUp` | Page Up key | | `Key.PageDown` | Page Down key | | `Key.End` | End key | | `Key.Home` | Home key | | `Key.ArrowLeft` | Left Arrow key | | `Key.ArrowUp` | Up Arrow key | | `Key.ArrowRight` | Right Arrow key | | `Key.ArrowDown` | Down Arrow key | | `Key.Insert` | Insert key | | `Key.Delete` | Delete key | **Character Keys:** | Constant | Description | | --------------- | ------------- | | `Key.Semicolon` | Semicolon key | | `Key.Equals` | Equals key | **Numpad Keys:** | Constant | Description | | ----------------------------- | ---------------- | | `Key.Numpad0` - `Key.Numpad9` | Numpad 0-9 | | `Key.Multiply` | Numpad Multiply | | `Key.Add` | Numpad Add | | `Key.Separator` | Numpad Separator | | `Key.Subtract` | Numpad Subtract | | `Key.Decimal` | Numpad Decimal | | `Key.Divide` | Numpad Divide | **Function Keys:** | Constant | Description | | -------------------- | ---------------------------- | | `Key.F1` - `Key.F12` | Function keys F1 through F12 | **Other Keys:** | Constant | Description | | -------------------- | ------------------------------ | | `Key.ZenkakuHankaku` | Zenkaku/Hankaku key (Japanese) | Cross-Platform Modifier Keys The `Key.Ctrl` constant provides a convenient way to use the "control" modifier across different operating systems. On macOS, it maps to the `Command` key, while on Windows and Linux it maps to the `Control` key. This is useful when writing tests that need to work across multiple platforms, e.g., for select-all (`Ctrl+A`), copy (`Ctrl+C`), or paste (`Ctrl+V`) operations. ## `@wdio/cli`[​](#wdiocli "Direct link to wdiocli") Instead of calling the `wdio` command, you can also include the test runner as module and run it in an arbitrary environment. For that, you'll need to require the `@wdio/cli` package as module, like this: * EcmaScript Modules * CommonJS ``` import Launcher from '@wdio/cli' ``` ``` const Launcher = require('@wdio/cli').default ``` After that, create an instance of the launcher, and run the test. #### `Launcher(configPath, opts)`[​](#launcherconfigpath-opts "Direct link to launcherconfigpath-opts") The `Launcher` class constructor expects the URL to the config file, and an `opts` object with settings that will overwrite those in the config. ##### Paramaters[​](#paramaters-6 "Direct link to Paramaters") * `configPath`: path to the `wdio.conf.js` to run * `opts`: arguments ([`<RunCommandArguments>`](https://github.com/webdriverio/webdriverio/blob/main/packages/wdio-cli/src/types.ts#L51-L77)) to overwrite values from the config file ##### Example[​](#example-7 "Direct link to Example") ``` const wdio = new Launcher( '/path/to/my/wdio.conf.js', { spec: '/path/to/a/single/spec.e2e.js' } ) wdio.run().then((exitCode) => { process.exit(exitCode) }, (error) => { console.error('Launcher failed to start the test', error.stacktrace) process.exit(1) }) ``` The `run` command returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). It is resolved if tests ran successfully or failed, and it is rejected if the launcher was unable to start run the tests. ## `@wdio/browser-runner`[​](#wdiobrowser-runner "Direct link to wdiobrowser-runner") When running unit or component tests using WebdriverIO's [browser runner](/docs/runner.md#browser-runner) you can import mocking utilities for your tests, e.g.: ``` import { fn, spyOn, mock, unmock } from '@wdio/browser-runner' ``` The following named exports are available: #### `fn`[​](#fn "Direct link to fn") Mock function, see more in the official [Vitest docs](https://vitest.dev/api/mock.html#mock-functions). #### `spyOn`[​](#spyon "Direct link to spyon") Spy function, see more in the official [Vitest docs](https://vitest.dev/api/mock.html#mock-functions). #### `mock`[​](#mock "Direct link to mock") Method to mock file or dependency module. ##### Paramaters[​](#paramaters-7 "Direct link to Paramaters") * `moduleName`: either a relative path to the file to be mocked or a module name. * `factory`: function to return the mocked value (optional) ##### Example[​](#example-8 "Direct link to Example") ``` mock('../src/constants.ts', () => ({ SOME_DEFAULT: 'mocked out' })) mock('lodash', (origModuleFactory) => { const origModule = await origModuleFactory() return { ...origModule, pick: fn() } }) ``` #### `unmock`[​](#unmock "Direct link to unmock") Unmock dependency that is defined within the manual mock (`__mocks__`) directory. ##### Paramaters[​](#paramaters-8 "Direct link to Paramaters") * `moduleName`: name of the module to be unmocked. ##### Example[​](#example-9 "Direct link to Example") ``` unmock('lodash') ``` --- Source: https://webdriver.io/docs/api/protocols.md # Protocol Commands WebdriverIO is an automation framework that relies on various automation protocols to control a remote agent, e.g. for a browser, mobile device or television. Based on the remote device different protocols come into play. These commands are assigned to the [Browser](/docs/api/browser.md) or [Element](/docs/api/element.md) Object depending on the session information by the remote server (e.g. browser driver). Internally WebdriverIO uses protocol commands for almost all interactions with the remote agent. However additional commands assigned to the [Browser](/docs/api/browser.md) or [Element](/docs/api/element.md) Object simplify the usage of WebdriverIO, e.g. getting the text of an element using protocol commands would look like this: ``` const searchInput = await browser.findElement('css selector', '#lst-ib') await client.getElementText(searchInput['element-6066-11e4-a52e-4f735466cecf']) ``` Using the convenient commands of the [Browser](/docs/api/browser.md) or [Element](/docs/api/element.md) Object this can be reduced to: ``` $('#lst-ib').getText() ``` The following section explain each individual protocol. ## WebDriver Protocol[​](#webdriver-protocol "Direct link to WebDriver Protocol") The [WebDriver](https://w3c.github.io/webdriver/#elements) protocol is a web standard for automating browser. As oppose to some other E2E tools it guarantees that automation can be done on actual browser that are used by your users, e.g. Firefox, Safari and Chrome and Chromium based browser like Edge, and not only on browser engines, e.g. WebKit, which are very different. The advantage of using the WebDriver protocol as oppose to debugging protocols like [Chrome DevTools](https://w3c.github.io/webdriver/#elements) is that you have a specific set of commands that allow to interact with the browser the same way across all browser which reduces the likelihood for flakiness. Furthermore offers this protocol abilities for massive scalability by using cloud vendors such as [Sauce Labs](https://saucelabs.com/), [BrowserStack](https://www.browserstack.com/) and [others](https://github.com/christian-bromann/awesome-selenium#cloud-services). ## WebDriver Bidi Protocol[​](#webdriver-bidi-protocol "Direct link to WebDriver Bidi Protocol") The [WebDriver Bidi](https://w3c.github.io/webdriver-bidi/) protocol is the second generation of the protocol and is currently being worked on by most browser vendors. Compared to its pre-predecessor the protocol supports a bi-directional communication (hence "Bidi") between the framework and the remote device. It furthermore introduces additional primitives for better browser introspection to better automate modern web applications in browser. Given this protocol is currently work in progress more features will be added over time and supported by browser. If you use WebdriverIOs convenient commands nothing will change for you. WebdriverIO will make use of these new protocol capabilities as soon as they are available and supported in the browser. ## Appium[​](#appium "Direct link to Appium") The [Appium](https://appium.io/) project provides capabilities to automate mobile, desktop and all other kinds of IoT devices. While WebDriver focuses on browser and the web, the vision of Appium is to use the same approach but for any arbitrary device. In addition to the commands that WebDriver defines, it has special commands that often are specific to the remote device that is being automated. For mobile testing scenarios this is ideal when you want to write and run the same tests for both Android and iOS applications. According to Appium [documentation](https://appium.github.io/appium.io/docs/en/about-appium/intro/?lang=en) it was designed to meet mobile automation needs according to a philosophy outlined by the following four tenets: * You shouldn't have to recompile your app or modify it in any way in order to automate it. * You shouldn't be locked into a specific language or framework to write and run your tests. * A mobile automation framework shouldn't reinvent the wheel when it comes to automation APIs. * A mobile automation framework should be open source, in spirit and practice as well as in name! ## Chromium[​](#chromium "Direct link to Chromium") The Chromium protocol offers a super set of commands on top of the WebDriver protocol that is only supported when running automated session through [Chromedriver](https://chromedriver.chromium.org/chromedriver-canary) or [Edgedriver](https://developer.microsoft.com/fr-fr/microsoft-edge/tools/webdriver). ## Firefox[​](#firefox "Direct link to Firefox") The Firefox protocol offers a super set of commands on top of the WebDriver protocol that is only supported when running automated session through [Geckodriver](https://github.com/mozilla/geckodriver). ## Sauce Labs[​](#sauce-labs "Direct link to Sauce Labs") The [Sauce Labs](https://saucelabs.com/) protocol offers a super set of commands on top of the WebDriver protocol that is only supported when running automated session using the Sauce Labs cloud. ## Selenium Standalone[​](#selenium-standalone "Direct link to Selenium Standalone") The [Selenium Standalone](https://www.selenium.dev/documentation/grid/advanced_features/endpoints/) protocol offers a super set of commands on top of the WebDriver protocol that is only supported when running automated session using the Selenium Grid. --- Source: https://webdriver.io/docs/api/appium.md # Appium ## getLogTypes[​](#getlogtypes "Direct link to getLogTypes") Get available log types.<br /><br />Appium command. More details can be found in the [official protocol docs](https://www.selenium.dev/documentation/webdriver/troubleshooting/logging/). ### Usage[​](#usage "Direct link to Usage") ``` await driver.getLogTypes() ``` ### Returns[​](#returns "Direct link to Returns") * **\<String\[]>** **`logTypes`:** The list of available log types, example: browser, driver. *** ## getLogs[​](#getlogs "Direct link to getLogs") Get the log for a given log type. Log buffer is reset after each request.<br /><br />Appium command. More details can be found in the [official protocol docs](https://www.selenium.dev/documentation/webdriver/troubleshooting/logging/). ### Usage[​](#usage-1 "Direct link to Usage") ``` await driver.getLogs(type) ``` ### Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------ | -------- | ------------ | | `type` | `string` | the log type | ### Returns[​](#returns-1 "Direct link to Returns") * **\<Object\[]>** **`logs`:** The list of log entries. *** ## getSession[​](#getsession "Direct link to getSession") Retrieve the capabilities of the current session.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/jsonwp/#getsession). caution This protocol command is deprecated<br />Use `getAppiumSessionCapabilities` instead ### Usage[​](#usage-2 "Direct link to Usage") ``` await driver.getSession() ``` ### Returns[​](#returns-2 "Direct link to Returns") * **\<Object>** **`capabilities`:** An object describing the session's capabilities. *** ## getAppiumContext[​](#getappiumcontext "Direct link to getAppiumContext") Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/guides/context/). ### Usage[​](#usage-3 "Direct link to Usage") ``` await driver.getAppiumContext() ``` ### Returns[​](#returns-3 "Direct link to Returns") * **\<Context>** **`context`:** a string representing the current context or null representing 'no context' *** ## switchAppiumContext[​](#switchappiumcontext "Direct link to switchAppiumContext") Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/guides/context/). ### Usage[​](#usage-4 "Direct link to Usage") ``` await driver.switchAppiumContext(name) ``` ### Parameters[​](#parameters-1 "Direct link to Parameters") | Name | Type | Details | | ------ | -------- | ------------------------------------------ | | `name` | `string` | a string representing an available context | *** ## getAppiumContexts[​](#getappiumcontexts "Direct link to getAppiumContexts") Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/guides/context/). ### Usage[​](#usage-5 "Direct link to Usage") ``` await driver.getAppiumContexts() ``` ### Returns[​](#returns-4 "Direct link to Returns") * **\<Context\[]>** **`contexts`:** an array of strings representing available contexts, e.g. 'WEBVIEW', or 'NATIVE' *** ## getAppiumCommands[​](#getappiumcommands "Direct link to getAppiumCommands") Retrieve the endpoints and BiDi commands supported in the current session.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/appium/#listcommands). ### Usage[​](#usage-6 "Direct link to Usage") ``` await driver.getAppiumCommands() ``` ### Returns[​](#returns-5 "Direct link to Returns") * **\<Object>** **`commands`:** Supported endpoints and BiDi commands, each grouped into common, driver-specific, and plugin-specific endpoints/commands. *** ## getAppiumExtensions[​](#getappiumextensions "Direct link to getAppiumExtensions") Retrieve the extension commands supported in the current session.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/appium/#listextensions). ### Usage[​](#usage-7 "Direct link to Usage") ``` await driver.getAppiumExtensions() ``` ### Returns[​](#returns-6 "Direct link to Returns") * **\<Object>** **`commands`:** Supported extension commands, grouped into driver-specific and plugin-specific commands. *** ## getAppiumSessionCapabilities[​](#getappiumsessioncapabilities "Direct link to getAppiumSessionCapabilities") Retrieve the capabilities of the current session.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/appium/#getappiumsessioncapabilities). ### Usage[​](#usage-8 "Direct link to Usage") ``` await driver.getAppiumSessionCapabilities() ``` ### Returns[​](#returns-7 "Direct link to Returns") * **\<Object>** **`capabilities`:** An object describing the session's capabilities. *** ## startRecordingScreen[​](#startrecordingscreen "Direct link to startRecordingScreen") Start recording the screen.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.github.io/appium.io/docs/en/commands/device/recording-screen/start-recording-screen/). ### Usage[​](#usage-9 "Direct link to Usage") ``` await driver.startRecordingScreen(options) ``` ### Parameters[​](#parameters-2 "Direct link to Parameters") | Name | Type | Details | | ------------------------- | -------- | --------------------------------------------------------------- | | `options`<br />*optional* | `object` | Appium driver-specific recording options (refer to driver docs) | ### Returns[​](#returns-8 "Direct link to Returns") * **\<string>** **`response`:** Empty string, or the base64 encoded string of a previous screen recording, if forceRestart and remotePath are not set ### Support[​](#support "Direct link to Support") ![Support for XCUITest (9.3+)](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) ![Support for Windows (10+)](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA4OCA4OCI+PHBhdGggZD0ibTAgMTIuNDAyIDM1LjY4Ny00Ljg2MDIuMDE1NiAzNC40MjMtMzUuNjcuMjAzMTN6bTM1LjY3IDMzLjUyOS4wMjc3IDM0LjQ1My0zNS42Ny00LjkwNDEtLjAwMi0yOS43OHptNC4zMjYxLTM5LjAyNSA0Ny4zMTgtNi45MDZ2NDEuNTI3bC00Ny4zMTguMzc1NjV6bTQ3LjMyOSAzOS4zNDktLjAxMTEgNDEuMzQtNDcuMzE4LTYuNjc4NC0uMDY2My0zNC43Mzl6IiBmaWxsPSIjMDBhZGVmIi8+PC9zdmc+) * **iOS:** XCUITest (9.3+) * **Android:** UiAutomator (4.2+) * **Windows:** Windows (10+) *** ## stopRecordingScreen[​](#stoprecordingscreen "Direct link to stopRecordingScreen") Stop recording the screen.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.github.io/appium.io/docs/en/commands/device/recording-screen/stop-recording-screen/). ### Usage[​](#usage-10 "Direct link to Usage") ``` await driver.stopRecordingScreen(options) ``` ### Parameters[​](#parameters-3 "Direct link to Parameters") | Name | Type | Details | | ------------------------- | -------- | --------------------------------------------------------------- | | `options`<br />*optional* | `object` | Appium driver-specific recording options (refer to driver docs) | ### Returns[​](#returns-9 "Direct link to Returns") * **\<string>** **`response`:** Base64 encoded string of the screen recording, or an empty string if the remotePath option is set ### Support[​](#support-1 "Direct link to Support") ![Support for XCUITest (9.3+)](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) ![Support for Windows (10+)](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA4OCA4OCI+PHBhdGggZD0ibTAgMTIuNDAyIDM1LjY4Ny00Ljg2MDIuMDE1NiAzNC40MjMtMzUuNjcuMjAzMTN6bTM1LjY3IDMzLjUyOS4wMjc3IDM0LjQ1My0zNS42Ny00LjkwNDEtLjAwMi0yOS43OHptNC4zMjYxLTM5LjAyNSA0Ny4zMTgtNi45MDZ2NDEuNTI3bC00Ny4zMTguMzc1NjV6bTQ3LjMyOSAzOS4zNDktLjAxMTEgNDEuMzQtNDcuMzE4LTYuNjc4NC0uMDY2My0zNC43Mzl6IiBmaWxsPSIjMDBhZGVmIi8+PC9zdmc+) * **iOS:** XCUITest (9.3+) * **Android:** UiAutomator (4.2+) * **Windows:** Windows (10+) *** ## rotateDevice[​](#rotatedevice "Direct link to rotateDevice") Rotate the device in three dimensions.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/mjsonwp/#setrotation). ### Usage[​](#usage-11 "Direct link to Usage") ``` await driver.rotateDevice(x, y, z) ``` ### Parameters[​](#parameters-4 "Direct link to Parameters") | Name | Type | Details | | ---- | -------- | ---------------------------------------------------- | | `x` | `number` | x offset to use for the center of the rotate gesture | | `y` | `number` | y offset to use for the center of the rotate gesture | | `z` | `number` | z offset to use for the center of the rotate gesture | ### Support[​](#support-2 "Direct link to Support") ![Support for UIAutomation (8.0 to 9.3)](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) * **iOS:** UIAutomation (8.0 to 9.3) * **Android:** UiAutomator (4.2+) *** ## installApp[​](#installapp "Direct link to installApp") Install the given app onto the device.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/appium/#installapp). ### Usage[​](#usage-12 "Direct link to Usage") ``` await driver.installApp(appPath, options) ``` ### Parameters[​](#parameters-5 "Direct link to Parameters") | Name | Type | Details | | ------------------------- | -------- | ------------------------------------ | | `appPath` | `string` | Path to application .apk file | | `options`<br />*optional* | `object` | Driver-specific installation options | ### Support[​](#support-3 "Direct link to Support") ![Support for XCUITest (9.3+), UIAutomation (8.0 to 9.3)](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) * **iOS:** XCUITest (9.3+), UIAutomation (8.0 to 9.3) * **Android:** UiAutomator (4.2+) *** ## activateApp[​](#activateapp "Direct link to activateApp") Activate the given app on the device<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/appium/#activateapp). ### Usage[​](#usage-13 "Direct link to Usage") ``` await driver.activateApp(appId, bundleId, options) ``` ### Parameters[​](#parameters-6 "Direct link to Parameters") | Name | Type | Details | | -------------------------- | -------- | ------------------------------------- | | `appId`<br />*optional* | `string` | App package ID (required for Android) | | `bundleId`<br />*optional* | `string` | Bundle ID (required for iOS) | | `options`<br />*optional* | `object` | Driver-specific launch options | ### Support[​](#support-4 "Direct link to Support") ![Support for XCUITest (9.3+)](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) * **iOS:** XCUITest (9.3+) * **Android:** UiAutomator (4.2+) *** ## removeApp[​](#removeapp "Direct link to removeApp") Remove an app from the device.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/appium/#removeapp). ### Usage[​](#usage-14 "Direct link to Usage") ``` await driver.removeApp(appId, bundleId, options) ``` ### Parameters[​](#parameters-7 "Direct link to Parameters") | Name | Type | Details | | -------------------------- | -------- | ------------------------------------- | | `appId`<br />*optional* | `string` | App package ID (required for Android) | | `bundleId`<br />*optional* | `string` | Bundle ID (required for iOS) | | `options`<br />*optional* | `object` | Driver-specific uninstall options | ### Returns[​](#returns-10 "Direct link to Returns") * **\<boolean>** **`didRemovalSucceed`:** Return true if uninstall was successful, false if not ### Support[​](#support-5 "Direct link to Support") ![Support for XCUITest (9.3+), UIAutomation (8.0 to 9.3)](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) * **iOS:** XCUITest (9.3+), UIAutomation (8.0 to 9.3) * **Android:** UiAutomator (4.2+) *** ## terminateApp[​](#terminateapp "Direct link to terminateApp") Terminate the given app on the device<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/appium/#terminateapp). ### Usage[​](#usage-15 "Direct link to Usage") ``` await driver.terminateApp(appId, bundleId, options) ``` ### Parameters[​](#parameters-8 "Direct link to Parameters") | Name | Type | Details | | -------------------------- | -------- | ------------------------------------- | | `appId`<br />*optional* | `string` | App package ID (required for Android) | | `bundleId`<br />*optional* | `string` | Bundle ID (required for iOS) | | `options`<br />*optional* | `object` | Driver-specific termination options | ### Support[​](#support-6 "Direct link to Support") ![Support for XCUITest (9.3+)](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) * **iOS:** XCUITest (9.3+) * **Android:** UiAutomator (4.2+) *** ## isAppInstalled[​](#isappinstalled "Direct link to isAppInstalled") Check whether the specified app is installed on the device.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/appium/#isappinstalled). ### Usage[​](#usage-16 "Direct link to Usage") ``` await driver.isAppInstalled(appId, bundleId) ``` ### Parameters[​](#parameters-9 "Direct link to Parameters") | Name | Type | Details | | -------------------------- | -------- | ------------------------------------- | | `appId`<br />*optional* | `string` | App package ID (required for Android) | | `bundleId`<br />*optional* | `string` | Bundle ID (required for iOS) | ### Returns[​](#returns-11 "Direct link to Returns") * **\<boolean>** **`isAppInstalled`:** Return true if installed, false if not ### Support[​](#support-7 "Direct link to Support") ![Support for XCUITest (9.3+), UIAutomation (8.0 to 9.3)](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) * **iOS:** XCUITest (9.3+), UIAutomation (8.0 to 9.3) * **Android:** UiAutomator (4.2+) *** ## queryAppState[​](#queryappstate "Direct link to queryAppState") Get the given app status on the device<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/appium/#queryappstate). ### Usage[​](#usage-17 "Direct link to Usage") ``` await driver.queryAppState(appId, bundleId) ``` ### Parameters[​](#parameters-10 "Direct link to Parameters") | Name | Type | Details | | -------------------------- | -------- | ------------------------------------- | | `appId`<br />*optional* | `string` | App package ID (required for Android) | | `bundleId`<br />*optional* | `string` | Bundle ID (required for iOS) | ### Returns[​](#returns-12 "Direct link to Returns") * **\<number>** **`appStatus`:** 0 is not installed. 1 is not running. 2 is running in background suspended. 3 is running in background. 4 is running in foreground ### Support[​](#support-8 "Direct link to Support") ![Support for XCUITest (9.3+)](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) * **iOS:** XCUITest (9.3+) * **Android:** UiAutomator (4.2+) *** ## hideKeyboard[​](#hidekeyboard "Direct link to hideKeyboard") Hide soft keyboard.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/appium/#hidekeyboard). ### Usage[​](#usage-18 "Direct link to Usage") ``` await driver.hideKeyboard(strategy, key, keyCode, keyName) ``` ### Parameters[​](#parameters-11 "Direct link to Parameters") | Name | Type | Details | | -------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------- | | `strategy`<br />*optional* | `string` | hide keyboard strategy (UIAutomation only), available strategies - 'press', 'pressKey', 'swipeDown', 'tapOut', 'tapOutside', 'default' | | `key`<br />*optional* | `string` | key value if strategy is 'pressKey' | | `keyCode`<br />*optional* | `string` | key code if strategy is 'pressKey' | | `keyName`<br />*optional* | `string` | key name if strategy is 'pressKey' | ### Support[​](#support-9 "Direct link to Support") ![Support for XCUITest (9.3+), UIAutomation (8.0 to 9.3)](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) ![Support for Windows (10+)](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA4OCA4OCI+PHBhdGggZD0ibTAgMTIuNDAyIDM1LjY4Ny00Ljg2MDIuMDE1NiAzNC40MjMtMzUuNjcuMjAzMTN6bTM1LjY3IDMzLjUyOS4wMjc3IDM0LjQ1My0zNS42Ny00LjkwNDEtLjAwMi0yOS43OHptNC4zMjYxLTM5LjAyNSA0Ny4zMTgtNi45MDZ2NDEuNTI3bC00Ny4zMTguMzc1NjV6bTQ3LjMyOSAzOS4zNDktLjAxMTEgNDEuMzQtNDcuMzE4LTYuNjc4NC0uMDY2My0zNC43Mzl6IiBmaWxsPSIjMDBhZGVmIi8+PC9zdmc+) * **iOS:** XCUITest (9.3+), UIAutomation (8.0 to 9.3) * **Android:** UiAutomator (4.2+) * **Windows:** Windows (10+) *** ## isKeyboardShown[​](#iskeyboardshown "Direct link to isKeyboardShown") Whether or not the soft keyboard is shown.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/appium/#iskeyboardshown). ### Usage[​](#usage-19 "Direct link to Usage") ``` await driver.isKeyboardShown() ``` ### Returns[​](#returns-13 "Direct link to Returns") * **\<boolean>** **`isKeyboardShown`:** True if the keyboard is shown ### Support[​](#support-10 "Direct link to Support") ![Support for XCUITest (9.3+), UIAutomation (8.0 to 9.3)](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) ![Support for Windows (10+)](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA4OCA4OCI+PHBhdGggZD0ibTAgMTIuNDAyIDM1LjY4Ny00Ljg2MDIuMDE1NiAzNC40MjMtMzUuNjcuMjAzMTN6bTM1LjY3IDMzLjUyOS4wMjc3IDM0LjQ1My0zNS42Ny00LjkwNDEtLjAwMi0yOS43OHptNC4zMjYxLTM5LjAyNSA0Ny4zMTgtNi45MDZ2NDEuNTI3bC00Ny4zMTguMzc1NjV6bTQ3LjMyOSAzOS4zNDktLjAxMTEgNDEuMzQtNDcuMzE4LTYuNjc4NC0uMDY2My0zNC43Mzl6IiBmaWxsPSIjMDBhZGVmIi8+PC9zdmc+) * **iOS:** XCUITest (9.3+), UIAutomation (8.0 to 9.3) * **Android:** UiAutomator (4.2+) * **Windows:** Windows (10+) *** ## pushFile[​](#pushfile "Direct link to pushFile") Place a file onto the device in a particular place.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/appium/#pushfile). ### Usage[​](#usage-20 "Direct link to Usage") ``` await driver.pushFile(path, data) ``` ### Parameters[​](#parameters-12 "Direct link to Parameters") | Name | Type | Details | | ------ | -------- | --------------------------- | | `path` | `string` | path to install the data to | | `data` | `string` | contents of file in base64 | ### Support[​](#support-11 "Direct link to Support") ![Support for XCUITest (9.3+), UIAutomation (8.0 to 9.3)](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) ![Support for Windows (10+)](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA4OCA4OCI+PHBhdGggZD0ibTAgMTIuNDAyIDM1LjY4Ny00Ljg2MDIuMDE1NiAzNC40MjMtMzUuNjcuMjAzMTN6bTM1LjY3IDMzLjUyOS4wMjc3IDM0LjQ1My0zNS42Ny00LjkwNDEtLjAwMi0yOS43OHptNC4zMjYxLTM5LjAyNSA0Ny4zMTgtNi45MDZ2NDEuNTI3bC00Ny4zMTguMzc1NjV6bTQ3LjMyOSAzOS4zNDktLjAxMTEgNDEuMzQtNDcuMzE4LTYuNjc4NC0uMDY2My0zNC43Mzl6IiBmaWxsPSIjMDBhZGVmIi8+PC9zdmc+) * **iOS:** XCUITest (9.3+), UIAutomation (8.0 to 9.3) * **Android:** UiAutomator (4.2+) * **Windows:** Windows (10+) *** ## pullFile[​](#pullfile "Direct link to pullFile") Retrieve a file from the device's file system.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/appium/#pullfile). ### Usage[​](#usage-21 "Direct link to Usage") ``` await driver.pullFile(path) ``` ### Parameters[​](#parameters-13 "Direct link to Parameters") | Name | Type | Details | | ------ | -------- | ------------------------------------ | | `path` | `string` | path on the device to pull file from | ### Returns[​](#returns-14 "Direct link to Returns") * **\<string>** **`response`:** Contents of file in base64 ### Support[​](#support-12 "Direct link to Support") ![Support for XCUITest (9.3+), UIAutomation (8.0 to 9.3)](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) ![Support for Windows (10+)](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA4OCA4OCI+PHBhdGggZD0ibTAgMTIuNDAyIDM1LjY4Ny00Ljg2MDIuMDE1NiAzNC40MjMtMzUuNjcuMjAzMTN6bTM1LjY3IDMzLjUyOS4wMjc3IDM0LjQ1My0zNS42Ny00LjkwNDEtLjAwMi0yOS43OHptNC4zMjYxLTM5LjAyNSA0Ny4zMTgtNi45MDZ2NDEuNTI3bC00Ny4zMTguMzc1NjV6bTQ3LjMyOSAzOS4zNDktLjAxMTEgNDEuMzQtNDcuMzE4LTYuNjc4NC0uMDY2My0zNC43Mzl6IiBmaWxsPSIjMDBhZGVmIi8+PC9zdmc+) * **iOS:** XCUITest (9.3+), UIAutomation (8.0 to 9.3) * **Android:** UiAutomator (4.2+) * **Windows:** Windows (10+) *** ## pullFolder[​](#pullfolder "Direct link to pullFolder") Retrieve a folder from the device's file system.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/appium/#pullfolder). ### Usage[​](#usage-22 "Direct link to Usage") ``` await driver.pullFolder(path) ``` ### Parameters[​](#parameters-14 "Direct link to Parameters") | Name | Type | Details | | ------ | -------- | -------------------------------------- | | `path` | `string` | path to an entire folder on the device | ### Returns[​](#returns-15 "Direct link to Returns") * **\<string>** **`response`:** Zip file of the folder contents in base64 ### Support[​](#support-13 "Direct link to Support") ![Support for XCUITest (9.3+), UIAutomation (8.0 to 9.3)](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) ![Support for Windows (10+)](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA4OCA4OCI+PHBhdGggZD0ibTAgMTIuNDAyIDM1LjY4Ny00Ljg2MDIuMDE1NiAzNC40MjMtMzUuNjcuMjAzMTN6bTM1LjY3IDMzLjUyOS4wMjc3IDM0LjQ1My0zNS42Ny00LjkwNDEtLjAwMi0yOS43OHptNC4zMjYxLTM5LjAyNSA0Ny4zMTgtNi45MDZ2NDEuNTI3bC00Ny4zMTguMzc1NjV6bTQ3LjMyOSAzOS4zNDktLjAxMTEgNDEuMzQtNDcuMzE4LTYuNjc4NC0uMDY2My0zNC43Mzl6IiBmaWxsPSIjMDBhZGVmIi8+PC9zdmc+) * **iOS:** XCUITest (9.3+), UIAutomation (8.0 to 9.3) * **Android:** UiAutomator (4.2+) * **Windows:** Windows (10+) *** ## getDeviceTime[​](#getdevicetime "Direct link to getDeviceTime") Get the time on the device.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.github.io/appium.io/docs/en/commands/device/system/system-time/). ### Usage[​](#usage-23 "Direct link to Usage") ``` await driver.getDeviceTime() ``` ### Returns[​](#returns-16 "Direct link to Returns") * **\<string>** **`time`:** Time on the device ### Support[​](#support-14 "Direct link to Support") ![Support for XCUITest (9.3+), UIAutomation (8.0 to 9.3)](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) * **iOS:** XCUITest (9.3+), UIAutomation (8.0 to 9.3) * **Android:** UiAutomator (4.2+) *** ## getSettings[​](#getsettings "Direct link to getSettings") Retrieve the current session settings.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/appium/#getsettings). ### Usage[​](#usage-24 "Direct link to Usage") ``` await driver.getSettings() ``` ### Returns[​](#returns-17 "Direct link to Returns") * **\<object>** **`settings`:** JSON hash of all the currently specified settings, see Settings API ### Support[​](#support-15 "Direct link to Support") ![Support for XCUITest (9.3+), UIAutomation (8.0 to 9.3)](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) ![Support for Windows (10+)](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA4OCA4OCI+PHBhdGggZD0ibTAgMTIuNDAyIDM1LjY4Ny00Ljg2MDIuMDE1NiAzNC40MjMtMzUuNjcuMjAzMTN6bTM1LjY3IDMzLjUyOS4wMjc3IDM0LjQ1My0zNS42Ny00LjkwNDEtLjAwMi0yOS43OHptNC4zMjYxLTM5LjAyNSA0Ny4zMTgtNi45MDZ2NDEuNTI3bC00Ny4zMTguMzc1NjV6bTQ3LjMyOSAzOS4zNDktLjAxMTEgNDEuMzQtNDcuMzE4LTYuNjc4NC0uMDY2My0zNC43Mzl6IiBmaWxsPSIjMDBhZGVmIi8+PC9zdmc+) * **iOS:** XCUITest (9.3+), UIAutomation (8.0 to 9.3) * **Android:** UiAutomator (4.2+) * **Windows:** Windows (10+) *** ## updateSettings[​](#updatesettings "Direct link to updateSettings") Update the session settings.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/appium/#updatesettings). ### Usage[​](#usage-25 "Direct link to Usage") ``` await driver.updateSettings(settings) ``` ### Parameters[​](#parameters-15 "Direct link to Parameters") | Name | Type | Details | | ---------- | -------- | ---------------------------------------- | | `settings` | `object` | key/value object with settings to update | ### Support[​](#support-16 "Direct link to Support") ![Support for XCUITest (9.3+), UIAutomation (8.0 to 9.3)](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) ![Support for Windows (10+)](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA4OCA4OCI+PHBhdGggZD0ibTAgMTIuNDAyIDM1LjY4Ny00Ljg2MDIuMDE1NiAzNC40MjMtMzUuNjcuMjAzMTN6bTM1LjY3IDMzLjUyOS4wMjc3IDM0LjQ1My0zNS42Ny00LjkwNDEtLjAwMi0yOS43OHptNC4zMjYxLTM5LjAyNSA0Ny4zMTgtNi45MDZ2NDEuNTI3bC00Ny4zMTguMzc1NjV6bTQ3LjMyOSAzOS4zNDktLjAxMTEgNDEuMzQtNDcuMzE4LTYuNjc4NC0uMDY2My0zNC43Mzl6IiBmaWxsPSIjMDBhZGVmIi8+PC9zdmc+) * **iOS:** XCUITest (9.3+), UIAutomation (8.0 to 9.3) * **Android:** UiAutomator (4.2+) * **Windows:** Windows (10+) *** ## executeDriverScript[​](#executedriverscript "Direct link to executeDriverScript") Execute a script in a child process. This approach helps minimize potential latency associated with each command. ***Using this command in Appium 2 or later requires installing the [`execute-driver`](https://github.com/appium/appium/tree/master/packages/execute-driver-plugin) plugin.***<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/plugins/#executedriverscript). ### Usage[​](#usage-26 "Direct link to Usage") ``` await driver.executeDriverScript(script, type, timeout) ``` ### Parameters[​](#parameters-16 "Direct link to Parameters") | Name | Type | Details | | ------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `script` | `string` | The script to execute. It has access to a 'driver' object which represents a WebdriverIO session attached to the current server. | | `type`<br />*optional* | `string` | The language/framework used in the script. Currently, only 'webdriverio' is supported and is the default. | | `timeout`<br />*optional* | `number` | The number of milliseconds the script should be allowed to run before being killed by the Appium server. Defaults to the equivalent of 1 hour. | ### Returns[​](#returns-18 "Direct link to Returns") * **\<object>** **`result`:** An object containing two fields: 'result', which is the return value of the script itself, and 'logs', which contains 3 inner fields, 'log', 'warn', and 'error', which hold an array of strings logged by console.log, console.warn, and console.error in the script's execution. *** ## getEvents[​](#getevents "Direct link to getEvents") Get events logged in the current session.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/appium/#getlogevents). ### Usage[​](#usage-27 "Direct link to Usage") ``` await driver.getEvents(type) ``` ### Parameters[​](#parameters-17 "Direct link to Parameters") | Name | Type | Details | | ---------------------- | ------------------ | ----------------------------------------------------- | | `type`<br />*optional* | `string, string[]` | One or more event types to filter the returned events | ### Returns[​](#returns-19 "Direct link to Returns") * **\<object>** **`result`:** A JSON hash of events like `{'commands' => [{'cmd' => 123455, ....}], 'startTime' => 1572954894127, }`. ### Support[​](#support-17 "Direct link to Support") ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) ![Support for XCUITest (9.3+)](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) * **Android:** UiAutomator (4.2+) * **iOS:** XCUITest (9.3+) *** ## logEvent[​](#logevent "Direct link to logEvent") Log a custom event.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/appium/#logcustomevent). ### Usage[​](#usage-28 "Direct link to Usage") ``` await driver.logEvent(vendor, event) ``` ### Parameters[​](#parameters-18 "Direct link to Parameters") | Name | Type | Details | | -------- | -------- | ------------------------------------------------------- | | `vendor` | `string` | Name of the namespace (vendor) used to prefix the event | | `event` | `string` | Name of the event | ### Support[​](#support-18 "Direct link to Support") ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) ![Support for XCUITest (9.3+)](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) * **Android:** UiAutomator (4.2+) * **iOS:** XCUITest (9.3+) *** ## compareImages[​](#compareimages "Direct link to compareImages") Compare two images using the specified mode of comparison. ***Using this command in Appium 2 or later requires installing the [`images`](https://github.com/appium/appium/tree/master/packages/images-plugin) plugin.***<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/plugins/#compareimages). ### Usage[​](#usage-29 "Direct link to Usage") ``` await driver.compareImages(mode, firstImage, secondImage, options) ``` ### Parameters[​](#parameters-19 "Direct link to Parameters") | Name | Type | Details | | ----------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------ | | `mode` | `string` | One of possible comparison modes: 'matchFeatures', 'getSimilarity', 'matchTemplate'. | | `firstImage` | `string` | Base64-encoded image file. | | `secondImage` | `string` | Base64-encoded image file. | | `options=[object Object]`<br />*optional* | `object` | The supported values of this property depend on the `mode` value. See Appium documentation for more details. | ### Returns[​](#returns-20 "Direct link to Returns") * **\<object>** **`result`:** The content of the resulting dictionary depends on the `mode` and `options` values. See Appium documentation for more details. *** ## availableIMEEngines[​](#availableimeengines "Direct link to availableIMEEngines") List all available IME engines on the device. To use an engine, it has to be present in this list.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/jsonwp/#availableimeengines). ### Usage[​](#usage-30 "Direct link to Usage") ``` await driver.availableIMEEngines() ``` ### Returns[​](#returns-21 "Direct link to Returns") * **\<String\[]>** **`engines`:** A list of available engines ### Support[​](#support-19 "Direct link to Support") ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) * **Android:** UiAutomator (4.2+) *** ## getActiveIMEEngine[​](#getactiveimeengine "Direct link to getActiveIMEEngine") Get the name of the active IME engine. The name string is platform specific.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/jsonwp/#getactiveimeengine). ### Usage[​](#usage-31 "Direct link to Usage") ``` await driver.getActiveIMEEngine() ``` ### Returns[​](#returns-22 "Direct link to Returns") * **\<String>** **`engine`:** The name of the active IME engine ### Support[​](#support-20 "Direct link to Support") ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) * **Android:** UiAutomator (4.2+) *** ## isIMEActivated[​](#isimeactivated "Direct link to isIMEActivated") Indicates whether IME input is active at the moment<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/jsonwp/#isimeactivated). ### Usage[​](#usage-32 "Direct link to Usage") ``` await driver.isIMEActivated() ``` ### Returns[​](#returns-23 "Direct link to Returns") * **\<Boolean>** **`isActive`:** true if IME input is available and currently active, false otherwise ### Support[​](#support-21 "Direct link to Support") ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) * **Android:** UiAutomator (4.2+) *** ## deactivateIMEEngine[​](#deactivateimeengine "Direct link to deactivateIMEEngine") De-activates the currently-active IME engine.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/jsonwp/#deactivateimeengine). ### Usage[​](#usage-33 "Direct link to Usage") ``` await driver.deactivateIMEEngine() ``` ### Support[​](#support-22 "Direct link to Support") ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) * **Android:** UiAutomator (4.2+) *** ## activateIMEEngine[​](#activateimeengine "Direct link to activateIMEEngine") Activates an IME engine.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/jsonwp/#activateimeengine). ### Usage[​](#usage-34 "Direct link to Usage") ``` await driver.activateIMEEngine(engine) ``` ### Parameters[​](#parameters-20 "Direct link to Parameters") | Name | Type | Details | | -------- | -------- | ------------------------------ | | `engine` | `string` | name of the engine to activate | ### Support[​](#support-23 "Direct link to Support") ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) * **Android:** UiAutomator (4.2+) *** ## getOrientation[​](#getorientation "Direct link to getOrientation") Get the current device orientation.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/jsonwp/#getorientation). ### Usage[​](#usage-35 "Direct link to Usage") ``` await driver.getOrientation() ``` ### Returns[​](#returns-24 "Direct link to Returns") * **\<String>** **`orientation`:** The current orientation corresponding to a value defined in ScreenOrientation: `LANDSCAPE|PORTRAIT`. ### Support[​](#support-24 "Direct link to Support") ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) ![Support for XCUITest (9.3+)](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) * **Android:** UiAutomator (4.2+) * **iOS:** XCUITest (9.3+) *** ## setOrientation[​](#setorientation "Direct link to setOrientation") Set the device orientation<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/jsonwp/#setorientation). ### Usage[​](#usage-36 "Direct link to Usage") ``` await driver.setOrientation(orientation) ``` ### Parameters[​](#parameters-21 "Direct link to Parameters") | Name | Type | Details | | ------------- | -------- | ---------------------------------------------------------------------------------- | | `orientation` | `string` | the new browser orientation as defined in ScreenOrientation: `LANDSCAPE\|PORTRAIT` | ### Support[​](#support-25 "Direct link to Support") ![Support for UiAutomator (4.2+)](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) ![Support for XCUITest (9.3+)](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) * **Android:** UiAutomator (4.2+) * **iOS:** XCUITest (9.3+) *** ## getGeoLocation[​](#getgeolocation "Direct link to getGeoLocation") Get the current geo location.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/jsonwp/#getgeolocation). ### Usage[​](#usage-37 "Direct link to Usage") ``` await driver.getGeoLocation() ``` ### Returns[​](#returns-25 "Direct link to Returns") * **\<Object>** **`location`:** The current geo location. *** ## setGeoLocation[​](#setgeolocation "Direct link to setGeoLocation") Set the current geo location.<br /><br />Appium command. More details can be found in the [official protocol docs](https://appium.io/docs/en/latest/reference/api/jsonwp/#setgeolocation). ### Usage[​](#usage-38 "Direct link to Usage") ``` await driver.setGeoLocation(location) ``` ### Parameters[​](#parameters-22 "Direct link to Parameters") | Name | Type | Details | | ---------- | -------- | ---------------------------------------------------------------------------- | | `location` | `object` | the new location (`{latitude: number, longitude: number, altitude: number}`) | --- Source: https://webdriver.io/docs/api/chromium.md # Chromium ## isAlertOpen[​](#isalertopen "Direct link to isAlertOpen") Whether a simple dialog is currently open.<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://github.com/bayandin/chromedriver/blob/v2.45/alert_commands.cc#L42-L49). ### Usage[​](#usage "Direct link to Usage") ``` await browser.isAlertOpen() ``` ### Example[​](#example "Direct link to Example") ``` console.log(browser.isAlertOpen()); // outputs: false browser.execute('window.alert()'); console.log(browser.isAlertOpen()); // outputs: true ``` ### Returns[​](#returns "Direct link to Returns") * **\<Boolean>** **`isAlertOpen`:** `true` or `false` based on whether simple dialog is present or not. *** ## isAutoReporting[​](#isautoreporting "Direct link to isAutoReporting") Whether it should automatically raises errors on browser logs.<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://codereview.chromium.org/101203012). ### Usage[​](#usage-1 "Direct link to Usage") ``` await browser.isAutoReporting() ``` ### Returns[​](#returns-1 "Direct link to Returns") * **\<Boolean>** **`isAutoReporting`:** `true` or `false` based on whether auto reporting is enabled. *** ## setAutoReporting[​](#setautoreporting "Direct link to setAutoReporting") Toggle whether to return response with unknown error with first browser error (e.g. failed to load resource due to 403/404 response) for all subsequent commands (once enabled).<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://codereview.chromium.org/101203012). ### Usage[​](#usage-2 "Direct link to Usage") ``` await browser.setAutoReporting(enabled) ``` ### Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------- | --------- | ----------------------------------------------------------------------------------------------------- | | `enabled` | `boolean` | `true` if auto reporting should be enabled, use `false` to disable previously enabled auto reporting. | ### Examples[​](#examples "Direct link to Examples") ``` // Enable auto reporting first thing after session was initiated with empty browser logs console.log(browser.setAutoReporting(true)); // outputs: null // Upon requesting an non-existing resource it will abort execution due to thrown unknown error browser.url('https://webdriver.io/img/404-does-not-exist.png'); ``` ``` // During the session do some operations which populate the browser logs browser.url('https://webdriver.io/img/404-does-not-exist.png'); browser.url('https://webdriver.io/403/no-access'); // Enable auto reporting which throws an unknown error for first browser log (404 response) browser.setAutoReporting(true); ``` ### Returns[​](#returns-2 "Direct link to Returns") * **\<Object|Null>** **`firstBrowserError`:** In case first browser error already occured prior to executing this command it will throw unknown error as response, which is an object with 'message' key describing first browser error. Otherwise it returns `null` on success. *** ## isLoading[​](#isloading "Direct link to isLoading") Determines load status for active window handle.<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://github.com/bayandin/chromedriver/blob/v2.45/session_commands.cc#L783-L802). ### Usage[​](#usage-3 "Direct link to Usage") ``` await browser.isLoading() ``` ### Example[​](#example-1 "Direct link to Example") ``` console.log(browser.isLoading()); // outputs: false browser.newWindow('https://webdriver.io'); console.log(browser.isLoading()); // outputs: true ``` ### Returns[​](#returns-3 "Direct link to Returns") * **\<Boolean>** **`isLoading`:** `true` or `false` based on whether active window handle is loading or not. *** ## takeHeapSnapshot[​](#takeheapsnapshot "Direct link to takeHeapSnapshot") Takes a heap snapshot of the current execution context.<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://github.com/bayandin/chromedriver/blob/v2.45/chrome/web_view.h#L198-L202). ### Usage[​](#usage-4 "Direct link to Usage") ``` await browser.takeHeapSnapshot() ``` ### Returns[​](#returns-4 "Direct link to Returns") * **\<Object>** **`heapSnapshot`:** A JSON representation of the heap snapshot. Which can be inspected by loading as file into Chrome DevTools. *** ## getNetworkConnection[​](#getnetworkconnection "Direct link to getNetworkConnection") Get the connection type for network emulation. This command is only applicable when remote end replies with `networkConnectionEnabled` capability set to `true`.<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://github.com/SeleniumHQ/mobile-spec/blob/master/spec-draft.md#device-modes). ### Usage[​](#usage-5 "Direct link to Usage") ``` await browser.getNetworkConnection() ``` ### Example[​](#example-2 "Direct link to Example") ``` const browser = remote({ capabilities: { browserName: 'chrome', 'goog:chromeOptions': { // Network emulation requires device mode, which is only enabled when mobile emulation is on mobileEmulation: { deviceName: 'iPad' }, }, } }); console.log(browser.getNetworkConnection()); // outputs: 6 (Both Wi-Fi and data) ``` ### Returns[​](#returns-5 "Direct link to Returns") * **\<Number>** **`connectionType`:** A bitmask to represent the network connection type. Airplane Mode (`1`), Wi-Fi only (`2`), Wi-Fi and data (`6`), 4G (`8`), 3G (`10`), 2G (`20`). By default [Wi-Fi and data are enabled](https://github.com/bayandin/chromedriver/blob/v2.45/chrome/chrome_desktop_impl.cc#L36-L37). *** ## setNetworkConnection[​](#setnetworkconnection "Direct link to setNetworkConnection") Change connection type for network connection. This command is only applicable when remote end replies with `networkConnectionEnabled` capability set to `true`.<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://github.com/SeleniumHQ/mobile-spec/blob/master/spec-draft.md#device-modes). ### Usage[​](#usage-6 "Direct link to Usage") ``` await browser.setNetworkConnection(parameters) ``` ### Parameters[​](#parameters-1 "Direct link to Parameters") | Name | Type | Details | | ------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `parameters` | `object` | Object containing ConnectionType, set bitmask as value for `type` key in object. Airplane Mode (`1`), Wi-Fi only (`2`), Wi-Fi and data (`6`), 4G (`8`), 3G (`10`), 2G (`20`). | ### Example[​](#example-3 "Direct link to Example") ``` const browser = remote({ capabilities: { browserName: 'chrome', 'goog:chromeOptions': { // Network emulation requires device mode, which is only enabled when mobile emulation is on mobileEmulation: { deviceName: 'iPad' }, }, } }); console.log(browser.setNetworkConnection({ type: 1 })); // outputs: 1 (Airplane Mode) ``` ### Returns[​](#returns-6 "Direct link to Returns") * **\<Number>** **`connectionType`:** A bitmask to represent the network connection type. Value should match specified `type` in object, however device might not be capable of the network connection type requested. *** ## getNetworkConditions[​](#getnetworkconditions "Direct link to getNetworkConditions") Get current network conditions used for emulation.<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://github.com/bayandin/chromedriver/blob/v2.45/session_commands.cc#L839-L859). ### Usage[​](#usage-7 "Direct link to Usage") ``` await browser.getNetworkConditions() ``` ### Returns[​](#returns-7 "Direct link to Returns") * **\<Object>** **`networkConditions`:** Object containing network conditions for `offline`, `latency`, `download_throughput` and `upload_throughput`. Network conditions must be set before it can be retrieved. *** ## setNetworkConditions[​](#setnetworkconditions "Direct link to setNetworkConditions") Set network conditions used for emulation by throttling connection.<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://github.com/bayandin/chromedriver/blob/v2.45/window_commands.cc#L1663-L1722). ### Usage[​](#usage-8 "Direct link to Usage") ``` await browser.setNetworkConditions(network_conditions, network_name) ``` ### Parameters[​](#parameters-2 "Direct link to Parameters") | Name | Type | Details | | ------------------------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `network_conditions` | `object` | Object containing network conditions which are `latency`, `throughput` (or `download_throughput`/`upload_throughput`) and `offline` (optional). | | `network_name`<br />*optional* | `string` | Name of [network throttling preset](https://github.com/bayandin/chromedriver/blob/v2.45/chrome/network_list.cc#L12-L25). `GPRS`, `Regular 2G`, `Good 2G`, `Regular 3G`, `Good 3G`, `Regular 4G`, `DSL`, `WiFi` or `No throttling` to disable. When preset is specified values passed in first argument are not respected. | ### Examples[​](#examples-1 "Direct link to Examples") ``` // Use different download (25kb/s) and upload (50kb/s) throughput values for throttling with a latency of 1000ms browser.setNetworkConditions({ latency: 1000, download_throughput: 25600, upload_throughput: 51200 }); ``` ``` // Force disconnected from network by setting 'offline' to true browser.setNetworkConditions({ latency: 0, throughput: 0, offline: true }); ``` ``` // When preset name (e.g. 'DSL') is specified it does not respect values in object (e.g. 'offline') browser.setNetworkConditions({ latency: 0, throughput: 0, offline: true }, 'DSL'); ``` ``` // Best practice for specifying network throttling preset is to use an empty object browser.setNetworkConditions({}, 'Good 3G'); ``` *** ## deleteNetworkConditions[​](#deletenetworkconditions "Direct link to deleteNetworkConditions") Disable any network throttling which might have been set. Equivalent of setting the `No throttling` preset.<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://github.com/bayandin/chromedriver/blob/v2.45/window_commands.cc#L1724-L1745). ### Usage[​](#usage-9 "Direct link to Usage") ``` await browser.deleteNetworkConditions() ``` *** ## sendCommand[​](#sendcommand "Direct link to sendCommand") Send a command to the DevTools debugger.<br />For a list of available commands and their parameters refer to the [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/).<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://github.com/bayandin/chromedriver/blob/v2.45/window_commands.cc#L1290-L1304). ### Usage[​](#usage-10 "Direct link to Usage") ``` await browser.sendCommand(cmd, params) ``` ### Parameters[​](#parameters-3 "Direct link to Parameters") | Name | Type | Details | | -------- | -------- | -------------------------------------------------------------------------------------------------------------------------- | | `cmd` | `string` | Name of the command (e.g. [`Browser.close`](https://chromedevtools.github.io/devtools-protocol/1-3/Browser#method-close)). | | `params` | `object` | Parameters to the command. In case no parameters for command, specify an empty object. | *** ## sendCommandAndGetResult[​](#sendcommandandgetresult "Direct link to sendCommandAndGetResult") Send a command to the DevTools debugger and wait for the result.<br />For a list of available commands and their parameters refer to the [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/).<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://github.com/bayandin/chromedriver/blob/v2.45/window_commands.cc#L1306-L1320). ### Usage[​](#usage-11 "Direct link to Usage") ``` await browser.sendCommandAndGetResult(cmd, params) ``` ### Parameters[​](#parameters-4 "Direct link to Parameters") | Name | Type | Details | | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `cmd` | `string` | Name of the command which returns a result (e.g. [`Network.getAllCookies`](https://chromedevtools.github.io/devtools-protocol/1-3/Network#method-getAllCookies)). | | `params` | `object` | Parameters to the command. In case no parameters for command, specify an empty object. | ### Returns[​](#returns-8 "Direct link to Returns") * **<\*>** **`result`:** Either the return value of your command, or the error which was the reason for your command's failure. *** ## file[​](#file "Direct link to file") Upload a file to remote machine on which the browser is running.<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://github.com/bayandin/chromedriver/blob/v2.45/session_commands.cc#L1037-L1065). ### Usage[​](#usage-12 "Direct link to Usage") ``` await browser.file(file) ``` ### Parameters[​](#parameters-5 "Direct link to Parameters") | Name | Type | Details | | ------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `file` | `string` | Base64-encoded zip archive containing **single** file which to upload. In case base64-encoded data does not represent a zip archive or archive contains more than one file it will throw an unknown error. | ### Returns[​](#returns-9 "Direct link to Returns") * **\<String>** **`path`:** Absolute path of uploaded file on remote machine. *** ## launchChromeApp[​](#launchchromeapp "Direct link to launchChromeApp") Launches a Chrome app by specified id.<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://github.com/bayandin/chromedriver/blob/v2.45/session_commands.cc#L521-L539). ### Usage[​](#usage-13 "Direct link to Usage") ``` await browser.launchChromeApp(id) ``` ### Parameters[​](#parameters-6 "Direct link to Parameters") | Name | Type | Details | | ---- | -------- | ---------------------------------------------------------------------- | | `id` | `string` | Extension id of app to be launched, as defined in chrome://extensions. | ### Example[​](#example-4 "Direct link to Example") ``` import fs from 'fs' const browser = remote({ capabilities: { browserName: 'chrome', 'goog:chromeOptions': { // Install upon starting browser in order to launch it extensions: [ // Entry should be a base64-encoded packed Chrome app (.crx) fs.readFileSync('/absolute/path/app.crx').toString('base64') ] } } }); browser.launchChromeApp('aohghmighlieiainnegkcijnfilokake')); // Google Docs (https://chrome.google.com/webstore/detail/docs/aohghmighlieiainnegkcijnfilokake) ``` *** ## getElementValue[​](#getelementvalue "Direct link to getElementValue") Retrieves the value of a given form control element.<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://github.com/bayandin/chromedriver/blob/v2.45/element_commands.cc#L431-L443). ### Usage[​](#usage-14 "Direct link to Usage") ``` await browser.getElementValue(elementId) ``` ### Parameters[​](#parameters-7 "Direct link to Parameters") | Name | Type | Details | | ----------- | -------- | ------------------------------- | | `elementId` | `String` | id of element to get value from | ### Returns[​](#returns-10 "Direct link to Returns") * **\<String|Null>** **`value`:** Current value of the element. In case specified element is not a form control element, it will return `null`. *** ## elementHover[​](#elementhover "Direct link to elementHover") Enable hover state for an element, which is reset upon next interaction.<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://github.com/bayandin/chromedriver/blob/v2.45/element_commands.cc#L126-L146). ### Usage[​](#usage-15 "Direct link to Usage") ``` await browser.elementHover(elementId) ``` ### Parameters[​](#parameters-8 "Direct link to Parameters") | Name | Type | Details | | ----------- | -------- | ------------------------------ | | `elementId` | `String` | id of element to hover over to | *** ## touchPinch[​](#touchpinch "Direct link to touchPinch") Trigger a pinch zoom effect.<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://github.com/bayandin/chromedriver/blob/v2.45/window_commands.cc#L813-L827). ### Usage[​](#usage-16 "Direct link to Usage") ``` await browser.touchPinch(x, y, scale) ``` ### Parameters[​](#parameters-9 "Direct link to Parameters") | Name | Type | Details | | ------- | -------- | ---------------------- | | `x` | `number` | x position to pinch on | | `y` | `number` | y position to pinch on | | `scale` | `number` | pinch zoom scale | *** ## freeze[​](#freeze "Direct link to freeze") Freeze the current page. Extension for [Page Lifecycle API](https://developers.google.com/web/updates/2018/07/page-lifecycle-api).<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://github.com/bayandin/chromedriver/blob/v2.45/window_commands.cc#L625-L633). ### Usage[​](#usage-17 "Direct link to Usage") ``` await browser.freeze() ``` *** ## resume[​](#resume "Direct link to resume") Resume the current page. Extension for [Page Lifecycle API](https://developers.google.com/web/updates/2018/07/page-lifecycle-api).<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://github.com/bayandin/chromedriver/blob/v2.45/window_commands.cc#L635-L645). ### Usage[​](#usage-18 "Direct link to Usage") ``` await browser.resume() ``` *** ## getCastSinks[​](#getcastsinks "Direct link to getCastSinks") Returns the list of cast sinks (Cast devices) available to the Chrome media router.<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://chromium.googlesource.com/chromium/src/+/refs/tags/73.0.3683.121/chrome/test/chromedriver/server/http_handler.cc#748). ### Usage[​](#usage-19 "Direct link to Usage") ``` await browser.getCastSinks() ``` ### Returns[​](#returns-11 "Direct link to Returns") * **\<string\[]>** **`sinks`:** List of available sinks. *** ## selectCastSink[​](#selectcastsink "Direct link to selectCastSink") Selects a cast sink (Cast device) as the recipient of media router intents (connect or play).<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://chromium.googlesource.com/chromium/src/+/refs/tags/73.0.3683.121/chrome/test/chromedriver/server/http_handler.cc#737). ### Usage[​](#usage-20 "Direct link to Usage") ``` await browser.selectCastSink(sinkName) ``` ### Parameters[​](#parameters-10 "Direct link to Parameters") | Name | Type | Details | | ---------- | -------- | ------------------------------ | | `sinkName` | `string` | The name of the target device. | *** ## startCastTabMirroring[​](#startcasttabmirroring "Direct link to startCastTabMirroring") Initiates tab mirroring for the current browser tab on the specified device.<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://chromium.googlesource.com/chromium/src/+/refs/tags/73.0.3683.121/chrome/test/chromedriver/server/http_handler.cc#741). ### Usage[​](#usage-21 "Direct link to Usage") ``` await browser.startCastTabMirroring(sinkName) ``` ### Parameters[​](#parameters-11 "Direct link to Parameters") | Name | Type | Details | | ---------- | -------- | ------------------------------ | | `sinkName` | `string` | The name of the target device. | *** ## getCastIssueMessage[​](#getcastissuemessage "Direct link to getCastIssueMessage") Returns error message if there is any issue in a Cast session.<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://chromium.googlesource.com/chromium/src/+/refs/tags/73.0.3683.121/chrome/test/chromedriver/server/http_handler.cc#751). ### Usage[​](#usage-22 "Direct link to Usage") ``` await browser.getCastIssueMessage() ``` ### Returns[​](#returns-12 "Direct link to Returns") * **\<String>** **`message`:** Error message, if any. *** ## stopCasting[​](#stopcasting "Direct link to stopCasting") Stops casting from media router to the specified device, if connected.<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://chromium.googlesource.com/chromium/src/+/refs/tags/73.0.3683.121/chrome/test/chromedriver/server/http_handler.cc#744). ### Usage[​](#usage-23 "Direct link to Usage") ``` await browser.stopCasting(sinkName) ``` ### Parameters[​](#parameters-12 "Direct link to Parameters") | Name | Type | Details | | ---------- | -------- | ------------------------------ | | `sinkName` | `string` | The name of the target device. | *** ## shutdown[​](#shutdown "Direct link to shutdown") Shutdown ChromeDriver process and consequently terminating all active sessions.<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://github.com/bayandin/chromedriver/blob/v2.45/session_commands.cc#L489-L498). ### Usage[​](#usage-24 "Direct link to Usage") ``` await browser.shutdown() ``` *** ## takeElementScreenshot[​](#takeelementscreenshot "Direct link to takeElementScreenshot") The Take Element Screenshot command takes a screenshot of the visible region encompassed by the bounding rectangle of an element.<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://w3c.github.io/webdriver/#dfn-take-element-screenshot). ### Usage[​](#usage-25 "Direct link to Usage") ``` await browser.takeElementScreenshot(elementId) ``` ### Parameters[​](#parameters-13 "Direct link to Parameters") | Name | Type | Details | | ----------- | -------- | ------------------------------------------------------------------- | | `elementId` | `String` | the id of an element returned in a previous call to Find Element(s) | ### Returns[​](#returns-13 "Direct link to Returns") * **\<String>** **`screenshot`:** The base64-encoded PNG image data comprising the screenshot of the visible region of an element’s bounding rectangle after it has been scrolled into view. *** ## getLogTypes[​](#getlogtypes "Direct link to getLogTypes") Get available log types.<br /><br />Appium command. More details can be found in the [official protocol docs](https://www.selenium.dev/documentation/webdriver/troubleshooting/logging/).<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://www.selenium.dev/documentation/webdriver/troubleshooting/logging/). ### Usage[​](#usage-26 "Direct link to Usage") ``` await browser.getLogTypes() ``` ### Returns[​](#returns-14 "Direct link to Returns") * **\<String\[]>** **`logTypes`:** The list of available log types, example: browser, driver. *** ## getLogs[​](#getlogs "Direct link to getLogs") Get the log for a given log type. Log buffer is reset after each request.<br /><br />Appium command. More details can be found in the [official protocol docs](https://www.selenium.dev/documentation/webdriver/troubleshooting/logging/).<br /><br />Non official and undocumented Chromium command. More about this command can be found [here](https://www.selenium.dev/documentation/webdriver/troubleshooting/logging/). ### Usage[​](#usage-27 "Direct link to Usage") ``` await browser.getLogs(type) ``` ### Parameters[​](#parameters-14 "Direct link to Parameters") | Name | Type | Details | | ------ | -------- | ------------ | | `type` | `string` | the log type | ### Returns[​](#returns-15 "Direct link to Returns") * **\<Object\[]>** **`logs`:** The list of log entries. --- Source: https://webdriver.io/docs/api/gecko.md # Firefox ## fullPageScreenshot[​](#fullpagescreenshot "Direct link to fullPageScreenshot") Captures a screenshot of the entire page.<br /><br />Firefox command. More details can be found in the [official protocol docs](https://phabricator.services.mozilla.com/source/mozilla-central/browse/default/testing/geckodriver/src/command.rs$43-46). ### Usage[​](#usage "Direct link to Usage") ``` await browser.fullPageScreenshot() ``` ### Returns[​](#returns "Direct link to Returns") * **\<String>** **`screenshot`:** The base64-encoded PNG image data comprising the screenshot of the full page. *** ## getMozContext[​](#getmozcontext "Direct link to getMozContext") Get the context that is currently in effect, e.g. `CHROME` or `CONTENT`.<br /><br />Firefox command. More details can be found in the [official protocol docs](https://github.com/SeleniumHQ/selenium/blob/586affe0cf675b1d5c8abc756defa4a46d95391b/javascript/node/selenium-webdriver/firefox.js#L615-L622). ### Usage[​](#usage-1 "Direct link to Usage") ``` await browser.getMozContext() ``` ### Example[​](#example "Direct link to Example") ``` console.log(await browser.getMozContext()); // outputs: 'CHROME' ``` ### Returns[​](#returns-1 "Direct link to Returns") * **\<String>** **`Context`:** The browser context, either `CHROME` or `CONTENT` *** ## setMozContext[​](#setmozcontext "Direct link to setMozContext") Changes target context for commands between chrome- and content.<br /><br />Changing the current context has a stateful impact on all subsequent commands. The `CONTENT` context has normal web platform document permissions, as if you would evaluate arbitrary JavaScript. The `CHROME` context gets elevated permissions that lets you manipulate the browser chrome itself, with full access to the XUL toolkit.<br /><br />Firefox command. More details can be found in the [official protocol docs](https://github.com/SeleniumHQ/selenium/blob/586affe0cf675b1d5c8abc756defa4a46d95391b/javascript/node/selenium-webdriver/firefox.js#L615-L645). ### Usage[​](#usage-2 "Direct link to Usage") ``` await browser.setMozContext(context) ``` ### Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------- | -------- | ------------------------------------------------- | | `context` | `string` | The browser context, either `CHROME` or `CONTENT` | ### Example[​](#example-1 "Direct link to Example") ``` console.log(await browser.getMozContext()); // outputs: 'CHROME' browser.setMozContext('CONTENT'); console.log(await browser.getMozContext()); // outputs: 'CONTENT' ``` *** ## installAddOn[​](#installaddon "Direct link to installAddOn") Installs a new addon with the current session. This function will return an ID that may later be used to uninstall the addon using `uninstallAddon`.<br /><br />Firefox command. More details can be found in the [official protocol docs](https://github.com/SeleniumHQ/selenium/blob/586affe0cf675b1d5c8abc756defa4a46d95391b/javascript/node/selenium-webdriver/firefox.js#L647-L668). ### Usage[​](#usage-3 "Direct link to Usage") ``` await browser.installAddOn(addon, temporary) ``` ### Parameters[​](#parameters-1 "Direct link to Parameters") | Name | Type | Details | | ----------- | --------- | --------------------------------------------------------------------------------------------------------- | | `addon` | `string` | base64 string of the add on file | | `temporary` | `boolean` | temporary Flag indicating whether the extension should be installed temporarily - gets removed on restart | ### Example[​](#example-2 "Direct link to Example") ``` // Create a buffer of the add on .zip file const extension = await fs.promises.readFile('/path/to/extension.zip') // Load extension in Firefox const id = await browser.installAddOn(extension.toString('base64'), false); ``` ### Returns[​](#returns-2 "Direct link to Returns") * **\<String>** **`id`:** A promise that will resolve to an ID for the newly installed addon. *** ## uninstallAddOn[​](#uninstalladdon "Direct link to uninstallAddOn") Uninstalls an addon from the current browser session's profile.<br /><br />Firefox command. More details can be found in the [official protocol docs](https://github.com/SeleniumHQ/selenium/blob/586affe0cf675b1d5c8abc756defa4a46d95391b/javascript/node/selenium-webdriver/firefox.js#L670-L687). ### Usage[​](#usage-4 "Direct link to Usage") ``` await browser.uninstallAddOn(id) ``` ### Parameters[​](#parameters-2 "Direct link to Parameters") | Name | Type | Details | | ---- | -------- | -------------------------------- | | `id` | `string` | id ID of the addon to uninstall. | ### Example[​](#example-3 "Direct link to Example") ``` // Create a buffer of the add on .zip file const extension = await fs.promises.readFile('/path/to/extension.zip') // Load extension in Firefox const id = await browser.installAddOn(extension.toString('base64'), false); // ... await browser.uninstallAddOn(id) ``` --- Source: https://webdriver.io/docs/api/saucelabs.md # Sauce Labs All commands are only supported on Chrome using Sauce Labs [Extended Debugging](https://docs.saucelabs.com/insights/debug/#enabling-extended-debugging) capabilities. You can enable these by setting the following Sauce options: ``` { browserName: 'Chrome', browserVersion: 'latest', platformName: 'Windows 10', 'sauce:options': { extendedDebugging: true } } ``` *** ## getPageLogs[​](#getpagelogs "Direct link to getPageLogs") Get webpage specific log information based on the last page load.<br /><br />Sauce Labs command. More details can be found in the [official protocol docs](https://docs.saucelabs.com/insights/debug/#network-logs). ### Usage[​](#usage "Direct link to Usage") ``` await browser.getPageLogs(type) ``` ### Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------ | -------- | ----------------------------------------------------------------------------------- | | `type` | `string` | log type (e.g. sauce<!-- -->:network<!-- -->', 'sauce<!-- -->:performance<!-- -->') | ### Examples[​](#examples "Direct link to Examples") ``` // Get Network Logs console.log(browser.getPageLogs('sauce:network')); /** * outputs: * [{ * "url": "https://app.saucelabs.com/dashboard", * "statusCode": 200, * "method": "GET", * "requestHeaders": { * ... * }, * "responseHeaders": { * ... * }, * "timing": { * ... * } * }, {, * ... * }] */ ``` ``` // Get Performance Logs (needs capturePerformance capability see: https://docs.saucelabs.com/performance/transitions/#setting-performance-capabilities console.log(browser.getPageLogs('sauce:performance')); /** * outputs: * { * "speedIndex": 1472.023, * "timeToFirstInteractive": 1243.214, * "firstMeaningfulPaint": 892.643, * ... * } */ ``` ### Returns[​](#returns "Direct link to Returns") * **\<object>** **`log`:** log output of desired type (see example) *** ## sauceThrottleNetwork[​](#saucethrottlenetwork "Direct link to sauceThrottleNetwork") With network conditioning you can test your site on a variety of network connections, including Edge, 3G, and even offline. You can throttle the data throughput, including the maximum download and upload throughput, and use latency manipulation to enforce a minimum delay in connection round-trip time (RTT).<br /><br />Sauce Labs command. More details can be found in the [official protocol docs](https://docs.saucelabs.com/insights/debug/#saucethrottlenetwork). ### Usage[​](#usage-1 "Direct link to Usage") ``` await browser.sauceThrottleNetwork(condition) ``` ### Parameters[​](#parameters-1 "Direct link to Parameters") | Name | Type | Details | | ----------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | `condition` | `string, object` | network condition to set (e.g. 'online', 'offline', 'GPRS', 'Regular 2G', 'Good 2G', 'Regular 3G', 'Good 3G', 'Regular 4G', 'DSL', 'Wifi') | ### Examples[​](#examples-1 "Direct link to Examples") ``` // predefined network condition browser.sauceThrottleNetwork('offline') ``` ``` // custom network condition browser.sauceThrottleNetwork({ download: 1000, upload: 500, latency: 40' }) ``` *** ## throttleCPU[​](#throttlecpu "Direct link to throttleCPU") You can throttle the CPU in DevTools to understand how your page performs under that constraint.<br /><br />Sauce Labs command. More details can be found in the [official protocol docs](https://docs.saucelabs.com/insights/debug/#saucethrottlecpu). ### Usage[​](#usage-2 "Direct link to Usage") ``` await browser.throttleCPU(rate) ``` ### Parameters[​](#parameters-2 "Direct link to Parameters") | Name | Type | Details | | ------ | -------- | ---------------------------------------------- | | `rate` | `number` | Rate on how much the CPU should get throttled. | ### Examples[​](#examples-2 "Direct link to Examples") ``` // throttle CPU and make it run 4x slower browser.throttleCPU(4) ``` ``` // reset CPU throttling browser.throttleCPU(0) ``` *** ## interceptRequest[​](#interceptrequest "Direct link to interceptRequest") Allows modifying any request made by the browser. You can blacklist, modify, or redirect these as required for your tests.<br /><br />Sauce Labs command. More details can be found in the [official protocol docs](https://docs.saucelabs.com/insights/debug/#intercept-network-requests). ### Usage[​](#usage-3 "Direct link to Usage") ``` await browser.interceptRequest(rule) ``` ### Parameters[​](#parameters-3 "Direct link to Parameters") | Name | Type | Details | | ------ | -------- | ------------------------------------------- | | `rule` | `object` | A rule describing the request interception. | ### Examples[​](#examples-3 "Direct link to Examples") ``` // redirect a request browser.interceptRequest({ url: 'https://saucelabs.com', redirect: 'https://google.com' }) ``` ``` // Blacklist requests to 3rd party vendors browser.interceptRequest({ url: 'https://api.segment.io/v1/p', error: 'Failed' }) ``` ``` // Modify requests to REST API (Mock REST API response) browser.interceptRequest({ url: 'http://sampleapp.appspot.com/api/todos', response: { headers: { 'x-custom-headers': 'foobar' }, body: [{ title: 'My custom todo', order: 1, completed: false, url: 'http://todo-backend-express.herokuapp.com/15727' }] } }) ``` *** ## assertPerformance[​](#assertperformance "Direct link to assertPerformance") Assert against the performance baseline of your app.<br /><br />Sauce Labs command. More details can be found in the [official protocol docs](https://docs.saucelabs.com/performance/transitions/#setting-performance-capabilities). ### Usage[​](#usage-4 "Direct link to Usage") ``` await browser.assertPerformance(name, metrics) ``` ### Parameters[​](#parameters-4 "Direct link to Parameters") | Name | Type | Details | | ------------------------- | ---------- | -------------------------------------------------------- | | `name` | `string` | Name of the job you created your baseline with. | | `metrics`<br />*optional* | `string[]` | Name of metrics you want to assert against the baseline. | ### Example[​](#example "Direct link to Example") ``` // test performance for a page browser.url('https://webdriver.io') const hasRegression = browser.assertPerformance({ name: 'my performance test', // make sure that the name is also set in the sauce options in your capabilities metrics: ['score', 'firstPaint'] }) ``` ### Returns[​](#returns-1 "Direct link to Returns") * **\<object>** **`hasRegression`:** An object containing the result as well as metrics about the result. *** ## jankinessCheck[​](#jankinesscheck "Direct link to jankinessCheck") Perform a scroll test that evaluates the jankiness of the application.<br /><br />Sauce Labs command. More details can be found in the [official protocol docs](https://docs.saucelabs.com/performance/motion/#implementing-the-jankiness-custom-command). ### Usage[​](#usage-5 "Direct link to Usage") ``` await browser.jankinessCheck() ``` ### Example[​](#example-1 "Direct link to Example") ``` // test performance for a page browser.url('https://webdriver.io') browser.jankinessCheck() ``` ### Returns[​](#returns-2 "Direct link to Returns") * **\<object>** **`testResults`:** An object containing the score as well as metrics around how smooth the UX of the page was during the test. *** ## mockRequest[​](#mockrequest "Direct link to mockRequest") Mocks a network resource.<br /><br />Sauce Labs command. More details can be found in the [official protocol docs](https://docs.saucelabs.com/). ### Usage[​](#usage-6 "Direct link to Usage") ``` await browser.mockRequest(url, filterOptions) ``` ### Parameters[​](#parameters-5 "Direct link to Parameters") | Name | Type | Details | | ------------------------------- | -------- | ----------------------------------------------------------------- | | `url` | `string` | URL glob to match url to mock. | | `filterOptions`<br />*optional* | `object` | Additional filter options for url to mock (e.g. headers, method). | ### Returns[​](#returns-3 "Direct link to Returns") * **\<object>** **`mockId`:** An object containing the id of a mock resource. *** ## getMockCalls[​](#getmockcalls "Direct link to getMockCalls") Receive request information about requests that match the mocked resource.<br /><br />Sauce Labs command. More details can be found in the [official protocol docs](https://docs.saucelabs.com/). ### Usage[​](#usage-7 "Direct link to Usage") ``` await browser.getMockCalls(mockId) ``` ### Parameters[​](#parameters-6 "Direct link to Parameters") | Name | Type | Details | | -------- | -------- | ---------------- | | `mockId` | `String` | the id of a mock | ### Returns[​](#returns-4 "Direct link to Returns") * **\<object>** **`requests`:** A list of request information. *** ## clearMockCalls[​](#clearmockcalls "Direct link to clearMockCalls") Clear list of mock calls.<br /><br />Sauce Labs command. More details can be found in the [official protocol docs](https://docs.saucelabs.com/). ### Usage[​](#usage-8 "Direct link to Usage") ``` await browser.clearMockCalls(mockId, restore) ``` ### Parameters[​](#parameters-7 "Direct link to Parameters") | Name | Type | Details | | ------------------------- | --------- | ----------------------------------------------- | | `mockId` | `String` | the id of a mock | | `restore`<br />*optional* | `boolean` | Set to true if mock should be restored as well. | *** ## respondMock[​](#respondmock "Direct link to respondMock") Respond if mock matches a specific resource.<br /><br />Sauce Labs command. More details can be found in the [official protocol docs](https://docs.saucelabs.com/). ### Usage[​](#usage-9 "Direct link to Usage") ``` await browser.respondMock(mockId, payload) ``` ### Parameters[​](#parameters-8 "Direct link to Parameters") | Name | Type | Details | | ------------------------- | -------- | ----------------------------- | | `mockId` | `String` | the id of a mock | | `payload`<br />*optional* | `object` | Information on mock response. | --- Source: https://webdriver.io/docs/api/selenium.md # Selenium Standalone ## file[​](#file "Direct link to file") Upload a file to remote machine on which the browser is running.<br /><br />Selenium Standalone command. More details can be found in the [official protocol docs](https://www.seleniumhq.org/). ### Usage[​](#usage "Direct link to Usage") ``` await browser.file(file) ``` ### Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `file` | `string` | Base64-encoded zip archive containing **single** file which to upload. In case base64-encoded data does not represent a zip archive or archive contains more than one file it will throw an unknown error. | ### Returns[​](#returns "Direct link to Returns") * **\<String>** **`path`:** Absolute path of uploaded file on remote machine. *** ## getDownloadableFiles[​](#getdownloadablefiles "Direct link to getDownloadableFiles") List files from remote machine available for download.<br /><br />Selenium Standalone command. More details can be found in the [official protocol docs](https://www.seleniumhq.org/). ### Usage[​](#usage-1 "Direct link to Usage") ``` await browser.getDownloadableFiles() ``` ### Returns[​](#returns-1 "Direct link to Returns") * **\<Object>** **`names`:** Object containing a list of downloadable files on remote machine. *** ## download[​](#download "Direct link to download") Download a file from remote machine on which the browser is running.<br /><br />Selenium Standalone command. More details can be found in the [official protocol docs](https://www.seleniumhq.org/). ### Usage[​](#usage-2 "Direct link to Usage") ``` await browser.download(name) ``` ### Parameters[​](#parameters-1 "Direct link to Parameters") | Name | Type | Details | | ------ | -------- | --------------------------------- | | `name` | `string` | Name of the file to be downloaded | ### Returns[​](#returns-2 "Direct link to Returns") * **\<Object>** **`data`:** Object containing downloaded file name and its content *** ## deleteDownloadableFiles[​](#deletedownloadablefiles "Direct link to deleteDownloadableFiles") Remove all downloadable files from remote machine on which the browser is running.<br /><br />Selenium Standalone command. More details can be found in the [official protocol docs](https://www.seleniumhq.org/). ### Usage[​](#usage-3 "Direct link to Usage") ``` await browser.deleteDownloadableFiles() ``` *** ## getHubConfig[​](#gethubconfig "Direct link to getHubConfig") Receive hub config remotely.<br /><br />Selenium Standalone command. More details can be found in the [official protocol docs](https://github.com/nicegraham/selenium-grid2-api#gridapihub). ### Usage[​](#usage-4 "Direct link to Usage") ``` await browser.getHubConfig() ``` ### Returns[​](#returns-3 "Direct link to Returns") * **\<Object>** **`config`:** Returns the hub config with slotCount, timeouts and other information. *** ## gridTestSession[​](#gridtestsession "Direct link to gridTestSession") Get the details of the Selenium Grid node running a session.<br /><br />Selenium Standalone command. More details can be found in the [official protocol docs](https://github.com/nicegraham/selenium-grid2-api#gridapitestsession). ### Usage[​](#usage-5 "Direct link to Usage") ``` await browser.gridTestSession(session) ``` ### Parameters[​](#parameters-2 "Direct link to Parameters") | Name | Type | Details | | --------- | -------- | ------------------------------------------------- | | `session` | `String` | The id of the session to receive hub details for. | ### Returns[​](#returns-4 "Direct link to Returns") * **\<Object>** **`details`:** Object containing information about session details. *** ## gridProxyDetails[​](#gridproxydetails "Direct link to gridProxyDetails") Get proxy details.<br /><br />Selenium Standalone command. More details can be found in the [official protocol docs](https://github.com/nicegraham/selenium-grid2-api#gridapiproxy). ### Usage[​](#usage-6 "Direct link to Usage") ``` await browser.gridProxyDetails(id) ``` ### Parameters[​](#parameters-3 "Direct link to Parameters") | Name | Type | Details | | ---- | -------- | -------------------------------------------------------------------- | | `id` | `string` | the id of the proxy (can be received using gridTestSession command). | ### Returns[​](#returns-5 "Direct link to Returns") * **\<Object>** **`details`:** Object containing information about proxy. *** ## manageSeleniumHubLifecycle[​](#manageseleniumhublifecycle "Direct link to manageSeleniumHubLifecycle") Manage lifecycle of hub node.<br /><br />Selenium Standalone command. More details can be found in the [official protocol docs](https://github.com/nicegraham/selenium-grid2-api#lifecycle-manager). ### Usage[​](#usage-7 "Direct link to Usage") ``` await browser.manageSeleniumHubLifecycle(action) ``` ### Parameters[​](#parameters-4 "Direct link to Parameters") | Name | Type | Details | | -------- | -------- | -------------------------------------------------------------------------------------- | | `action` | `String` | Command to call on Selenium Hub. The only implemented action is to 'shutdown' the hub. | *** ## queryGrid[​](#querygrid "Direct link to queryGrid") Send GraphQL queries to the Selenium (hub or node) server to fetch data. (Only supported with Selenium v4 Server)<br /><br />Selenium Standalone command. More details can be found in the [official protocol docs](https://www.selenium.dev/documentation/grid/advanced_features/graphql_support/). ### Usage[​](#usage-8 "Direct link to Usage") ``` await browser.queryGrid(query) ``` ### Parameters[​](#parameters-5 "Direct link to Parameters") | Name | Type | Details | | ------- | -------- | ----------------------------------------- | | `query` | `string` | A GraphQL query to be send to the server. | ### Example[​](#example "Direct link to Example") ``` const result = await browser.queryGrid('{ nodesInfo { nodes { status, uri } } }'); console.log(JSON.stringify(result, null, 4)) /** * outputs: * { * "data": { * "nodesInfo": { * "nodes": [{ * "status": "UP", * "uri": "http://192.168.0.39:4444" * }] * } * } * } */ ``` ### Returns[​](#returns-6 "Direct link to Returns") * **\<Object>** **`data`:** Result of the GraphQL query. --- Source: https://webdriver.io/docs/api/webdriver.md # WebDriver Protocol ## newSession[​](#newsession "Direct link to newSession") The New Session command creates a new WebDriver session with the endpoint node. If the creation fails, a session not created error is returned.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-new-sessions). ### Usage[​](#usage "Direct link to Usage") ``` await browser.newSession(capabilities) ``` ### Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | -------------- | -------- | -------------------------------------------------------------------------------------------------------------------- | | `capabilities` | `object` | a JSON object, the set of capabilities that was ultimately merged and matched in the capability processing algorithm | ### Returns[​](#returns "Direct link to Returns") * **\<Object>** **`session`:** Object containing sessionId and capabilities of created WebDriver session. *** ## deleteSession[​](#deletesession "Direct link to deleteSession") The Delete Session command closes any top-level browsing contexts associated with the current session, terminates the connection, and finally closes the current session.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-delete-session). ### Usage[​](#usage-1 "Direct link to Usage") ``` await browser.deleteSession(deleteSessionOpts) ``` ### Parameters[​](#parameters-1 "Direct link to Parameters") | Name | Type | Details | | ----------------------------------- | -------- | ------------------------------------------------------------------------------------------- | | `deleteSessionOpts`<br />*optional* | `object` | Object containing options for the deleteSession command, e.g. `{ shutdownDriver: boolean }` | *** ## status[​](#status "Direct link to status") The Status command returns information about whether a remote end is in a state in which it can create new sessions and can additionally include arbitrary meta information that is specific to the implementation.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-status). ### Usage[​](#usage-2 "Direct link to Usage") ``` await browser.status() ``` ### Example[​](#example "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L5-L16 >) ### Returns[​](#returns-1 "Direct link to Returns") * **\<Object>** **`status`:** Object containing status of the driver status. *** ## getTimeouts[​](#gettimeouts "Direct link to getTimeouts") The Get Timeouts command gets timeout durations associated with the current session.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-get-timeouts). ### Usage[​](#usage-3 "Direct link to Usage") ``` await browser.getTimeouts() ``` ### Example[​](#example-1 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L20-L24 >) ### Returns[​](#returns-2 "Direct link to Returns") * **\<Object>** **`timeouts`:** Object containing timeout durations for `script`, `pageLoad` and `implicit` timeouts. *** ## setTimeouts[​](#settimeouts "Direct link to setTimeouts") The Set Timeouts command sets timeout durations associated with the current session. The timeouts that can be controlled are listed in the table of session timeouts below.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-set-timeouts). ### Usage[​](#usage-4 "Direct link to Usage") ``` await browser.setTimeouts(implicit, pageLoad, script) ``` ### Parameters[​](#parameters-2 "Direct link to Parameters") | Name | Type | Details | | -------------------------- | -------------- | ----------------------------------------------- | | `implicit`<br />*optional* | `number, null` | integer in ms for session implicit wait timeout | | `pageLoad`<br />*optional* | `number, null` | integer in ms for session page load timeout | | `script`<br />*optional* | `number, null` | integer in ms for session script timeout | ### Example[​](#example-2 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L28-L33 >) *** ## getUrl[​](#geturl "Direct link to getUrl") The Get Current URL command returns the URL of the current top-level browsing context.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-get-current-url). ### Usage[​](#usage-5 "Direct link to Usage") ``` await browser.getUrl() ``` ### Example[​](#example-3 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L39-L43 >) ### Returns[​](#returns-3 "Direct link to Returns") * **\<string>** **`url`:** current top-level browsing context’s active document’s document URL *** ## navigateTo[​](#navigateto "Direct link to navigateTo") The navigateTo (go) command is used to cause the user agent to navigate the current top-level browsing context a new location.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-navigate-to). info This protocol command is embedded in the following convenient method: [url](/docs/api/browser/url.md). It is recommended to use this command instead. ### Usage[​](#usage-6 "Direct link to Usage") ``` await browser.navigateTo(url) ``` ### Parameters[​](#parameters-3 "Direct link to Parameters") | Name | Type | Details | | ----- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | `url` | `string` | string representing an absolute URL (beginning with http(s)), possibly including a fragment (#...), could also be a local scheme (about: etc) | ### Example[​](#example-4 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L47-L51 >) *** ## back[​](#back "Direct link to back") The Back command causes the browser to traverse one step backward in the joint session history of the current top-level browsing context. This is equivalent to pressing the back button in the browser chrome or calling `window.history.back`. WebdriverIO's `browser.back()` uses this endpoint for a classic session. On a WebDriver BiDi session it calls `browsingContext.traverseHistory` with `{ context, delta: -1 }` on the top-level browsing context (a frame selected with `switchFrame` is not the target), then waits for the document readiness mapped from `pageLoadStrategy`: `none` does not wait, `eager` waits for `browsingContext.domContentLoaded`, and `normal` waits for `browsingContext.load`. The wait uses the session page-load timeout. A missing previous entry rejects with `no such history entry`.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-back). info This protocol command is embedded in the following convenient method: [back](/docs/api/browser/back.md). It is recommended to use this command instead. ### Usage[​](#usage-7 "Direct link to Usage") ``` await browser.back() ``` ### Example[​](#example-5 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L55-L59 >) *** ## forward[​](#forward "Direct link to forward") The Forward command causes the browser to traverse one step forwards in the joint session history of the current top-level browsing context. WebdriverIO's `browser.forward()` uses this endpoint for a classic session. On a WebDriver BiDi session it calls `browsingContext.traverseHistory` with `{ context, delta: 1 }` on the top-level browsing context (a frame selected with `switchFrame` is not the target), then waits for the document readiness mapped from `pageLoadStrategy`: `none` does not wait, `eager` waits for `browsingContext.domContentLoaded`, and `normal` waits for `browsingContext.load`. The wait uses the session page-load timeout. A missing next entry rejects with `no such history entry`.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-forward). info This protocol command is embedded in the following convenient method: [forward](/docs/api/browser/forward.md). It is recommended to use this command instead. ### Usage[​](#usage-8 "Direct link to Usage") ``` await browser.forward() ``` ### Example[​](#example-6 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L63-L69 >) *** ## refresh[​](#refresh "Direct link to refresh") The Refresh command causes the browser to reload the page in current top-level browsing context.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-refresh). ### Usage[​](#usage-9 "Direct link to Usage") ``` await browser.refresh() ``` ### Example[​](#example-7 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L73-L78 >) *** ## getTitle[​](#gettitle "Direct link to getTitle") The Get Title command returns the document title of the current top-level browsing context, equivalent to calling `document.title`.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-get-title). ### Usage[​](#usage-10 "Direct link to Usage") ``` await browser.getTitle() ``` ### Example[​](#example-8 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L82-L86 >) ### Returns[​](#returns-4 "Direct link to Returns") * **\<string>** **`title`:** Returns a string which is the same as `document.title` of the current top-level browsing context. *** ## getWindowHandle[​](#getwindowhandle "Direct link to getWindowHandle") The Get Window Handle command returns the window handle for the current top-level browsing context. It can be used as an argument to Switch To Window.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-get-window-handle). ### Usage[​](#usage-11 "Direct link to Usage") ``` await browser.getWindowHandle() ``` ### Example[​](#example-9 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L90-L93 >) ### Returns[​](#returns-5 "Direct link to Returns") * **\<string>** **`handle`:** Returns a string which is the window handle for the current top-level browsing context. *** ## closeWindow[​](#closewindow "Direct link to closeWindow") The Close Window command closes the current top-level browsing context. Once done, if there are no more top-level browsing contexts open, the WebDriver session itself is closed.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-close-window). ### Usage[​](#usage-12 "Direct link to Usage") ``` await browser.closeWindow() ``` ### Example[​](#example-10 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L97-L117 >) *** ## switchToWindow[​](#switchtowindow "Direct link to switchToWindow") The Switch To Window command is used to select the current top-level browsing context for the current session, i.e. the one that will be used for processing commands.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-switch-to-window). info This protocol command is embedded in the following convenient method: [switchWindow](/docs/api/browser/switchWindow.md). It is recommended to use this command instead. ### Usage[​](#usage-13 "Direct link to Usage") ``` await browser.switchToWindow(handle) ``` ### Parameters[​](#parameters-4 "Direct link to Parameters") | Name | Type | Details | | -------- | -------- | ------------------------------------------------------------------------------------------------------------------- | | `handle` | `string` | a string representing a window handle, should be one of the strings that was returned in a call to getWindowHandles | ### Example[​](#example-11 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L121-L130 >) *** ## createWindow[​](#createwindow "Direct link to createWindow") Create a new top-level browsing context.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#new-window). ### Usage[​](#usage-14 "Direct link to Usage") ``` await browser.createWindow(type) ``` ### Parameters[​](#parameters-5 "Direct link to Parameters") | Name | Type | Details | | ------ | -------- | ---------------------------------------------------------------------------------------------------------------------------- | | `type` | `string` | Set to 'tab' if the newly created window shares an OS-level window with the current browsing context, or 'window' otherwise. | ### Example[​](#example-12 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L134-L136 >) ### Returns[​](#returns-6 "Direct link to Returns") * **\<Object>** **`window`:** New window object containing 'handle' with the value of the handle and 'type' with the value of the created window type *** ## getWindowHandles[​](#getwindowhandles "Direct link to getWindowHandles") The Get Window Handles command returns a list of window handles for every open top-level browsing context. The order in which the window handles are returned is arbitrary.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-get-window-handles). ### Usage[​](#usage-15 "Direct link to Usage") ``` await browser.getWindowHandles() ``` ### Example[​](#example-13 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L140-L143 >) ### Returns[​](#returns-7 "Direct link to Returns") * **\<String\[]>** **`handles`:** An array which is a list of window handles. *** ## printPage[​](#printpage "Direct link to printPage") The Print Page command renders the current browsing context to a paginated PDF. This is the WebDriver Classic endpoint. `browser.savePDF` calls it when the session is not using WebDriver BiDi. **Note:** Chrome's Classic print endpoint was limited to [headless mode](https://webdriver.io/docs/capabilities/#run-browser-headless) ([crbug 753118](https://bugs.chromium.org/p/chromium/issues/detail?id=753118)). That limit is specific to this Classic command. Headed and headless Chrome, Edge, and Firefox print through WebDriver BiDi [`browsingContext.print`](https://w3c.github.io/webdriver-bidi/#command-browsingContext-print), which `browser.savePDF` uses on a BiDi session. Current Chrome can also complete this Classic command from a headed session; older Chrome may still require headless.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#print-page). ### Usage[​](#usage-16 "Direct link to Usage") ``` await browser.printPage(orientation, scale, background, width, height, top, bottom, left, right, shrinkToFit, pageRanges) ``` ### Parameters[​](#parameters-6 "Direct link to Parameters") | Name | Type | Details | | ----------------------------- | ------------------ | ---------------------------------------------------------------- | | `orientation`<br />*optional* | `string` | page orientation, `portrait` or `landscape`. Default: `portrait` | | `scale`<br />*optional* | `number` | page scale. Default: `1` | | `background`<br />*optional* | `boolean` | page background. Default: `false` | | `width`<br />*optional* | `number` | page width in cm. Default: `21.59` from page | | `height`<br />*optional* | `number` | page height in cm. Default: `27.94` from page | | `top`<br />*optional* | `number` | page margin in cm from top margin. Default: `1` | | `bottom`<br />*optional* | `number` | page margin in cm from bottom margin. Default: `1` | | `left`<br />*optional* | `number` | page margin in cm from left margin. Default: `1` | | `right`<br />*optional* | `number` | page margin in cm from right margin. Default: `1` | | `shrinkToFit`<br />*optional* | `boolean` | shrink pdf to fit in page. Default: `true` | | `pageRanges`<br />*optional* | `string, number[]` | page ranges. Default `[]` | ### Example[​](#example-14 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L150-L151 >) ### Returns[​](#returns-8 "Direct link to Returns") * **\<string>** **`pdf`:** The base64-encoded PDF representation of the paginated document. *** ## switchToParentFrame[​](#switchtoparentframe "Direct link to switchToParentFrame") The Switch to Parent Frame command sets the current browsing context for future commands to the parent of the current browsing context.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-switch-to-parent-frame). ### Usage[​](#usage-17 "Direct link to Usage") ``` await browser.switchToParentFrame() ``` ### Example[​](#example-15 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L172-L189 >) *** ## getWindowRect[​](#getwindowrect "Direct link to getWindowRect") The Get Window Rect command returns the size and position on the screen of the operating system window corresponding to the current top-level browsing context.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-get-window-rect). info This protocol command is embedded in the following convenient method: [getWindowSize](/docs/api/browser/getWindowSize.md). It is recommended to use this command instead. ### Usage[​](#usage-18 "Direct link to Usage") ``` await browser.getWindowRect() ``` ### Example[​](#example-16 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L193-L196 >) ### Returns[​](#returns-9 "Direct link to Returns") * **\<Object>** **`windowRect`:** A JSON representation of a "window rect" object. This has 4 properties: `x`, `y`, `width` and `height`. *** ## setWindowRect[​](#setwindowrect "Direct link to setWindowRect") The Set Window Rect command alters the size and the position of the operating system window corresponding to the current top-level browsing context.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-set-window-rect). info This protocol command is embedded in the following convenient method: [setWindowSize](/docs/api/browser/setWindowSize.md). It is recommended to use this command instead. ### Usage[​](#usage-19 "Direct link to Usage") ``` await browser.setWindowRect(x, y, width, height) ``` ### Parameters[​](#parameters-7 "Direct link to Parameters") | Name | Type | Details | | -------- | -------------- | ----------------------------------------------------------------------------------------------------- | | `x` | `number, null` | the screenX attribute of the window object | | `y` | `number, null` | the screenY attribute of the window object | | `width` | `number, null` | the width of the outer dimensions of the top-level browsing context, including browser chrome etc... | | `height` | `number, null` | the height of the outer dimensions of the top-level browsing context, including browser chrome etc... | ### Example[​](#example-17 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L200-L204 >) ### Returns[​](#returns-10 "Direct link to Returns") * **\<Object>** **`windowRect`:** A JSON representation of a "window rect" object based on the new window state. *** ## maximizeWindow[​](#maximizewindow "Direct link to maximizeWindow") The Maximize Window command invokes the window manager-specific "maximize" operation, if any, on the window containing the current top-level browsing context. This typically increases the window to the maximum available size without going full-screen.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-maximize-window). ### Usage[​](#usage-20 "Direct link to Usage") ``` await browser.maximizeWindow() ``` ### Example[​](#example-18 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L208-L212 >) ### Returns[​](#returns-11 "Direct link to Returns") * **\<Object>** **`windowRect`:** A JSON representation of a "window rect" object based on the new window state. *** ## minimizeWindow[​](#minimizewindow "Direct link to minimizeWindow") The Minimize Window command invokes the window manager-specific "minimize" operation, if any, on the window containing the current top-level browsing context. This typically hides the window in the system tray.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-minimize-window). ### Usage[​](#usage-21 "Direct link to Usage") ``` await browser.minimizeWindow() ``` ### Returns[​](#returns-12 "Direct link to Returns") * **\<Object>** **`windowRect`:** A JSON representation of a "window rect" object of the (new) current top-level browsing context. *** ## fullscreenWindow[​](#fullscreenwindow "Direct link to fullscreenWindow") The Fullscreen Window command invokes the window manager-specific “full screen” operation, if any, on the window containing the current top-level browsing context. This typically increases the window to the size of the physical display and can hide browser chrome elements such as toolbars.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-fullscreen-window). ### Usage[​](#usage-22 "Direct link to Usage") ``` await browser.fullscreenWindow() ``` ### Returns[​](#returns-13 "Direct link to Returns") * **\<Object>** **`windowRect`:** A JSON representation of a "window rect" object of the (new) current top-level browsing context. *** ## findElement[​](#findelement "Direct link to findElement") The Find Element command is used to find an element in the current browsing context that can be used for future commands. This command returns JSON representation of the element that can be passed to $ command to transform the reference to an extended WebdriverIO element.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-find-element). info This protocol command is embedded in the following convenient method: [$](/docs/api/browser/$.md). It is recommended to use this command instead. ### Usage[​](#usage-23 "Direct link to Usage") ``` await browser.findElement(using, value) ``` ### Parameters[​](#parameters-8 "Direct link to Parameters") | Name | Type | Details | | ------- | -------- | -------------------------------------------------------- | | `using` | `string` | a valid element location strategy | | `value` | `string` | the actual selector that will be used to find an element | ### Example[​](#example-19 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L226-L232 >) ### Returns[​](#returns-14 "Direct link to Returns") * **\<object>** **`element`:** A JSON representation of an element object, e.g. `{ 'element-6066-11e4-a52e-4f735466cecf': 'ELEMENT_1' }`. *** ## findElementFromShadowRoot[​](#findelementfromshadowroot "Direct link to findElementFromShadowRoot") The Find Element From Shadow Root command is used to find an element within the shadow root of an element that can be used for future commands. This command returns JSON representation of the element that can be passed to $ command to transform the reference to an extended WebdriverIO element.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#find-element-from-shadow-root). info This protocol command is embedded in the following convenient method: [shadow$](/docs/api/element/shadow$.md). It is recommended to use this command instead. ### Usage[​](#usage-24 "Direct link to Usage") ``` await browser.findElementFromShadowRoot(shadowId, using, value) ``` ### Parameters[​](#parameters-9 "Direct link to Parameters") | Name | Type | Details | | ---------- | -------- | -------------------------------------------------------- | | `shadowId` | `String` | element id of a shadow root element | | `using` | `string` | a valid element location strategy | | `value` | `string` | the actual selector that will be used to find an element | ### Example[​](#example-20 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L236-L248 >) ### Returns[​](#returns-15 "Direct link to Returns") * **\<object>** **`element`:** A JSON representation of an element shadow object, e.g. `{ 'element-6066-11e4-a52e-4f735466cecf': 'ELEMENT_1' }`. *** ## findElements[​](#findelements "Direct link to findElements") The Find Elements command is used to find elements in the current browsing context that can be used for future commands. This command returns array of JSON representation of the elements that can be passed to $ command to transform the reference to an extended WebdriverIO element (See findElement).<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-find-elements). info This protocol command is embedded in the following convenient method: [$$](/docs/api/browser/$$.md). It is recommended to use this command instead. ### Usage[​](#usage-25 "Direct link to Usage") ``` await browser.findElements(using, value) ``` ### Parameters[​](#parameters-10 "Direct link to Parameters") | Name | Type | Details | | ------- | -------- | -------------------------------------------------------- | | `using` | `string` | a valid element location strategy | | `value` | `string` | the actual selector that will be used to find an element | ### Example[​](#example-21 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L252-L254 >) ### Returns[​](#returns-16 "Direct link to Returns") * **\<object\[]>** **`elements`:** A (possibly empty) JSON list of representations of an element object, e.g. `[{ 'element-6066-11e4-a52e-4f735466cecf': 'ELEMENT_1' }]`. *** ## findElementsFromShadowRoot[​](#findelementsfromshadowroot "Direct link to findElementsFromShadowRoot") The Find Elements command is used to find elements within the shadow root of an element that can be used for future commands. This command returns array of JSON representation of the elements that can be passed to $ command to transform the reference to an extended WebdriverIO element (See findElement).<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#find-elements-from-shadow-root). info This protocol command is embedded in the following convenient method: [shadow$$](/docs/api/element/shadow$$.md). It is recommended to use this command instead. ### Usage[​](#usage-26 "Direct link to Usage") ``` await browser.findElementsFromShadowRoot(shadowId, using, value) ``` ### Parameters[​](#parameters-11 "Direct link to Parameters") | Name | Type | Details | | ---------- | -------- | -------------------------------------------------------- | | `shadowId` | `String` | element id of a shadow root element | | `using` | `string` | a valid element location strategy | | `value` | `string` | the actual selector that will be used to find an element | ### Example[​](#example-22 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L258-L268 >) ### Returns[​](#returns-17 "Direct link to Returns") * **\<object\[]>** **`elements`:** A (possibly empty) JSON list of representations of an element object, e.g. `{ 'element-6066-11e4-a52e-4f735466cecf': 'ELEMENT_1' }`. *** ## findElementFromElement[​](#findelementfromelement "Direct link to findElementFromElement") The Find Element From Element command is used to find an element from a web element in the current browsing context that can be used for future commands. This command returns JSON representation of the element that can be passed to $ command to transform the reference to an extended WebdriverIO element (See findElement).<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-find-element-from-element). info This protocol command is embedded in the following convenient method: [$](/docs/api/element/$.md). It is recommended to use this command instead. ### Usage[​](#usage-27 "Direct link to Usage") ``` await browser.findElementFromElement(elementId, using, value) ``` ### Parameters[​](#parameters-12 "Direct link to Parameters") | Name | Type | Details | | ----------- | -------- | ------------------------------------------------------------------- | | `elementId` | `String` | the id of an element returned in a previous call to Find Element(s) | | `using` | `string` | a valid element location strategy | | `value` | `string` | the actual selector that will be used to find an element | ### Example[​](#example-23 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L272-L279 >) ### Returns[​](#returns-18 "Direct link to Returns") * **\<object>** **`element`:** A JSON representation of an element object, e.g. `{ 'element-6066-11e4-a52e-4f735466cecf': 'ELEMENT_1' }`. *** ## findElementsFromElement[​](#findelementsfromelement "Direct link to findElementsFromElement") The Find Elements From Element command is used to find elements from a web element in the current browsing context that can be used for future commands. This command returns array of JSON representation of the elements that can be passed to $ command to transform the reference to an extended WebdriverIO element (See findElement).<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-find-elements-from-element). info This protocol command is embedded in the following convenient method: [$$](/docs/api/element/$$.md). It is recommended to use this command instead. ### Usage[​](#usage-28 "Direct link to Usage") ``` await browser.findElementsFromElement(elementId, using, value) ``` ### Parameters[​](#parameters-13 "Direct link to Parameters") | Name | Type | Details | | ----------- | -------- | ------------------------------------------------------------------- | | `elementId` | `String` | the id of an element returned in a previous call to Find Element(s) | | `using` | `string` | a valid element location strategy | | `value` | `string` | the actual selector that will be used to find an element | ### Example[​](#example-24 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L283-L290 >) ### Returns[​](#returns-19 "Direct link to Returns") * **\<object\[]>** **`elements`:** A (possibly empty) JSON list of representations of an element object, e.g. `[{ 'element-6066-11e4-a52e-4f735466cecf': 'ELEMENT_1' }]`. *** ## getElementShadowRoot[​](#getelementshadowroot "Direct link to getElementShadowRoot") Get the shadow root object of an element. The result object can be used to fetch elements within this shadow root using e.g. findElementFromShadowRoots or findElementsFromShadowRoots.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#get-element-shadow-root). info This protocol command is embedded in the following convenient method: [shadow$](/docs/api/element/shadow$.md). It is recommended to use this command instead. ### Usage[​](#usage-29 "Direct link to Usage") ``` await browser.getElementShadowRoot(elementId) ``` ### Parameters[​](#parameters-14 "Direct link to Parameters") | Name | Type | Details | | ----------- | -------- | ------------------------------------------------------------------- | | `elementId` | `String` | the id of an element returned in a previous call to Find Element(s) | ### Example[​](#example-25 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L294-L305 >) ### Returns[​](#returns-20 "Direct link to Returns") * **\<object>** **`shadowRoot`:** A JSON representation of an element shadow root, e.g. `{ 'shadow-6066-11e4-a52e-4f735466cecf': 'ELEMENT_1' }`. *** ## getActiveElement[​](#getactiveelement "Direct link to getActiveElement") Get Active Element returns the active element of the current browsing context’s document element. This command returns JSON representation of the element that can be passed to $ command to transform the reference to an extended WebdriverIO element (See findElement).<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-get-active-element). ### Usage[​](#usage-30 "Direct link to Usage") ``` await browser.getActiveElement() ``` ### Example[​](#example-26 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L309-L316 >) ### Returns[​](#returns-21 "Direct link to Returns") * **\<object>** **`element`:** A JSON representation of an element object, e.g. `{ 'element-6066-11e4-a52e-4f735466cecf': 'ELEMENT_1' }`. *** ## isElementSelected[​](#iselementselected "Direct link to isElementSelected") Is Element Selected determines if the referenced element is selected or not. This operation only makes sense on input elements of the Checkbox- and Radio Button states, or option elements.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-is-element-selected). info This protocol command is embedded in the following convenient method: [isSelected](/docs/api/element/isSelected.md). It is recommended to use this command instead. ### Usage[​](#usage-31 "Direct link to Usage") ``` await browser.isElementSelected(elementId) ``` ### Parameters[​](#parameters-15 "Direct link to Parameters") | Name | Type | Details | | ----------- | -------- | ------------------------------------------------------------------- | | `elementId` | `String` | the id of an element returned in a previous call to Find Element(s) | ### Example[​](#example-27 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L322-L325 >) ### Returns[​](#returns-22 "Direct link to Returns") * **\<Boolean>** **`isSelected`:** `true` or `false` based on the selected state. *** ## isElementDisplayed[​](#iselementdisplayed "Direct link to isElementDisplayed") Is Element Displayed determines the visibility of an element which is guided by what is perceptually visible to the human eye. In this context, an element's displayedness does not relate to the `visibility` or `display` style properties.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#element-displayedness). info This protocol command is embedded in the following convenient method: [isDisplayed](/docs/api/element/isDisplayed.md). It is recommended to use this command instead. ### Usage[​](#usage-32 "Direct link to Usage") ``` await browser.isElementDisplayed(elementId) ``` ### Parameters[​](#parameters-16 "Direct link to Parameters") | Name | Type | Details | | ----------- | -------- | ------------------------------------------------------------------- | | `elementId` | `String` | the id of an element returned in a previous call to Find Element(s) | ### Example[​](#example-28 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L331-L333 >) ### Returns[​](#returns-23 "Direct link to Returns") * **\<Boolean>** **`isDisplayed`:** `true` or `false` based on the visible state. *** ## getElementAttribute[​](#getelementattribute "Direct link to getElementAttribute") The Get Element Attribute command will return the attribute of a web element.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-get-element-attribute). info This protocol command is embedded in the following convenient method: [getAttribute](/docs/api/element/getAttribute.md). It is recommended to use this command instead. ### Usage[​](#usage-33 "Direct link to Usage") ``` await browser.getElementAttribute(elementId, name) ``` ### Parameters[​](#parameters-17 "Direct link to Parameters") | Name | Type | Details | | ----------- | -------- | ------------------------------------------------------------------- | | `elementId` | `String` | the id of an element returned in a previous call to Find Element(s) | | `name` | `String` | name of the attribute value to retrieve | ### Example[​](#example-29 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L339-L341 >) ### Returns[​](#returns-24 "Direct link to Returns") * **<(string|null)>** **`attribute`:** The named attribute of the element. *** ## getElementProperty[​](#getelementproperty "Direct link to getElementProperty") The Get Element Property command will return the result of getting a property of an element.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-get-element-property). info This protocol command is embedded in the following convenient method: [getProperty](/docs/api/element/getProperty.md). It is recommended to use this command instead. ### Usage[​](#usage-34 "Direct link to Usage") ``` await browser.getElementProperty(elementId, name) ``` ### Parameters[​](#parameters-18 "Direct link to Parameters") | Name | Type | Details | | ----------- | -------- | ------------------------------------------------------------------- | | `elementId` | `String` | the id of an element returned in a previous call to Find Element(s) | | `name` | `String` | name of the attribute property to retrieve | ### Example[​](#example-30 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L347-L349 >) ### Returns[​](#returns-25 "Direct link to Returns") * **\<unknown>** **`property`:** The value of the named own property of the element. *** ## getElementCSSValue[​](#getelementcssvalue "Direct link to getElementCSSValue") The Get Element CSS Value command retrieves the computed value of the given CSS property of the given web element.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-get-element-css-value). info This protocol command is embedded in the following convenient method: [getCSSProperty](/docs/api/element/getCSSProperty.md). It is recommended to use this command instead. ### Usage[​](#usage-35 "Direct link to Usage") ``` await browser.getElementCSSValue(elementId, propertyName) ``` ### Parameters[​](#parameters-19 "Direct link to Parameters") | Name | Type | Details | | -------------- | -------- | ------------------------------------------------------------------- | | `elementId` | `String` | the id of an element returned in a previous call to Find Element(s) | | `propertyName` | `String` | name of the CSS property to retrieve | ### Example[​](#example-31 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L355-L357 >) ### Returns[​](#returns-26 "Direct link to Returns") * **\<string>** **`cssValue`:** The computed value of the parameter corresponding to property name from the element's style declarations (unless the document type is xml, in which case the return value is simply the empty string). *** ## getElementText[​](#getelementtext "Direct link to getElementText") The Get Element Text command intends to return an element’s text "as rendered". An element's rendered text is also used for locating a elements by their link text and partial link text.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-get-element-text). ### Usage[​](#usage-36 "Direct link to Usage") ``` await browser.getElementText(elementId) ``` ### Parameters[​](#parameters-20 "Direct link to Parameters") | Name | Type | Details | | ----------- | -------- | ------------------------------------------------------------------- | | `elementId` | `String` | the id of an element returned in a previous call to Find Element(s) | ### Example[​](#example-32 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L363-L365 >) ### Returns[​](#returns-27 "Direct link to Returns") * **\<string>** **`text`:** The visible text of the element (including child elements), following the algorithm defined in the Selenium Atoms for [`bot.dom.getVisibleText`](https://github.com/SeleniumHQ/selenium/blob/e09e28f016c9f53196cf68d6f71991c5af4a35d4/javascript/atoms/dom.js#L981). *** ## getElementTagName[​](#getelementtagname "Direct link to getElementTagName") The Get Element Tag Name command returns the qualified element name of the given web element.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-get-element-tag-name). info This protocol command is embedded in the following convenient method: [getTagName](/docs/api/element/getTagName.md). It is recommended to use this command instead. ### Usage[​](#usage-37 "Direct link to Usage") ``` await browser.getElementTagName(elementId) ``` ### Parameters[​](#parameters-21 "Direct link to Parameters") | Name | Type | Details | | ----------- | -------- | ------------------------------------------------------------------- | | `elementId` | `String` | the id of an element returned in a previous call to Find Element(s) | ### Example[​](#example-33 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L371-L373 >) ### Returns[​](#returns-28 "Direct link to Returns") * **\<string>** **`text`:** The tagName attribute of the element. *** ## getElementRect[​](#getelementrect "Direct link to getElementRect") The Get Element Rect command returns the dimensions and coordinates of the given web element.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-get-element-rect). info This protocol command is embedded in the following convenient methods: [getSize](/docs/api/element/getSize.md), [getLocation](/docs/api/element/getLocation.md). It is recommended to use these commands instead. ### Usage[​](#usage-38 "Direct link to Usage") ``` await browser.getElementRect(elementId) ``` ### Parameters[​](#parameters-22 "Direct link to Parameters") | Name | Type | Details | | ----------- | -------- | ------------------------------------------------------------------- | | `elementId` | `String` | the id of an element returned in a previous call to Find Element(s) | ### Example[​](#example-34 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L379-L381 >) ### Returns[​](#returns-29 "Direct link to Returns") * **\<Object>** **`elementRect`:** A JSON object representing the position and bounding rect of the element. *** ## isElementEnabled[​](#iselementenabled "Direct link to isElementEnabled") Is Element Enabled determines if the referenced element is enabled or not. This operation only makes sense on form controls.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-is-element-enabled). info This protocol command is embedded in the following convenient method: [isEnabled](/docs/api/element/isEnabled.md). It is recommended to use this command instead. ### Usage[​](#usage-39 "Direct link to Usage") ``` await browser.isElementEnabled(elementId) ``` ### Parameters[​](#parameters-23 "Direct link to Parameters") | Name | Type | Details | | ----------- | -------- | ------------------------------------------------------------------- | | `elementId` | `String` | the id of an element returned in a previous call to Find Element(s) | ### Example[​](#example-35 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L387-L390 >) ### Returns[​](#returns-30 "Direct link to Returns") * **\<Boolean>** **`isEnabled`:** If the element is in an xml document, or is a disabled form control: `false`, otherwise, `true`. *** ## elementClick[​](#elementclick "Direct link to elementClick") The Element Click command scrolls into view the element if it is not already pointer-interactable, and clicks its in-view center point. If the element's center point is obscured by another element, an element click intercepted error is returned. If the element is outside the viewport, an element not interactable error is returned.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-element-click). info This protocol command is embedded in the following convenient method: [click](/docs/api/element/click.md). It is recommended to use this command instead. ### Usage[​](#usage-40 "Direct link to Usage") ``` await browser.elementClick(elementId) ``` ### Parameters[​](#parameters-24 "Direct link to Parameters") | Name | Type | Details | | ----------- | -------- | ------------------------------------------------------------------- | | `elementId` | `String` | the id of an element returned in a previous call to Find Element(s) | ### Example[​](#example-36 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L396-L398 >) *** ## elementClear[​](#elementclear "Direct link to elementClear") The Element Clear command scrolls into view an editable or resettable element and then attempts to clear its selected files or text content.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-element-clear). info This protocol command is embedded in the following convenient method: [clearValue](/docs/api/element/clearValue.md). It is recommended to use this command instead. ### Usage[​](#usage-41 "Direct link to Usage") ``` await browser.elementClear(elementId) ``` ### Parameters[​](#parameters-25 "Direct link to Parameters") | Name | Type | Details | | ----------- | -------- | ------------------------------------------------------------------- | | `elementId` | `String` | the id of an element returned in a previous call to Find Element(s) | ### Example[​](#example-37 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L404-L407 >) *** ## elementSendKeys[​](#elementsendkeys "Direct link to elementSendKeys") The Element Send Keys command scrolls into view the form control element and then sends the provided keys to the element. In case the element is not keyboard-interactable, an element not interactable error is returned.<br /><br />The key input state used for input may be cleared mid-way through "typing" by sending the null key, which is U+E000 (NULL).<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-element-send-keys). info This protocol command is embedded in the following convenient methods: [addValue](/docs/api/element/addValue.md), [setValue](/docs/api/element/setValue.md). It is recommended to use these commands instead. ### Usage[​](#usage-42 "Direct link to Usage") ``` await browser.elementSendKeys(elementId, text) ``` ### Parameters[​](#parameters-26 "Direct link to Parameters") | Name | Type | Details | | ----------- | -------- | ------------------------------------------------------------------- | | `elementId` | `String` | the id of an element returned in a previous call to Find Element(s) | | `text` | `string` | string to send as keystrokes to the element | ### Example[​](#example-38 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L413-L416 >) *** ## getPageSource[​](#getpagesource "Direct link to getPageSource") The Get Page Source command returns a string serialization of the DOM of the current browsing context active document.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-get-page-source). ### Usage[​](#usage-43 "Direct link to Usage") ``` await browser.getPageSource() ``` ### Example[​](#example-39 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L420-L421 >) ### Returns[​](#returns-31 "Direct link to Returns") * **\<string>** **`pageSource`:** the DOM of the current browsing context active document *** ## executeScript[​](#executescript "Direct link to executeScript") The Execute Script command executes a JavaScript function in the context of the current browsing context and returns the return value of the function.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-execute-script). info This protocol command is embedded in the following convenient method: [execute](/docs/api/browser/execute.md). It is recommended to use this command instead. ### Usage[​](#usage-44 "Direct link to Usage") ``` await browser.executeScript(script, args) ``` ### Parameters[​](#parameters-27 "Direct link to Parameters") | Name | Type | Details | | -------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------- | | `script` | `string` | a string, the Javascript function body you want executed | | `args` | `string, object, number, boolean, null, undefined[]` | an array of JSON values which will be deserialized and passed as arguments to your function | ### Example[​](#example-40 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L425-L426 >) ### Returns[​](#returns-32 "Direct link to Returns") * **<\*>** **`result`:** Either the return value of your script, the fulfillment of the Promise returned by your script, or the error which was the reason for your script's returned Promise's rejection. *** ## executeAsyncScript[​](#executeasyncscript "Direct link to executeAsyncScript") The Execute Async Script command causes JavaScript to execute as an anonymous function. Unlike the Execute Script command, the result of the function is ignored. Instead an additional argument is provided as the final argument to the function. This is a function that, when called, returns its first argument as the response.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-execute-async-script). info This protocol command is embedded in the following convenient method: [execute](/docs/api/browser/execute.md). It is recommended to use this command instead. ### Usage[​](#usage-45 "Direct link to Usage") ``` await browser.executeAsyncScript(script, args) ``` ### Parameters[​](#parameters-28 "Direct link to Parameters") | Name | Type | Details | | -------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------- | | `script` | `string` | a string, the Javascript function body you want executed | | `args` | `string, object, number, boolean, null, undefined[]` | an array of JSON values which will be deserialized and passed as arguments to your function | ### Example[​](#example-41 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L430-L434 >) ### Returns[​](#returns-33 "Direct link to Returns") * **<\*>** **`result`:** Either the return value of your script, the fulfillment of the Promise returned by your script, or the error which was the reason for your script's returned Promise's rejection. *** ## getAllCookies[​](#getallcookies "Direct link to getAllCookies") The Get All Cookies command returns all cookies associated with the address of the current browsing context’s active document.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-get-all-cookies). ### Usage[​](#usage-46 "Direct link to Usage") ``` await browser.getAllCookies() ``` ### Example[​](#example-42 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L438-L455 >) ### Returns[​](#returns-34 "Direct link to Returns") * **\<Object\[]>** **`cookies`:** A list of serialized cookies. Each serialized cookie has a number of optional fields which may or may not be returned in addition to `name` and `value`. *** ## addCookie[​](#addcookie "Direct link to addCookie") The Add Cookie command adds a single cookie to the cookie store associated with the active document's address.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-adding-a-cookie). ### Usage[​](#usage-47 "Direct link to Usage") ``` await browser.addCookie(cookie) ``` ### Parameters[​](#parameters-29 "Direct link to Parameters") | Name | Type | Details | | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | `cookie` | `object` | A JSON object representing a cookie. It must have at least the name and value fields and could have more, including expiry-time and so on | ### Example[​](#example-43 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L459-L477 >) *** ## deleteAllCookies[​](#deleteallcookies "Direct link to deleteAllCookies") The Delete All Cookies command allows deletion of all cookies associated with the active document's address.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-delete-all-cookies). ### Usage[​](#usage-48 "Direct link to Usage") ``` await browser.deleteAllCookies() ``` ### Example[​](#example-44 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L481-L485 >) *** ## getNamedCookie[​](#getnamedcookie "Direct link to getNamedCookie") The Get Named Cookie command returns the cookie with the requested name from the associated cookies in the cookie store of the current browsing context's active document. If no cookie is found, a no such cookie error is returned.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-get-named-cookie). ### Usage[​](#usage-49 "Direct link to Usage") ``` await browser.getNamedCookie(name) ``` ### Parameters[​](#parameters-30 "Direct link to Parameters") | Name | Type | Details | | ------ | -------- | ------------------------------ | | `name` | `String` | name of the cookie to retrieve | ### Example[​](#example-45 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L489-L503 >) ### Returns[​](#returns-35 "Direct link to Returns") * **\<Object>** **`cookie`:** A serialized cookie, with name and value fields. There are a number of optional fields like `path`, `domain`, and `expiry-time` which may also be present. *** ## deleteCookie[​](#deletecookie "Direct link to deleteCookie") The Delete Cookie command allows you to delete either a single cookie by parameter name, or all the cookies associated with the active document's address if name is undefined.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-delete-cookie). ### Usage[​](#usage-50 "Direct link to Usage") ``` await browser.deleteCookie(name) ``` ### Parameters[​](#parameters-31 "Direct link to Parameters") | Name | Type | Details | | ------ | -------- | ---------------------------- | | `name` | `String` | name of the cookie to delete | ### Example[​](#example-46 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L507-L512 >) *** ## performActions[​](#performactions "Direct link to performActions") The Perform Actions command is used to execute complex user actions. Most users should prefer the higher-level [`browser.action()`](https://webdriver.io/docs/api/browser/action) API. See [spec](https://github.com/jlipps/simple-wd-spec#perform-actions) for more details.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-perform-actions). ### Usage[​](#usage-51 "Direct link to Usage") ``` await browser.performActions(actions) ``` ### Parameters[​](#parameters-32 "Direct link to Parameters") | Name | Type | Details | | --------- | ---------- | -------------------------------------------------------------------------------------- | | `actions` | `object[]` | a list of objects, each of which represents an input source and its associated actions | *** ## releaseActions[​](#releaseactions "Direct link to releaseActions") The Release Actions command is used to release all the keys and pointer buttons that are currently depressed. This causes events to be fired as if the state was released by an explicit series of actions. It also clears all the internal state of the virtual devices.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-release-actions). ### Usage[​](#usage-52 "Direct link to Usage") ``` await browser.releaseActions() ``` *** ## dismissAlert[​](#dismissalert "Direct link to dismissAlert") The Dismiss Alert command dismisses a simple dialog if present, otherwise error. A request to dismiss an alert user prompt, which may not necessarily have a dismiss button, has the same effect as accepting it.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-dismiss-alert). ### Usage[​](#usage-53 "Direct link to Usage") ``` await browser.dismissAlert() ``` ### Example[​](#example-47 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L516-L517 >) *** ## acceptAlert[​](#acceptalert "Direct link to acceptAlert") The Accept Alert command accepts a simple dialog if present, otherwise error.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-accept-alert). ### Usage[​](#usage-54 "Direct link to Usage") ``` await browser.acceptAlert() ``` *** ## getAlertText[​](#getalerttext "Direct link to getAlertText") The Get Alert Text command returns the message of the current user prompt. If there is no current user prompt, it returns an error.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-get-alert-text). ### Usage[​](#usage-55 "Direct link to Usage") ``` await browser.getAlertText() ``` ### Example[​](#example-48 "Direct link to Example") examples.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/api/webdriver/examples.js#L521-L522 >) ### Returns[​](#returns-36 "Direct link to Returns") * **\<string>** **`alertText`:** The message of the user prompt. *** ## sendAlertText[​](#sendalerttext "Direct link to sendAlertText") The Send Alert Text command sets the text field of a window\.prompt user prompt to the given value.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-send-alert-text). ### Usage[​](#usage-56 "Direct link to Usage") ``` await browser.sendAlertText(text) ``` ### Parameters[​](#parameters-33 "Direct link to Parameters") | Name | Type | Details | | ------ | -------- | --------------------------- | | `text` | `string` | string to set the prompt to | *** ## takeScreenshot[​](#takescreenshot "Direct link to takeScreenshot") The Take Screenshot command takes a screenshot of the top-level browsing context's viewport.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-take-screenshot). ### Usage[​](#usage-57 "Direct link to Usage") ``` await browser.takeScreenshot() ``` ### Returns[​](#returns-37 "Direct link to Returns") * **\<string>** **`screenshot`:** The base64-encoded PNG image data comprising the screenshot of the initial viewport. *** ## takeElementScreenshot[​](#takeelementscreenshot "Direct link to takeElementScreenshot") The Take Element Screenshot command takes a screenshot of the visible region encompassed by the bounding rectangle of an element.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#dfn-take-element-screenshot). ### Usage[​](#usage-58 "Direct link to Usage") ``` await browser.takeElementScreenshot(elementId) ``` ### Parameters[​](#parameters-34 "Direct link to Parameters") | Name | Type | Details | | ----------- | -------- | ------------------------------------------------------------------- | | `elementId` | `String` | the id of an element returned in a previous call to Find Element(s) | ### Returns[​](#returns-38 "Direct link to Returns") * **\<string>** **`screenshot`:** The base64-encoded PNG image data comprising the screenshot of the visible region of an element’s bounding rectangle after it has been scrolled into view. *** ## getElementComputedRole[​](#getelementcomputedrole "Direct link to getElementComputedRole") Get the computed WAI-ARIA role of an element.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#get-computed-role). ### Usage[​](#usage-59 "Direct link to Usage") ``` await browser.getElementComputedRole(elementId) ``` ### Parameters[​](#parameters-35 "Direct link to Parameters") | Name | Type | Details | | ----------- | -------- | ------------------------------------------------------------------- | | `elementId` | `String` | the id of an element returned in a previous call to Find Element(s) | ### Returns[​](#returns-39 "Direct link to Returns") * **\<string>** **`role`:** The result of computing the WAI-ARIA role of element. *** ## getElementComputedLabel[​](#getelementcomputedlabel "Direct link to getElementComputedLabel") Get the accessible name of the element.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver/#get-computed-label). ### Usage[​](#usage-60 "Direct link to Usage") ``` await browser.getElementComputedLabel(elementId) ``` ### Parameters[​](#parameters-36 "Direct link to Parameters") | Name | Type | Details | | ----------- | -------- | ------------------------------------------------------------------- | | `elementId` | `String` | the id of an element returned in a previous call to Find Element(s) | ### Returns[​](#returns-40 "Direct link to Returns") * **\<string>** **`label`:** The result of a Accessible Name and Description Computation for the Accessible Name of the element. *** ## setPermissions[​](#setpermissions "Direct link to setPermissions") Simulates user modification of a PermissionDescriptor's permission state. **Note:** this feature has not landed in all browsers yet.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/permissions/#set-permission-command). ### Usage[​](#usage-61 "Direct link to Usage") ``` await browser.setPermissions(descriptor, state, oneRealm) ``` ### Parameters[​](#parameters-37 "Direct link to Parameters") | Name | Type | Details | | -------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `descriptor` | `object` | Each powerful feature has one or more aspects that websites can request permission to access. To describe these aspects, each feature defines a subtype of PermissionDescriptor to be its permission descriptor type. **Note:** this feature has not landed in all browsers yet. | | `state` | `string` | Determines whether permission is granted, denied or prompted. | | `oneRealm`<br />*optional* | `boolean` | Whether or not to apply permissions to all execution contexts. | ### Examples[​](#examples "Direct link to Examples") ``` // set midi permissions browser.setPermissions( { name: 'midi', sysex: true }, 'granted' // can be also "denied" or "prompt" ); ``` ``` // set clipboard permissions browser.setPermissions({ name: 'clipboard-read' }, 'granted'); // now you can read the clipboard via, e.g. const clipboardText = await browser.execute(() => navigator.clipboard.readText()); ``` *** ## generateTestReport[​](#generatetestreport "Direct link to generateTestReport") Generates a report for testing. Extension for [Reporting API](https://developers.google.com/web/updates/2018/09/reportingapi). **Note:** this feature has not landed in all browsers yet.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/reporting/#automation). ### Usage[​](#usage-62 "Direct link to Usage") ``` await browser.generateTestReport(message, group) ``` ### Parameters[​](#parameters-38 "Direct link to Parameters") | Name | Type | Details | | ----------------------- | -------- | ------------------------------------------------------ | | `message` | `string` | Message to be displayed in the report. | | `group`<br />*optional* | `string` | Specifies the endpoint group to deliver the report to. | *** ## createMockSensor[​](#createmocksensor "Direct link to createMockSensor") Creates a mock sensor to emulate sensors like Ambient Light Sensor. **Note:** this feature has not landed in all browsers yet.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/sensors/#create-mock-sensor-command). ### Usage[​](#usage-63 "Direct link to Usage") ``` await browser.createMockSensor(type, connected, maxSamplingFrequency, minSamplingFrequency) ``` ### Parameters[​](#parameters-39 "Direct link to Parameters") | Name | Type | Details | | -------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------ | | `type` | `string` | Type of sensor API to mock, e.g. 'ambient-light' | | `connected`<br />*optional* | `boolean` | A flag indicating whether the mock sensor is connected. | | `maxSamplingFrequency`<br />*optional* | `number` | A double representing frequency in Hz that is used to set maximum supported sampling frequency for the associated mock sensor. | | `minSamplingFrequency`<br />*optional* | `number` | A double representing frequency in Hz that is used to set minimum supported sampling frequency for the associated mock sensor. | *** ## getMockSensor[​](#getmocksensor "Direct link to getMockSensor") Retrieves information about a given type of mock sensor. **Note:** this feature has not landed in all browsers yet.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/sensors/#get-mock-sensor-command). ### Usage[​](#usage-64 "Direct link to Usage") ``` await browser.getMockSensor(type) ``` ### Parameters[​](#parameters-40 "Direct link to Parameters") | Name | Type | Details | | ------ | -------- | ---------------------------------------------- | | `type` | `String` | Mock sensor type to retrieve information from. | ### Returns[​](#returns-41 "Direct link to Returns") * **\<object>** **`sensorReading`:** Values of the mock sensor reading. *** ## updateMockSensor[​](#updatemocksensor "Direct link to updateMockSensor") Updates the mock sensor type. **Note:** this feature has not landed in all browsers yet.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/sensors/#update-mock-sensor-reading-command). ### Usage[​](#usage-65 "Direct link to Usage") ``` await browser.updateMockSensor(type, reading) ``` ### Parameters[​](#parameters-41 "Direct link to Parameters") | Name | Type | Details | | --------- | -------- | ------------------------------------------- | | `type` | `String` | Mock sensor type to update information for. | | `reading` | `object` | A JSON Object with the new reading. | *** ## deleteMockSensor[​](#deletemocksensor "Direct link to deleteMockSensor") The Delete Session command closes any top-level browsing contexts associated with the current session, terminates the connection, and finally closes the current session. **Note:** this feature has not landed in all browsers yet.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/sensors/#delete-mock-sensor-command). ### Usage[​](#usage-66 "Direct link to Usage") ``` await browser.deleteMockSensor(type) ``` ### Parameters[​](#parameters-42 "Direct link to Parameters") | Name | Type | Details | | ------ | -------- | --------------------------- | | `type` | `String` | Mock sensor type to delete. | *** ## setTimeZone[​](#settimezone "Direct link to setTimeZone") Simulates the changing of a time zone for the purposes of testing. **Note:** this feature has not landed in all browsers yet.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-emulation-setTimezoneOverride). ### Usage[​](#usage-67 "Direct link to Usage") ``` await browser.setTimeZone(time_zone) ``` ### Parameters[​](#parameters-43 "Direct link to Parameters") | Name | Type | Details | | ----------- | -------- | ------------------------------------- | | `time_zone` | `string` | Name of the timezone, e.g. Asia/Tokyo | *** ## addVirtualAuthenticator[​](#addvirtualauthenticator "Direct link to addVirtualAuthenticator") Creates a software [Virtual Authenticator](https://www.w3.org/TR/webauthn-2/#virtual-authenticators).<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://www.w3.org/TR/webauthn-2/#sctn-automation-add-virtual-authenticator). ### Usage[​](#usage-68 "Direct link to Usage") ``` await browser.addVirtualAuthenticator(protocol, transport, hasResidentKey, hasUserVerification, isUserConsenting, isUserVerified, extensions, uvm) ``` ### Parameters[​](#parameters-44 "Direct link to Parameters") | Name | Type | Details | | ------------------------------------- | ---------- | ------------------------------------------------------- | | `protocol` | `string` | Valid values: 'ctap1/u2f', 'ctap2', 'ctap2\_1'. | | `transport` | `string` | Valid values: 'usb', 'nfc', 'ble' or 'internal'. | | `hasResidentKey`<br />*optional* | `boolean` | Valid values: true, false. | | `hasUserVerification`<br />*optional* | `boolean` | Valid values: true, false. | | `isUserConsenting`<br />*optional* | `boolean` | Valid values: true, false. | | `isUserVerified`<br />*optional* | `boolean` | Valid values: true, false. | | `extensions`<br />*optional* | `string[]` | An array of extension identifiers | | `uvm`<br />*optional* | `object[]` | Valid values: Up to 3 User Verification Method entries. | ### Returns[​](#returns-42 "Direct link to Returns") * **\<string>** **`authenticatorId`:** Returns the string ID of the authenticator. *** ## removeVirtualAuthenticator[​](#removevirtualauthenticator "Direct link to removeVirtualAuthenticator") Removes a previously created Virtual Authenticator.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://www.w3.org/TR/webauthn-2/#sctn-automation-remove-virtual-authenticator). ### Usage[​](#usage-69 "Direct link to Usage") ``` await browser.removeVirtualAuthenticator(authenticatorId) ``` ### Parameters[​](#parameters-45 "Direct link to Parameters") | Name | Type | Details | | ----------------- | -------- | ------------------- | | `authenticatorId` | `String` | id of authenticator | *** ## addCredential[​](#addcredential "Direct link to addCredential") Injects a Public Key Credential Source into an existing Virtual Authenticator.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://www.w3.org/TR/webauthn-2/#sctn-automation-add-credential). ### Usage[​](#usage-70 "Direct link to Usage") ``` await browser.addCredential(authenticatorId, credentialId, isResidentCredential, rpId, privateKey, userHandle, signCount, largeBlob) ``` ### Parameters[​](#parameters-46 "Direct link to Parameters") | Name | Type | Details | | ---------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | `authenticatorId` | `String` | ID of authenticator | | `credentialId` | `string` | The Credential ID encoded using Base64url Encoding. | | `isResidentCredential` | `boolean` | If set to true, a client-side discoverable credential is created. If set to false, a server-side credential is created instead. | | `rpId` | `string` | The Relying Party ID the credential is scoped to. | | `privateKey` | `string` | An asymmetric key package containing a single private key per \[RFC5958], encoded using Base64url Encoding. | | `userHandle`<br />*optional* | `string` | The userHandle associated to the credential encoded using Base64url Encoding. This property may not be defined. | | `signCount`<br />*optional* | `number, null` | The initial value for a signature counter associated to the public key credential source. | | `largeBlob`<br />*optional* | `string` | The large, per-credential blob associated to the public key credential source, encoded using Base64url Encoding. This property may not be defined. | *** ## getCredentials[​](#getcredentials "Direct link to getCredentials") Returns one Credential Parameters object for every Public Key Credential Source stored in a Virtual Authenticator, regardless of whether they were stored using Add Credential or `navigator.credentials.create()`.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://www.w3.org/TR/webauthn-2/#sctn-automation-get-credentials). ### Usage[​](#usage-71 "Direct link to Usage") ``` await browser.getCredentials(authenticatorId) ``` ### Parameters[​](#parameters-47 "Direct link to Parameters") | Name | Type | Details | | ----------------- | -------- | ------------------- | | `authenticatorId` | `String` | id of authenticator | ### Returns[​](#returns-43 "Direct link to Returns") * **\<object\[]>** **`credentials`:** Returns an array of credentials. *** ## removeAllCredentials[​](#removeallcredentials "Direct link to removeAllCredentials") Removes all Public Key Credential Sources stored on a Virtual Authenticator.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://www.w3.org/TR/webauthn-2/#sctn-automation-remove-all-credentials). ### Usage[​](#usage-72 "Direct link to Usage") ``` await browser.removeAllCredentials(authenticatorId) ``` ### Parameters[​](#parameters-48 "Direct link to Parameters") | Name | Type | Details | | ----------------- | -------- | ------------------- | | `authenticatorId` | `String` | id of authenticator | *** ## removeCredential[​](#removecredential "Direct link to removeCredential") Removes a Public Key Credential Source stored on a Virtual Authenticator.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://www.w3.org/TR/webauthn-2/#sctn-automation-remove-credential). ### Usage[​](#usage-73 "Direct link to Usage") ``` await browser.removeCredential(authenticatorId, credentialId) ``` ### Parameters[​](#parameters-49 "Direct link to Parameters") | Name | Type | Details | | ----------------- | -------- | ------------------- | | `authenticatorId` | `String` | id of authenticator | | `credentialId` | `String` | id of credential | *** ## setUserVerified[​](#setuserverified "Direct link to setUserVerified") The Set User Verified extension command sets the isUserVerified property on the Virtual Authenticator.<br /><br />WebDriver Protocol command. More details can be found in the [official protocol docs](https://www.w3.org/TR/webauthn-2/#sctn-automation-set-user-verified). ### Usage[​](#usage-74 "Direct link to Usage") ``` await browser.setUserVerified(authenticatorId, isUserVerified) ``` ### Parameters[​](#parameters-50 "Direct link to Parameters") | Name | Type | Details | | ----------------- | --------- | ---------------------------------------------- | | `authenticatorId` | `String` | id of authenticator | | `isUserVerified` | `boolean` | Whether to always succeed in user verification | --- Source: https://webdriver.io/docs/api/webdriverBidi.md # WebDriver Bidi Protocol These protocol commands are generated based on the current living [WebDriver Bidi](https://w3c.github.io/webdriver-bidi/) specification. To enable the protocol for your test make sure to have `webSocketUrl: true` set in your capabilities. Use with Caution! Browser support is not guaranteed and interfaces can change in the future. The standard is currently under development and browser vendors will add these capabilities based on their own timelines. Last Updated: Wed Nov 04 2026 11:43:49 GMT+0000 (Coordinated Universal Time) *** ## send[​](#send "Direct link to send") Send socket commands via WebDriver Bidi<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://github.com/w3c/webdriver-bidi). ### Usage[​](#usage "Direct link to Usage") ``` await browser.send(params) ``` ### Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | -------- | ------------- | -------------- | | `params` | `CommandData` | socket payload | ### Returns[​](#returns "Direct link to Returns") * **\<Object>** **`CommandResponse`:** WebDriver Bidi response *** ## sendAsync[​](#sendasync "Direct link to sendAsync") Send asynchronous socket commands via WebDriver Bidi<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://github.com/w3c/webdriver-bidi). ### Usage[​](#usage-1 "Direct link to Usage") ``` await browser.sendAsync(params) ``` ### Parameters[​](#parameters-1 "Direct link to Parameters") | Name | Type | Details | | -------- | ------------- | -------------- | | `params` | `CommandData` | socket payload | ### Returns[​](#returns-1 "Direct link to Returns") * **\<Number>** **`id`:** id of WebDriver Bidi request *** ## sessionStatus[​](#sessionstatus "Direct link to sessionStatus") WebDriver Bidi command to send command method "session.status" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-session-status). ### Usage[​](#usage-2 "Direct link to Usage") ``` await browser.sessionStatus(params) ``` ### Parameters[​](#parameters-2 "Direct link to Parameters") | Name | Type | Details | | -------- | -------------------- | -------- | | `params` | `remote.EmptyParams` | ``` {} ``` | ### Returns[​](#returns-2 "Direct link to Returns") * **\<Object>** **`local.SessionStatusResult`:** Command return value with the following interface: <!-- --> ``` { ready: boolean; message: string; } ``` *** ## sessionNew[​](#sessionnew "Direct link to sessionNew") WebDriver Bidi command to send command method "session.new" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-session-new). ### Usage[​](#usage-3 "Direct link to Usage") ``` await browser.sessionNew(params) ``` ### Parameters[​](#parameters-3 "Direct link to Parameters") | Name | Type | Details | | -------- | ----------------------------- | --------------------------------------------------- | | `params` | `remote.SessionNewParameters` | ``` { capabilities: SessionCapabilitiesRequest; } ``` | ### Returns[​](#returns-3 "Direct link to Returns") * **\<Object>** **`local.SessionNewResult`:** Command return value with the following interface: <!-- --> ``` { sessionId: string; capabilities: SessionCapabilityResponse; } ``` *** ## sessionEnd[​](#sessionend "Direct link to sessionEnd") WebDriver Bidi command to send command method "session.end" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-session-end). ### Usage[​](#usage-4 "Direct link to Usage") ``` await browser.sessionEnd(params) ``` ### Parameters[​](#parameters-4 "Direct link to Parameters") | Name | Type | Details | | -------- | -------------------- | -------- | | `params` | `remote.EmptyParams` | ``` {} ``` | ### Returns[​](#returns-4 "Direct link to Returns") * **\<Object>** **`local.SessionEndResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## sessionSubscribe[​](#sessionsubscribe "Direct link to sessionSubscribe") WebDriver Bidi command to send command method "session.subscribe" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-session-subscribe). ### Usage[​](#usage-5 "Direct link to Usage") ``` await browser.sessionSubscribe(params) ``` ### Parameters[​](#parameters-5 "Direct link to Parameters") | Name | Type | Details | | -------- | ----------------------------------- | --------------------------------------------------------------------------------------------------------------- | | `params` | `remote.SessionSubscribeParameters` | ``` { events: string[]; contexts?: BrowsingContextBrowsingContext[]; userContexts?: BrowserUserContext[]; } ``` | ### Returns[​](#returns-5 "Direct link to Returns") * **\<Object>** **`local.SessionSubscribeResult`:** Command return value with the following interface: <!-- --> ``` { subscription: SessionSubscription; } ``` *** ## sessionUnsubscribe[​](#sessionunsubscribe "Direct link to sessionUnsubscribe") WebDriver Bidi command to send command method "session.unsubscribe" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-session-unsubscribe). ### Usage[​](#usage-6 "Direct link to Usage") ``` await browser.sessionUnsubscribe(params) ``` ### Parameters[​](#parameters-6 "Direct link to Parameters") | Name | Type | Details | | -------- | ------------------------------------- | -------- | | `params` | `remote.SessionUnsubscribeParameters` | ``` {} ``` | ### Returns[​](#returns-6 "Direct link to Returns") * **\<Object>** **`local.SessionUnsubscribeResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## browserClose[​](#browserclose "Direct link to browserClose") WebDriver Bidi command to send command method "browser.close" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browser-close). ### Usage[​](#usage-7 "Direct link to Usage") ``` await browser.browserClose(params) ``` ### Parameters[​](#parameters-7 "Direct link to Parameters") | Name | Type | Details | | -------- | -------------------- | -------- | | `params` | `remote.EmptyParams` | ``` {} ``` | ### Returns[​](#returns-7 "Direct link to Returns") * **\<Object>** **`local.BrowserCloseResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## browserCreateUserContext[​](#browsercreateusercontext "Direct link to browserCreateUserContext") WebDriver Bidi command to send command method "browser.createUserContext" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browser-createUserContext). ### Usage[​](#usage-8 "Direct link to Usage") ``` await browser.browserCreateUserContext(params) ``` ### Parameters[​](#parameters-8 "Direct link to Parameters") | Name | Type | Details | | -------- | ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.BrowserCreateUserContextParameters` | ``` { acceptInsecureCerts?: boolean; proxy?: SessionProxyConfiguration; unhandledPromptBehavior?: SessionUserPromptHandler; } ``` | ### Returns[​](#returns-8 "Direct link to Returns") * **\<Object>** **`local.BrowserCreateUserContextResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## browserGetClientWindows[​](#browsergetclientwindows "Direct link to browserGetClientWindows") WebDriver Bidi command to send command method "browser.getClientWindows" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browser-getClientWindows). ### Usage[​](#usage-9 "Direct link to Usage") ``` await browser.browserGetClientWindows(params) ``` ### Parameters[​](#parameters-9 "Direct link to Parameters") | Name | Type | Details | | -------- | -------------------- | -------- | | `params` | `remote.EmptyParams` | ``` {} ``` | ### Returns[​](#returns-9 "Direct link to Returns") * **\<Object>** **`local.BrowserGetClientWindowsResult`:** Command return value with the following interface: <!-- --> ``` { clientWindows: BrowserClientWindowInfo[]; } ``` *** ## browserGetUserContexts[​](#browsergetusercontexts "Direct link to browserGetUserContexts") WebDriver Bidi command to send command method "browser.getUserContexts" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browser-getUserContexts). ### Usage[​](#usage-10 "Direct link to Usage") ``` await browser.browserGetUserContexts(params) ``` ### Parameters[​](#parameters-10 "Direct link to Parameters") | Name | Type | Details | | -------- | -------------------- | -------- | | `params` | `remote.EmptyParams` | ``` {} ``` | ### Returns[​](#returns-10 "Direct link to Returns") * **\<Object>** **`local.BrowserGetUserContextsResult`:** Command return value with the following interface: <!-- --> ``` { userContexts: BrowserUserContextInfo[]; } ``` *** ## browserRemoveUserContext[​](#browserremoveusercontext "Direct link to browserRemoveUserContext") WebDriver Bidi command to send command method "browser.removeUserContext" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browser-removeUserContext). ### Usage[​](#usage-11 "Direct link to Usage") ``` await browser.browserRemoveUserContext(params) ``` ### Parameters[​](#parameters-11 "Direct link to Parameters") | Name | Type | Details | | -------- | ------------------------------------------- | ------------------------------------------ | | `params` | `remote.BrowserRemoveUserContextParameters` | ``` { userContext: BrowserUserContext; } ``` | ### Returns[​](#returns-11 "Direct link to Returns") * **\<Object>** **`local.BrowserRemoveUserContextResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## browserSetClientWindowState[​](#browsersetclientwindowstate "Direct link to browserSetClientWindowState") WebDriver Bidi command to send command method "browser.setClientWindowState" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browser-setClientWindowState). ### Usage[​](#usage-12 "Direct link to Usage") ``` await browser.browserSetClientWindowState(params) ``` ### Parameters[​](#parameters-12 "Direct link to Parameters") | Name | Type | Details | | -------- | ---------------------------------------------- | --------------------------------------------- | | `params` | `remote.BrowserSetClientWindowStateParameters` | ``` { clientWindow: BrowserClientWindow; }; ``` | ### Returns[​](#returns-12 "Direct link to Returns") * **\<Object>** **`local.BrowserSetClientWindowStateResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## browserSetDownloadBehavior[​](#browsersetdownloadbehavior "Direct link to browserSetDownloadBehavior") WebDriver Bidi command to send command method "browser.setDownloadBehavior" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browser-setDownloadBehavior). ### Usage[​](#usage-13 "Direct link to Usage") ``` await browser.browserSetDownloadBehavior(params) ``` ### Parameters[​](#parameters-13 "Direct link to Parameters") | Name | Type | Details | | -------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------- | | `params` | `remote.BrowserSetDownloadBehaviorParameters` | ``` { downloadBehavior: BrowserDownloadBehavior | null; userContexts?: BrowserUserContext[]; } ``` | ### Returns[​](#returns-13 "Direct link to Returns") * **\<Object>** **`local.BrowserSetDownloadBehaviorResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## browsingContextActivate[​](#browsingcontextactivate "Direct link to browsingContextActivate") WebDriver Bidi command to send command method "browsingContext.activate" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browsingContext-activate). ### Usage[​](#usage-14 "Direct link to Usage") ``` await browser.browsingContextActivate(params) ``` ### Parameters[​](#parameters-14 "Direct link to Parameters") | Name | Type | Details | | -------- | ------------------------------------------ | -------------------------------------------------- | | `params` | `remote.BrowsingContextActivateParameters` | ``` { context: BrowsingContextBrowsingContext; } ``` | ### Returns[​](#returns-14 "Direct link to Returns") * **\<Object>** **`local.BrowsingContextActivateResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## browsingContextCaptureScreenshot[​](#browsingcontextcapturescreenshot "Direct link to browsingContextCaptureScreenshot") WebDriver Bidi command to send command method "browsingContext.captureScreenshot" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browsingContext-captureScreenshot). ### Usage[​](#usage-15 "Direct link to Usage") ``` await browser.browsingContextCaptureScreenshot(params) ``` ### Parameters[​](#parameters-15 "Direct link to Parameters") | Name | Type | Details | | -------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `params` | `remote.BrowsingContextCaptureScreenshotParameters` | ``` { context: BrowsingContextBrowsingContext; /** * @default 'viewport' */ origin?: "viewport" | "document"; format?: BrowsingContextImageFormat; clip?: BrowsingContextClipRectangle; imageSize?: BrowsingContextImageSize; } ``` | ### Returns[​](#returns-15 "Direct link to Returns") * **\<Object>** **`local.BrowsingContextCaptureScreenshotResult`:** Command return value with the following interface: <!-- --> ``` { data: string; } ``` *** ## browsingContextClose[​](#browsingcontextclose "Direct link to browsingContextClose") WebDriver Bidi command to send command method "browsingContext.close" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browsingContext-close). ### Usage[​](#usage-16 "Direct link to Usage") ``` await browser.browsingContextClose(params) ``` ### Parameters[​](#parameters-16 "Direct link to Parameters") | Name | Type | Details | | -------- | --------------------------------------- | --------------------------------------------------------------------------- | | `params` | `remote.BrowsingContextCloseParameters` | ``` { context: BrowsingContextBrowsingContext; promptUnload?: boolean; } ``` | ### Returns[​](#returns-16 "Direct link to Returns") * **\<Object>** **`local.BrowsingContextCloseResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## browsingContextCreate[​](#browsingcontextcreate "Direct link to browsingContextCreate") WebDriver Bidi command to send command method "browsingContext.create" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browsingContext-create). ### Usage[​](#usage-17 "Direct link to Usage") ``` await browser.browsingContextCreate(params) ``` ### Parameters[​](#parameters-17 "Direct link to Parameters") | Name | Type | Details | | -------- | ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.BrowsingContextCreateParameters` | ``` { type: BrowsingContextCreateType; referenceContext?: BrowsingContextBrowsingContext; background?: boolean; userContext?: BrowserUserContext; } ``` | ### Returns[​](#returns-17 "Direct link to Returns") * **\<Object>** **`local.BrowsingContextCreateResult`:** Command return value with the following interface: <!-- --> ``` { context: BrowsingContextBrowsingContext; userContext?: BrowserUserContext; } ``` *** ## browsingContextGetTree[​](#browsingcontextgettree "Direct link to browsingContextGetTree") WebDriver Bidi command to send command method "browsingContext.getTree" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browsingContext-getTree). ### Usage[​](#usage-18 "Direct link to Usage") ``` await browser.browsingContextGetTree(params) ``` ### Parameters[​](#parameters-18 "Direct link to Parameters") | Name | Type | Details | | -------- | ----------------------------------------- | -------------------------------------------------------------------- | | `params` | `remote.BrowsingContextGetTreeParameters` | ``` { maxDepth?: JsUint; root?: BrowsingContextBrowsingContext; } ``` | ### Returns[​](#returns-18 "Direct link to Returns") * **\<Object>** **`local.BrowsingContextGetTreeResult`:** Command return value with the following interface: <!-- --> ``` { contexts: BrowsingContextInfoList; } ``` *** ## browsingContextHandleUserPrompt[​](#browsingcontexthandleuserprompt "Direct link to browsingContextHandleUserPrompt") WebDriver Bidi command to send command method "browsingContext.handleUserPrompt" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browsingContext-handleUserPrompt). ### Usage[​](#usage-19 "Direct link to Usage") ``` await browser.browsingContextHandleUserPrompt(params) ``` ### Parameters[​](#parameters-19 "Direct link to Parameters") | Name | Type | Details | | -------- | -------------------------------------------------- | ----------------------------------------------------------------------------------------- | | `params` | `remote.BrowsingContextHandleUserPromptParameters` | ``` { context: BrowsingContextBrowsingContext; accept?: boolean; userText?: string; } ``` | ### Returns[​](#returns-19 "Direct link to Returns") * **\<Object>** **`local.BrowsingContextHandleUserPromptResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## browsingContextLocateNodes[​](#browsingcontextlocatenodes "Direct link to browsingContextLocateNodes") WebDriver Bidi command to send command method "browsingContext.locateNodes" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browsingContext-locateNodes). ### Usage[​](#usage-20 "Direct link to Usage") ``` await browser.browsingContextLocateNodes(params) ``` ### Parameters[​](#parameters-20 "Direct link to Parameters") | Name | Type | Details | | -------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.BrowsingContextLocateNodesParameters` | ``` { context: BrowsingContextBrowsingContext; locator: BrowsingContextLocator; maxNodeCount?: JsUint; serializationOptions?: ScriptSerializationOptions; startNodes?: ScriptSharedReference[]; } ``` | ### Returns[​](#returns-20 "Direct link to Returns") * **\<Object>** **`local.BrowsingContextLocateNodesResult`:** Command return value with the following interface: <!-- --> ``` { nodes: ScriptNodeRemoteValue[]; } ``` *** ## browsingContextNavigate[​](#browsingcontextnavigate "Direct link to browsingContextNavigate") WebDriver Bidi command to send command method "browsingContext.navigate" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browsingContext-navigate). ### Usage[​](#usage-21 "Direct link to Usage") ``` await browser.browsingContextNavigate(params) ``` ### Parameters[​](#parameters-21 "Direct link to Parameters") | Name | Type | Details | | -------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------- | | `params` | `remote.BrowsingContextNavigateParameters` | ``` { context: BrowsingContextBrowsingContext; url: string; wait?: BrowsingContextReadinessState; } ``` | ### Returns[​](#returns-21 "Direct link to Returns") * **\<Object>** **`local.BrowsingContextNavigateResult`:** Command return value with the following interface: <!-- --> ``` { navigation: BrowsingContextNavigation | null; url: string; } ``` *** ## browsingContextPrint[​](#browsingcontextprint "Direct link to browsingContextPrint") WebDriver Bidi command to send command method "browsingContext.print" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browsingContext-print). ### Usage[​](#usage-22 "Direct link to Usage") ``` await browser.browsingContextPrint(params) ``` ### Parameters[​](#parameters-22 "Direct link to Parameters") | Name | Type | Details | | -------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.BrowsingContextPrintParameters` | ``` { context: BrowsingContextBrowsingContext; background?: boolean; margin?: BrowsingContextPrintMarginParameters; /** * @default 'portrait' */ orientation?: "portrait" | "landscape"; page?: BrowsingContextPrintPageParameters; pageRanges?: (JsUint | string)[]; /** * @default 1 */ scale?: number; /** * @default true */ shrinkToFit?: boolean; } ``` | ### Returns[​](#returns-22 "Direct link to Returns") * **\<Object>** **`local.BrowsingContextPrintResult`:** Command return value with the following interface: <!-- --> ``` { data: string; } ``` *** ## browsingContextReload[​](#browsingcontextreload "Direct link to browsingContextReload") WebDriver Bidi command to send command method "browsingContext.reload" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browsingContext-reload). ### Usage[​](#usage-23 "Direct link to Usage") ``` await browser.browsingContextReload(params) ``` ### Parameters[​](#parameters-23 "Direct link to Parameters") | Name | Type | Details | | -------- | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | | `params` | `remote.BrowsingContextReloadParameters` | ``` { context: BrowsingContextBrowsingContext; ignoreCache?: boolean; wait?: BrowsingContextReadinessState; } ``` | ### Returns[​](#returns-23 "Direct link to Returns") * **\<Object>** **`local.BrowsingContextReloadResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## browsingContextSetBypassCsp[​](#browsingcontextsetbypasscsp "Direct link to browsingContextSetBypassCsp") WebDriver Bidi command to send command method "browsingContext.setBypassCSP" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browsingContext-setBypassCSP). ### Usage[​](#usage-24 "Direct link to Usage") ``` await browser.browsingContextSetBypassCsp(params) ``` ### Parameters[​](#parameters-24 "Direct link to Parameters") | Name | Type | Details | | -------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | | `params` | `remote.BrowsingContextSetBypassCspParameters` | ``` { bypass: true | null; contexts?: BrowsingContextBrowsingContext[]; userContexts?: BrowserUserContext[]; } ``` | ### Returns[​](#returns-24 "Direct link to Returns") * **\<Object>** **`local.BrowsingContextSetBypassCspResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## browsingContextSetViewport[​](#browsingcontextsetviewport "Direct link to browsingContextSetViewport") WebDriver Bidi command to send command method "browsingContext.setViewport" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browsingContext-setViewport). ### Usage[​](#usage-25 "Direct link to Usage") ``` await browser.browsingContextSetViewport(params) ``` ### Parameters[​](#parameters-25 "Direct link to Parameters") | Name | Type | Details | | -------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `params` | `remote.BrowsingContextSetViewportParameters` | ``` { context?: BrowsingContextBrowsingContext; viewport?: BrowsingContextViewport | null; devicePixelRatio?: number | null; userContexts?: BrowserUserContext[]; } ``` | ### Returns[​](#returns-25 "Direct link to Returns") * **\<Object>** **`local.BrowsingContextSetViewportResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## browsingContextStartScreencast[​](#browsingcontextstartscreencast "Direct link to browsingContextStartScreencast") WebDriver Bidi command to send command method "browsingContext.startScreencast" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browsingContext-startScreencast). ### Usage[​](#usage-26 "Direct link to Usage") ``` await browser.browsingContextStartScreencast(params) ``` ### Parameters[​](#parameters-26 "Direct link to Parameters") | Name | Type | Details | | -------- | ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.BrowsingContextStartScreencastParameters` | ``` { context: BrowsingContextBrowsingContext; destinationFolder?: string; mimeType?: string; video?: BrowsingContextMediaTrackConstraints; audio?: boolean; } ``` | ### Returns[​](#returns-26 "Direct link to Returns") * **\<Object>** **`local.BrowsingContextStartScreencastResult`:** Command return value with the following interface: <!-- --> ``` { screencast: BrowsingContextScreencast; path: string; } ``` *** ## browsingContextStopScreencast[​](#browsingcontextstopscreencast "Direct link to browsingContextStopScreencast") WebDriver Bidi command to send command method "browsingContext.stopScreencast" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browsingContext-stopScreencast). ### Usage[​](#usage-27 "Direct link to Usage") ``` await browser.browsingContextStopScreencast(params) ``` ### Parameters[​](#parameters-27 "Direct link to Parameters") | Name | Type | Details | | -------- | ------------------------------------------------ | ------------------------------------------------ | | `params` | `remote.BrowsingContextStopScreencastParameters` | ``` { screencast: BrowsingContextScreencast; } ``` | ### Returns[​](#returns-27 "Direct link to Returns") * **\<Object>** **`local.BrowsingContextStopScreencastResult`:** Command return value with the following interface: <!-- --> ``` { path: string; error?: string; } ``` *** ## browsingContextTraverseHistory[​](#browsingcontexttraversehistory "Direct link to browsingContextTraverseHistory") WebDriver Bidi command to send command method "browsingContext.traverseHistory" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-browsingContext-traverseHistory). ### Usage[​](#usage-28 "Direct link to Usage") ``` await browser.browsingContextTraverseHistory(params) ``` ### Parameters[​](#parameters-28 "Direct link to Parameters") | Name | Type | Details | | -------- | ------------------------------------------------- | ----------------------------------------------------------------- | | `params` | `remote.BrowsingContextTraverseHistoryParameters` | ``` { context: BrowsingContextBrowsingContext; delta: JsInt; } ``` | ### Returns[​](#returns-28 "Direct link to Returns") * **\<Object>** **`local.BrowsingContextTraverseHistoryResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## emulationSetForcedColorsModeThemeOverride[​](#emulationsetforcedcolorsmodethemeoverride "Direct link to emulationSetForcedColorsModeThemeOverride") WebDriver Bidi command to send command method "emulation.setForcedColorsModeThemeOverride" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-emulation-setForcedColorsModeThemeOverride). ### Usage[​](#usage-29 "Direct link to Usage") ``` await browser.emulationSetForcedColorsModeThemeOverride(params) ``` ### Parameters[​](#parameters-29 "Direct link to Parameters") | Name | Type | Details | | -------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.EmulationSetForcedColorsModeThemeOverrideParameters` | ``` { theme: EmulationForcedColorsModeTheme | null; contexts?: BrowsingContextBrowsingContext[]; userContexts?: BrowserUserContext[]; } ``` | ### Returns[​](#returns-29 "Direct link to Returns") * **\<Object>** **`local.EmulationSetForcedColorsModeThemeOverrideResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## emulationSetGeolocationOverride[​](#emulationsetgeolocationoverride "Direct link to emulationSetGeolocationOverride") WebDriver Bidi command to send command method "emulation.setGeolocationOverride" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-emulation-setGeolocationOverride). ### Usage[​](#usage-30 "Direct link to Usage") ``` await browser.emulationSetGeolocationOverride(params) ``` ### Parameters[​](#parameters-30 "Direct link to Parameters") | Name | Type | Details | | -------- | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.EmulationSetGeolocationOverrideParameters` | ``` { coordinates: EmulationGeolocationCoordinates | null; } | { error: EmulationGeolocationPositionError; }) & { contexts?: BrowsingContextBrowsingContext[]; userContexts?: BrowserUserContext[]; }; ``` | ### Returns[​](#returns-30 "Direct link to Returns") * **\<Object>** **`local.EmulationSetGeolocationOverrideResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## emulationSetLocaleOverride[​](#emulationsetlocaleoverride "Direct link to emulationSetLocaleOverride") WebDriver Bidi command to send command method "emulation.setLocaleOverride" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-emulation-setLocaleOverride). ### Usage[​](#usage-31 "Direct link to Usage") ``` await browser.emulationSetLocaleOverride(params) ``` ### Parameters[​](#parameters-31 "Direct link to Parameters") | Name | Type | Details | | -------- | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.EmulationSetLocaleOverrideParameters` | ``` { locale: string | null; contexts?: BrowsingContextBrowsingContext[]; userContexts?: BrowserUserContext[]; } ``` | ### Returns[​](#returns-31 "Direct link to Returns") * **\<Object>** **`local.EmulationSetLocaleOverrideResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## emulationSetMediaFeaturesOverride[​](#emulationsetmediafeaturesoverride "Direct link to emulationSetMediaFeaturesOverride") WebDriver Bidi command to send command method "emulation.setMediaFeaturesOverride" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-emulation-setMediaFeaturesOverride). ### Usage[​](#usage-32 "Direct link to Usage") ``` await browser.emulationSetMediaFeaturesOverride(params) ``` ### Parameters[​](#parameters-32 "Direct link to Parameters") | Name | Type | Details | | -------- | ---------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.EmulationSetMediaFeaturesOverrideParameters` | ``` { features: EmulationMediaFeatures | null; contexts?: BrowsingContextBrowsingContext[]; userContexts?: BrowserUserContext[]; } ``` | ### Returns[​](#returns-32 "Direct link to Returns") * **\<Object>** **`local.EmulationSetMediaFeaturesOverrideResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## emulationSetNetworkConditions[​](#emulationsetnetworkconditions "Direct link to emulationSetNetworkConditions") WebDriver Bidi command to send command method "emulation.setNetworkConditions" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-emulation-setNetworkConditions). ### Usage[​](#usage-33 "Direct link to Usage") ``` await browser.emulationSetNetworkConditions(params) ``` ### Parameters[​](#parameters-33 "Direct link to Parameters") | Name | Type | Details | | -------- | ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.EmulationSetNetworkConditionsParameters` | ``` { networkConditions: EmulationNetworkConditions | null; contexts?: BrowsingContextBrowsingContext[]; userContexts?: BrowserUserContext[]; } ``` | ### Returns[​](#returns-33 "Direct link to Returns") * **\<Object>** **`local.EmulationSetNetworkConditionsResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## emulationSetScreenSettingsOverride[​](#emulationsetscreensettingsoverride "Direct link to emulationSetScreenSettingsOverride") WebDriver Bidi command to send command method "emulation.setScreenSettingsOverride" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-emulation-setScreenSettingsOverride). ### Usage[​](#usage-34 "Direct link to Usage") ``` await browser.emulationSetScreenSettingsOverride(params) ``` ### Parameters[​](#parameters-34 "Direct link to Parameters") | Name | Type | Details | | -------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.EmulationSetScreenSettingsOverrideParameters` | ``` { screenArea: EmulationScreenArea | null; contexts?: BrowsingContextBrowsingContext[]; userContexts?: BrowserUserContext[]; } ``` | ### Returns[​](#returns-34 "Direct link to Returns") * **\<Object>** **`local.EmulationSetScreenSettingsOverrideResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## emulationSetScreenOrientationOverride[​](#emulationsetscreenorientationoverride "Direct link to emulationSetScreenOrientationOverride") WebDriver Bidi command to send command method "emulation.setScreenOrientationOverride" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-emulation-setScreenOrientationOverride). ### Usage[​](#usage-35 "Direct link to Usage") ``` await browser.emulationSetScreenOrientationOverride(params) ``` ### Parameters[​](#parameters-35 "Direct link to Parameters") | Name | Type | Details | | -------- | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.EmulationSetScreenOrientationOverrideParameters` | ``` { screenOrientation: EmulationScreenOrientation | null; contexts?: BrowsingContextBrowsingContext[]; userContexts?: BrowserUserContext[]; } ``` | ### Returns[​](#returns-35 "Direct link to Returns") * **\<Object>** **`local.EmulationSetScreenOrientationOverrideResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## emulationSetUserAgentOverride[​](#emulationsetuseragentoverride "Direct link to emulationSetUserAgentOverride") WebDriver Bidi command to send command method "emulation.setUserAgentOverride" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-emulation-setUserAgentOverride). ### Usage[​](#usage-36 "Direct link to Usage") ``` await browser.emulationSetUserAgentOverride(params) ``` ### Parameters[​](#parameters-36 "Direct link to Parameters") | Name | Type | Details | | -------- | ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.EmulationSetUserAgentOverrideParameters` | ``` { userAgent: string | null; contexts?: BrowsingContextBrowsingContext[]; userContexts?: BrowserUserContext[]; } ``` | ### Returns[​](#returns-36 "Direct link to Returns") * **\<Object>** **`local.EmulationSetUserAgentOverrideResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## emulationSetViewportMetaOverride[​](#emulationsetviewportmetaoverride "Direct link to emulationSetViewportMetaOverride") WebDriver Bidi command to send command method "emulation.setViewportMetaOverride" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-emulation-setViewportMetaOverride). ### Usage[​](#usage-37 "Direct link to Usage") ``` await browser.emulationSetViewportMetaOverride(params) ``` ### Parameters[​](#parameters-37 "Direct link to Parameters") | Name | Type | Details | | -------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | | `params` | `remote.EmulationSetViewportMetaOverrideParameters` | ``` { viewportMeta: true | null; contexts?: BrowsingContextBrowsingContext[]; userContexts?: BrowserUserContext[]; } ``` | ### Returns[​](#returns-37 "Direct link to Returns") * **\<Object>** **`local.EmulationSetViewportMetaOverrideResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## emulationSetScriptingEnabled[​](#emulationsetscriptingenabled "Direct link to emulationSetScriptingEnabled") WebDriver Bidi command to send command method "emulation.setScriptingEnabled" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-emulation-setScriptingEnabled). ### Usage[​](#usage-38 "Direct link to Usage") ``` await browser.emulationSetScriptingEnabled(params) ``` ### Parameters[​](#parameters-38 "Direct link to Parameters") | Name | Type | Details | | -------- | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.EmulationSetScriptingEnabledParameters` | ``` { enabled: false | null; contexts?: BrowsingContextBrowsingContext[]; userContexts?: BrowserUserContext[]; } ``` | ### Returns[​](#returns-38 "Direct link to Returns") * **\<Object>** **`local.EmulationSetScriptingEnabledResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## emulationSetScrollbarTypeOverride[​](#emulationsetscrollbartypeoverride "Direct link to emulationSetScrollbarTypeOverride") WebDriver Bidi command to send command method "emulation.setScrollbarTypeOverride" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-emulation-setScrollbarTypeOverride). ### Usage[​](#usage-39 "Direct link to Usage") ``` await browser.emulationSetScrollbarTypeOverride(params) ``` ### Parameters[​](#parameters-39 "Direct link to Parameters") | Name | Type | Details | | -------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | `params` | `remote.EmulationSetScrollbarTypeOverrideParameters` | ``` { scrollbarType: "classic" | "overlay" | null; contexts?: BrowsingContextBrowsingContext[]; userContexts?: BrowserUserContext[]; } ``` | ### Returns[​](#returns-39 "Direct link to Returns") * **\<Object>** **`local.EmulationSetScrollbarTypeOverrideResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## emulationSetTextLayoutModeOverride[​](#emulationsettextlayoutmodeoverride "Direct link to emulationSetTextLayoutModeOverride") WebDriver Bidi command to send command method "emulation.setTextLayoutModeOverride" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-emulation-setTextLayoutModeOverride). ### Usage[​](#usage-40 "Direct link to Usage") ``` await browser.emulationSetTextLayoutModeOverride(params) ``` ### Parameters[​](#parameters-40 "Direct link to Parameters") | Name | Type | Details | | -------- | ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.EmulationSetTextLayoutModeOverrideParameters` | ``` { textLayoutMode: EmulationTextLayoutMode | null; contexts?: BrowsingContextBrowsingContext[]; userContexts?: BrowserUserContext[]; } ``` | ### Returns[​](#returns-40 "Direct link to Returns") * **\<Object>** **`local.EmulationSetTextLayoutModeOverrideResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## emulationSetTimezoneOverride[​](#emulationsettimezoneoverride "Direct link to emulationSetTimezoneOverride") WebDriver Bidi command to send command method "emulation.setTimezoneOverride" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-emulation-setTimezoneOverride). ### Usage[​](#usage-41 "Direct link to Usage") ``` await browser.emulationSetTimezoneOverride(params) ``` ### Parameters[​](#parameters-41 "Direct link to Parameters") | Name | Type | Details | | -------- | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.EmulationSetTimezoneOverrideParameters` | ``` { timezone: string | null; contexts?: BrowsingContextBrowsingContext[]; userContexts?: BrowserUserContext[]; } ``` | ### Returns[​](#returns-41 "Direct link to Returns") * **\<Object>** **`local.EmulationSetTimezoneOverrideResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## emulationSetTouchOverride[​](#emulationsettouchoverride "Direct link to emulationSetTouchOverride") WebDriver Bidi command to send command method "emulation.setTouchOverride" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-emulation-setTouchOverride). ### Usage[​](#usage-42 "Direct link to Usage") ``` await browser.emulationSetTouchOverride(params) ``` ### Parameters[​](#parameters-42 "Direct link to Parameters") | Name | Type | Details | | -------- | -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.EmulationSetTouchOverrideParameters` | ``` { maxTouchPoints: JsUint | null; contexts?: BrowsingContextBrowsingContext[]; userContexts?: BrowserUserContext[]; } ``` | ### Returns[​](#returns-42 "Direct link to Returns") * **\<Object>** **`local.EmulationSetTouchOverrideResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## networkAddDataCollector[​](#networkadddatacollector "Direct link to networkAddDataCollector") WebDriver Bidi command to send command method "network.addDataCollector" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-network-addDataCollector). ### Usage[​](#usage-43 "Direct link to Usage") ``` await browser.networkAddDataCollector(params) ``` ### Parameters[​](#parameters-43 "Direct link to Parameters") | Name | Type | Details | | -------- | ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.NetworkAddDataCollectorParameters` | ``` { dataTypes: NetworkDataType[]; maxEncodedDataSize: JsUint; /** * @default 'blob' */ collectorType?: NetworkCollectorType; contexts?: BrowsingContextBrowsingContext[]; userContexts?: BrowserUserContext[]; } ``` | ### Returns[​](#returns-43 "Direct link to Returns") * **\<Object>** **`local.NetworkAddDataCollectorResult`:** Command return value with the following interface: <!-- --> ``` { collector: NetworkCollector; } ``` *** ## networkAddIntercept[​](#networkaddintercept "Direct link to networkAddIntercept") WebDriver Bidi command to send command method "network.addIntercept" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-network-addIntercept). ### Usage[​](#usage-44 "Direct link to Usage") ``` await browser.networkAddIntercept(params) ``` ### Parameters[​](#parameters-44 "Direct link to Parameters") | Name | Type | Details | | -------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.NetworkAddInterceptParameters` | ``` { phases: NetworkInterceptPhase[]; contexts?: BrowsingContextBrowsingContext[]; urlPatterns?: NetworkUrlPattern[]; } ``` | ### Returns[​](#returns-44 "Direct link to Returns") * **\<Object>** **`local.NetworkAddInterceptResult`:** Command return value with the following interface: <!-- --> ``` { intercept: NetworkIntercept; } ``` *** ## networkContinueRequest[​](#networkcontinuerequest "Direct link to networkContinueRequest") WebDriver Bidi command to send command method "network.continueRequest" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-network-continueRequest). ### Usage[​](#usage-45 "Direct link to Usage") ``` await browser.networkContinueRequest(params) ``` ### Parameters[​](#parameters-45 "Direct link to Parameters") | Name | Type | Details | | -------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `params` | `remote.NetworkContinueRequestParameters` | ``` { request: NetworkRequest; body?: NetworkBytesValue; cookies?: NetworkCookieHeader[]; headers?: NetworkHeader[]; method?: string; url?: string; } ``` | ### Returns[​](#returns-45 "Direct link to Returns") * **\<Object>** **`local.NetworkContinueRequestResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## networkContinueResponse[​](#networkcontinueresponse "Direct link to networkContinueResponse") WebDriver Bidi command to send command method "network.continueResponse" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-network-continueResponse). ### Usage[​](#usage-46 "Direct link to Usage") ``` await browser.networkContinueResponse(params) ``` ### Parameters[​](#parameters-46 "Direct link to Parameters") | Name | Type | Details | | -------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.NetworkContinueResponseParameters` | ``` { request: NetworkRequest; cookies?: NetworkSetCookieHeader[]; credentials?: NetworkAuthCredentials; headers?: NetworkHeader[]; reasonPhrase?: string; statusCode?: JsUint; } ``` | ### Returns[​](#returns-46 "Direct link to Returns") * **\<Object>** **`local.NetworkContinueResponseResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## networkContinueWithAuth[​](#networkcontinuewithauth "Direct link to networkContinueWithAuth") WebDriver Bidi command to send command method "network.continueWithAuth" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-network-continueWithAuth). ### Usage[​](#usage-47 "Direct link to Usage") ``` await browser.networkContinueWithAuth(params) ``` ### Parameters[​](#parameters-47 "Direct link to Parameters") | Name | Type | Details | | -------- | ------------------------------------------ | ----------------------------------- | | `params` | `remote.NetworkContinueWithAuthParameters` | ``` { request: NetworkRequest; }; ``` | ### Returns[​](#returns-47 "Direct link to Returns") * **\<Object>** **`local.NetworkContinueWithAuthResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## networkDisownData[​](#networkdisowndata "Direct link to networkDisownData") WebDriver Bidi command to send command method "network.disownData" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-network-disownData). ### Usage[​](#usage-48 "Direct link to Usage") ``` await browser.networkDisownData(params) ``` ### Parameters[​](#parameters-48 "Direct link to Parameters") | Name | Type | Details | | -------- | ------------------------------------ | -------------------------------------------------------------------------------------------- | | `params` | `remote.NetworkDisownDataParameters` | ``` { dataType: NetworkDataType; collector: NetworkCollector; request: NetworkRequest; } ``` | ### Returns[​](#returns-48 "Direct link to Returns") * **\<Object>** **`local.NetworkDisownDataResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## networkFailRequest[​](#networkfailrequest "Direct link to networkFailRequest") WebDriver Bidi command to send command method "network.failRequest" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-network-failRequest). ### Usage[​](#usage-49 "Direct link to Usage") ``` await browser.networkFailRequest(params) ``` ### Parameters[​](#parameters-49 "Direct link to Parameters") | Name | Type | Details | | -------- | ------------------------------------- | ---------------------------------- | | `params` | `remote.NetworkFailRequestParameters` | ``` { request: NetworkRequest; } ``` | ### Returns[​](#returns-49 "Direct link to Returns") * **\<Object>** **`local.NetworkFailRequestResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## networkGetData[​](#networkgetdata "Direct link to networkGetData") WebDriver Bidi command to send command method "network.getData" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-network-getData). ### Usage[​](#usage-50 "Direct link to Usage") ``` await browser.networkGetData(params) ``` ### Parameters[​](#parameters-50 "Direct link to Parameters") | Name | Type | Details | | -------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------------- | | `params` | `remote.NetworkGetDataParameters` | ``` { dataType: NetworkDataType; collector?: NetworkCollector; disown?: boolean; request: NetworkRequest; } ``` | ### Returns[​](#returns-50 "Direct link to Returns") * **\<Object>** **`local.NetworkGetDataResult`:** Command return value with the following interface: <!-- --> ``` { bytes: NetworkBytesValue; } ``` *** ## networkProvideResponse[​](#networkprovideresponse "Direct link to networkProvideResponse") WebDriver Bidi command to send command method "network.provideResponse" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-network-provideResponse). ### Usage[​](#usage-51 "Direct link to Usage") ``` await browser.networkProvideResponse(params) ``` ### Parameters[​](#parameters-51 "Direct link to Parameters") | Name | Type | Details | | -------- | ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.NetworkProvideResponseParameters` | ``` { request: NetworkRequest; body?: NetworkBytesValue; cookies?: NetworkSetCookieHeader[]; headers?: NetworkHeader[]; reasonPhrase?: string; statusCode?: JsUint; } ``` | ### Returns[​](#returns-51 "Direct link to Returns") * **\<Object>** **`local.NetworkProvideResponseResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## networkRemoveDataCollector[​](#networkremovedatacollector "Direct link to networkRemoveDataCollector") WebDriver Bidi command to send command method "network.removeDataCollector" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-network-removeDataCollector). ### Usage[​](#usage-52 "Direct link to Usage") ``` await browser.networkRemoveDataCollector(params) ``` ### Parameters[​](#parameters-52 "Direct link to Parameters") | Name | Type | Details | | -------- | --------------------------------------------- | -------------------------------------- | | `params` | `remote.NetworkRemoveDataCollectorParameters` | ``` { collector: NetworkCollector; } ``` | ### Returns[​](#returns-52 "Direct link to Returns") * **\<Object>** **`local.NetworkRemoveDataCollectorResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## networkRemoveIntercept[​](#networkremoveintercept "Direct link to networkRemoveIntercept") WebDriver Bidi command to send command method "network.removeIntercept" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-network-removeIntercept). ### Usage[​](#usage-53 "Direct link to Usage") ``` await browser.networkRemoveIntercept(params) ``` ### Parameters[​](#parameters-53 "Direct link to Parameters") | Name | Type | Details | | -------- | ----------------------------------------- | -------------------------------------- | | `params` | `remote.NetworkRemoveInterceptParameters` | ``` { intercept: NetworkIntercept; } ``` | ### Returns[​](#returns-53 "Direct link to Returns") * **\<Object>** **`local.NetworkRemoveInterceptResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## networkSetCacheBehavior[​](#networksetcachebehavior "Direct link to networkSetCacheBehavior") WebDriver Bidi command to send command method "network.setCacheBehavior" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-network-setCacheBehavior). ### Usage[​](#usage-54 "Direct link to Usage") ``` await browser.networkSetCacheBehavior(params) ``` ### Parameters[​](#parameters-54 "Direct link to Parameters") | Name | Type | Details | | -------- | ------------------------------------------ | -------------------------------------------------------------------------------------------- | | `params` | `remote.NetworkSetCacheBehaviorParameters` | ``` { cacheBehavior: "default" | "bypass"; contexts?: BrowsingContextBrowsingContext[]; } ``` | ### Returns[​](#returns-54 "Direct link to Returns") * **\<Object>** **`local.NetworkSetCacheBehaviorResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## networkSetExtraHeaders[​](#networksetextraheaders "Direct link to networkSetExtraHeaders") WebDriver Bidi command to send command method "network.setExtraHeaders" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-network-setExtraHeaders). ### Usage[​](#usage-55 "Direct link to Usage") ``` await browser.networkSetExtraHeaders(params) ``` ### Parameters[​](#parameters-55 "Direct link to Parameters") | Name | Type | Details | | -------- | ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.NetworkSetExtraHeadersParameters` | ``` { headers: NetworkHeader[]; contexts?: BrowsingContextBrowsingContext[]; userContexts?: BrowserUserContext[]; } ``` | ### Returns[​](#returns-55 "Direct link to Returns") * **\<Object>** **`local.NetworkSetExtraHeadersResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## scriptAddPreloadScript[​](#scriptaddpreloadscript "Direct link to scriptAddPreloadScript") WebDriver Bidi command to send command method "script.addPreloadScript" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-script-addPreloadScript). ### Usage[​](#usage-56 "Direct link to Usage") ``` await browser.scriptAddPreloadScript(params) ``` ### Parameters[​](#parameters-56 "Direct link to Parameters") | Name | Type | Details | | -------- | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.ScriptAddPreloadScriptParameters` | ``` { functionDeclaration: string; arguments?: ScriptChannelValue[]; contexts?: BrowsingContextBrowsingContext[]; userContexts?: BrowserUserContext[]; sandbox?: string; } ``` | ### Returns[​](#returns-56 "Direct link to Returns") * **\<Object>** **`local.ScriptAddPreloadScriptResult`:** Command return value with the following interface: <!-- --> ``` { script: ScriptPreloadScript; } ``` *** ## scriptDisown[​](#scriptdisown "Direct link to scriptDisown") WebDriver Bidi command to send command method "script.disown" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-script-disown). ### Usage[​](#usage-57 "Direct link to Usage") ``` await browser.scriptDisown(params) ``` ### Parameters[​](#parameters-57 "Direct link to Parameters") | Name | Type | Details | | -------- | ------------------------------- | --------------------------------------------------------- | | `params` | `remote.ScriptDisownParameters` | ``` { handles: ScriptHandle[]; target: ScriptTarget; } ``` | ### Returns[​](#returns-57 "Direct link to Returns") * **\<Object>** **`local.ScriptDisownResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## scriptCallFunction[​](#scriptcallfunction "Direct link to scriptCallFunction") WebDriver Bidi command to send command method "script.callFunction" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-script-callFunction). ### Usage[​](#usage-58 "Direct link to Usage") ``` await browser.scriptCallFunction(params) ``` ### Parameters[​](#parameters-58 "Direct link to Parameters") | Name | Type | Details | | -------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.ScriptCallFunctionParameters` | ``` { functionDeclaration: string; awaitPromise: boolean; target: ScriptTarget; arguments?: ScriptLocalValue[]; resultOwnership?: ScriptResultOwnership; serializationOptions?: ScriptSerializationOptions; this?: ScriptLocalValue; userActivation?: boolean; } ``` | ### Returns[​](#returns-58 "Direct link to Returns") * **\<Object>** **`local.ScriptCallFunctionResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## scriptEvaluate[​](#scriptevaluate "Direct link to scriptEvaluate") WebDriver Bidi command to send command method "script.evaluate" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-script-evaluate). ### Usage[​](#usage-59 "Direct link to Usage") ``` await browser.scriptEvaluate(params) ``` ### Parameters[​](#parameters-59 "Direct link to Parameters") | Name | Type | Details | | -------- | --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `params` | `remote.ScriptEvaluateParameters` | ``` { expression: string; target: ScriptTarget; awaitPromise: boolean; resultOwnership?: ScriptResultOwnership; serializationOptions?: ScriptSerializationOptions; userActivation?: boolean; } ``` | ### Returns[​](#returns-59 "Direct link to Returns") * **\<Object>** **`local.ScriptEvaluateResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## scriptGetRealms[​](#scriptgetrealms "Direct link to scriptGetRealms") WebDriver Bidi command to send command method "script.getRealms" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-script-getRealms). ### Usage[​](#usage-60 "Direct link to Usage") ``` await browser.scriptGetRealms(params) ``` ### Parameters[​](#parameters-60 "Direct link to Parameters") | Name | Type | Details | | -------- | ---------------------------------- | ---------------------------------------------------------------------------- | | `params` | `remote.ScriptGetRealmsParameters` | ``` { context?: BrowsingContextBrowsingContext; type?: ScriptRealmType; } ``` | ### Returns[​](#returns-60 "Direct link to Returns") * **\<Object>** **`local.ScriptGetRealmsResult`:** Command return value with the following interface: <!-- --> ``` { realms: ScriptRealmInfo[]; } ``` *** ## scriptRemovePreloadScript[​](#scriptremovepreloadscript "Direct link to scriptRemovePreloadScript") WebDriver Bidi command to send command method "script.removePreloadScript" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-script-removePreloadScript). ### Usage[​](#usage-61 "Direct link to Usage") ``` await browser.scriptRemovePreloadScript(params) ``` ### Parameters[​](#parameters-61 "Direct link to Parameters") | Name | Type | Details | | -------- | -------------------------------------------- | -------------------------------------- | | `params` | `remote.ScriptRemovePreloadScriptParameters` | ``` { script: ScriptPreloadScript; } ``` | ### Returns[​](#returns-61 "Direct link to Returns") * **\<Object>** **`local.ScriptRemovePreloadScriptResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## storageGetCookies[​](#storagegetcookies "Direct link to storageGetCookies") WebDriver Bidi command to send command method "storage.getCookies" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-storage-getCookies). ### Usage[​](#usage-62 "Direct link to Usage") ``` await browser.storageGetCookies(params) ``` ### Parameters[​](#parameters-62 "Direct link to Parameters") | Name | Type | Details | | -------- | ------------------------------------ | -------------------------------------------------------------------------------- | | `params` | `remote.StorageGetCookiesParameters` | ``` { filter?: StorageCookieFilter; partition?: StoragePartitionDescriptor; } ``` | ### Returns[​](#returns-62 "Direct link to Returns") * **\<Object>** **`local.StorageGetCookiesResult`:** Command return value with the following interface: <!-- --> ``` { cookies: NetworkCookie[]; partitionKey: StoragePartitionKey; } ``` *** ## storageSetCookie[​](#storagesetcookie "Direct link to storageSetCookie") WebDriver Bidi command to send command method "storage.setCookie" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-storage-setCookie). ### Usage[​](#usage-63 "Direct link to Usage") ``` await browser.storageSetCookie(params) ``` ### Parameters[​](#parameters-63 "Direct link to Parameters") | Name | Type | Details | | -------- | ----------------------------------- | -------------------------------------------------------------------------------- | | `params` | `remote.StorageSetCookieParameters` | ``` { cookie: StoragePartialCookie; partition?: StoragePartitionDescriptor; } ``` | ### Returns[​](#returns-63 "Direct link to Returns") * **\<Object>** **`local.StorageSetCookieResult`:** Command return value with the following interface: <!-- --> ``` { partitionKey: StoragePartitionKey; } ``` *** ## storageDeleteCookies[​](#storagedeletecookies "Direct link to storageDeleteCookies") WebDriver Bidi command to send command method "storage.deleteCookies" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-storage-deleteCookies). ### Usage[​](#usage-64 "Direct link to Usage") ``` await browser.storageDeleteCookies(params) ``` ### Parameters[​](#parameters-64 "Direct link to Parameters") | Name | Type | Details | | -------- | --------------------------------------- | -------------------------------------------------------------------------------- | | `params` | `remote.StorageDeleteCookiesParameters` | ``` { filter?: StorageCookieFilter; partition?: StoragePartitionDescriptor; } ``` | ### Returns[​](#returns-64 "Direct link to Returns") * **\<Object>** **`local.StorageDeleteCookiesResult`:** Command return value with the following interface: <!-- --> ``` { partitionKey: StoragePartitionKey; } ``` *** ## inputPerformActions[​](#inputperformactions "Direct link to inputPerformActions") WebDriver Bidi command to send command method "input.performActions" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-input-performActions). ### Usage[​](#usage-65 "Direct link to Usage") ``` await browser.inputPerformActions(params) ``` ### Parameters[​](#parameters-65 "Direct link to Parameters") | Name | Type | Details | | -------- | -------------------------------------- | ---------------------------------------------------------------------------------- | | `params` | `remote.InputPerformActionsParameters` | ``` { context: BrowsingContextBrowsingContext; actions: InputSourceActions[]; } ``` | ### Returns[​](#returns-65 "Direct link to Returns") * **\<Object>** **`local.InputPerformActionsResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## inputReleaseActions[​](#inputreleaseactions "Direct link to inputReleaseActions") WebDriver Bidi command to send command method "input.releaseActions" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-input-releaseActions). ### Usage[​](#usage-66 "Direct link to Usage") ``` await browser.inputReleaseActions(params) ``` ### Parameters[​](#parameters-66 "Direct link to Parameters") | Name | Type | Details | | -------- | -------------------------------------- | -------------------------------------------------- | | `params` | `remote.InputReleaseActionsParameters` | ``` { context: BrowsingContextBrowsingContext; } ``` | ### Returns[​](#returns-66 "Direct link to Returns") * **\<Object>** **`local.InputReleaseActionsResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## inputSetFiles[​](#inputsetfiles "Direct link to inputSetFiles") WebDriver Bidi command to send command method "input.setFiles" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-input-setFiles). ### Usage[​](#usage-67 "Direct link to Usage") ``` await browser.inputSetFiles(params) ``` ### Parameters[​](#parameters-67 "Direct link to Parameters") | Name | Type | Details | | -------- | -------------------------------- | ----------------------------------------------------------------------------------------------------- | | `params` | `remote.InputSetFilesParameters` | ``` { context: BrowsingContextBrowsingContext; element: ScriptSharedReference; files: string[]; } ``` | ### Returns[​](#returns-67 "Direct link to Returns") * **\<Object>** **`local.InputSetFilesResult`:** Command return value with the following interface: <!-- --> ``` ; ``` *** ## webExtensionInstall[​](#webextensioninstall "Direct link to webExtensionInstall") WebDriver Bidi command to send command method "webExtension.install" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-webExtension-install). ### Usage[​](#usage-68 "Direct link to Usage") ``` await browser.webExtensionInstall(params) ``` ### Parameters[​](#parameters-68 "Direct link to Parameters") | Name | Type | Details | | -------- | -------------------------------------- | --------------------------------------------------- | | `params` | `remote.WebExtensionInstallParameters` | ``` { extensionData: WebExtensionExtensionData; } ``` | ### Returns[​](#returns-68 "Direct link to Returns") * **\<Object>** **`local.WebExtensionInstallResult`:** Command return value with the following interface: <!-- --> ``` { extension: WebExtensionExtension; } ``` *** ## webExtensionUninstall[​](#webextensionuninstall "Direct link to webExtensionUninstall") WebDriver Bidi command to send command method "webExtension.uninstall" with parameters.<br /><br />WebDriver Bidi Protocol command. More details can be found in the [official protocol docs](https://w3c.github.io/webdriver-bidi/#command-webExtension-uninstall). ### Usage[​](#usage-69 "Direct link to Usage") ``` await browser.webExtensionUninstall(params) ``` ### Parameters[​](#parameters-69 "Direct link to Parameters") | Name | Type | Details | | -------- | ---------------------------------------- | ------------------------------------------- | | `params` | `remote.WebExtensionUninstallParameters` | ``` { extension: WebExtensionExtension; } ``` | ### Returns[​](#returns-69 "Direct link to Returns") * **\<Object>** **`local.WebExtensionUninstallResult`:** Command return value with the following interface: <!-- --> ``` ; ``` --- Source: https://webdriver.io/docs/api/browser.md # The Browser Object **Extends:** [EventEmitter](https://nodejs.org/api/events.html#class-eventemitter) The browser object is the session instance you use to control the browser or mobile device with. If you use the WDIO test runner, you can access the WebDriver instance through the global `browser` or `driver` object or import it using [`@wdio/globals`](/docs/api/globals.md). If you use WebdriverIO in standalone mode the browser object is returned by the [`remote`](/docs/api/modules.md#remoteoptions-modifier) method. The session is initialized by the test runner. The same goes for ending the session. This is also done by the test runner process. ## Properties[​](#properties "Direct link to Properties") A browser object has the following properties: | Name | Type | Details | | ----------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `capabilities` | `Object` | Assigned capabilities from the remote server.<br />**Example:**``` { acceptInsecureCerts: false, browserName: 'chrome', browserVersion: '105.0.5195.125', chrome: { chromedriverVersion: '105.0.5195.52', userDataDir: '/var/folders/3_/pzc_f56j15vbd9z3r0j050sh0000gn/T/.com.google.Chrome.76HD3S' }, 'goog:chromeOptions': { debuggerAddress: 'localhost:64679' }, networkConnectionEnabled: false, pageLoadStrategy: 'normal', platformName: 'mac os x', proxy: {}, setWindowRect: true, strictFileInteractability: false, timeouts: { implicit: 0, pageLoad: 300000, script: 30000 }, unhandledPromptBehavior: 'dismiss and notify', 'webauthn:extension:credBlob': true, 'webauthn:extension:largeBlob': true, 'webauthn:virtualAuthenticators': true } ``` | | `requestedCapabilities` | `Object` | Capabilities requested from the remote server.<br />**Example:**``` { browserName: 'chrome' } ``` | | `sessionId` | `String` | Session id assigned from the remote server. | | `options` | `Object` | WebdriverIO [options](/docs/configuration.md) depending on how the browser object was created. See more [setup types](/docs/setuptypes.md). | | `commandList` | `String[]` | A list of commands registered to the browser instance | | `isChrome` | `Boolean` | Indicates if this Chrome instance | | `isFirefox` | `Boolean` | Indicates if this Firefox instance | | `isBidi` | `Boolean` | Indicates if this session uses Bidi | | `isSauce` | `Boolean` | Indicates if this session is Running on Sauce Labs | | `isMacApp` | `Boolean` | Indicates if this session is Running for a native Mac App | | `isWindowsApp` | `Boolean` | Indicates if this session is Running for a native Windows App | | `isMobile` | `Boolean` | Indicates a mobile session. See more under [Mobile Flags](#mobile-flags). | | `isIOS` | `Boolean` | Indicates an iOS session. See more under [Mobile Flags](#mobile-flags). | | `isAndroid` | `Boolean` | Indicates an Android session. See more under [Mobile Flags](#mobile-flags). | | `isNativeContext` | `Boolean` | Indicates if the mobile is in the `NATIVE_APP` context. See more under [Mobile Flags](#mobile-flags). | | `mobileContext` | `string` | The will provide the **current** context the driver is in, for example `NATIVE_APP`, `WEBVIEW_<packageName>` for Android or `WEBVIEW_<pid>` for iOS. It will save an extra WebDriver to `driver.getContext()`. See more under [Mobile Flags](#mobile-flags). | ## Methods[​](#methods "Direct link to Methods") Based on the automation backend used for your session, WebdriverIO identifies which [Protocol Commands](/docs/api/protocols.md) will be attached to the [browser object](/docs/api/browser.md). For example if you run an automated session in Chrome, you will have access to Chromium specific commands like [`elementHover`](/docs/api/chromium.md#elementhover) but not any of the [Appium commands](/docs/api/appium.md). Furthermore WebdriverIO provides a set of convenient methods that are recommended to use, to interact with the [browser](/docs/api/browser.md) or [elements](/docs/api/element.md) on the page. In addition to that the following commands are available: | Name | Parameters | Details | | -------------------- | ---------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `addCommand` | - `commandName` (Type: `String`)<br />- `fn` (Type: `Function`)<br />- `attachToElement` (Type: `boolean`) | Allows to define custom commands that can be called from the browser object for composition purposes. Read more in the [Custom Command](/docs/customcommands.md) guide. | | `overwriteCommand` | - `commandName` (Type: `String`)<br />- `fn` (Type: `Function`)<br />- `attachToElement` (Type: `boolean`) | Allows to overwrite any browser command with custom functionality. Use carefully as it can confuse framework users. Read more in the [Custom Command](/docs/customcommands.md#overwriting-native-commands) guide. | | `addLocatorStrategy` | - `strategyName` (Type: `String`)<br />- `fn` (Type: `Function`) | Allows to define a custom selector strategy, read more in the [Selectors](/docs/selectors.md#custom-selector-strategies) guide. | ## Remarks[​](#remarks "Direct link to Remarks") ### Mobile Flags[​](#mobile-flags "Direct link to Mobile Flags") If you need to modify your test based on whether or not your session runs on a mobile device, you can access the mobile flags to check. For example, given this config: ``` // wdio.conf.js export const config = { // ... capabilities: \\{ platformName: 'iOS', app: 'net.company.SafariLauncher', udid: '123123123123abc', deviceName: 'iPhone', // ... } // ... } ``` You can access these flags in your test like so: ``` // Note: `driver` is the equivalent to the `browser` object but semantically more correct // you can choose which global variable you want to use console.log(driver.isMobile) // outputs: true console.log(driver.isIOS) // outputs: true console.log(driver.isAndroid) // outputs: false ``` This can be useful if, for example, you want to define selectors in your [page objects](/docs/pageobjects.md) based on the device type, like this: ``` // mypageobject.page.js import Page from './page' class LoginPage extends Page { // ... get username() { const selectorAndroid = 'new UiSelector().text("Cancel").className("android.widget.Button")' const selectorIOS = 'UIATarget.localTarget().frontMostApp().mainWindow().buttons()[0]' const selectorType = driver.isAndroid ? 'android' : 'ios' const selector = driver.isAndroid ? selectorAndroid : selectorIOS return $(`${selectorType}=${selector}`) } // ... } ``` You can also use these flags to run only certain tests for certain device types: ``` // mytest.e2e.js describe('my test', () => { // ... // only run test with Android devices if (driver.isAndroid) { it('tests something only for Android', () => { // ... }) } // ... }) ``` ### Events[​](#events "Direct link to Events") The browser object is an EventEmitter and a couple of events are emitted for your use cases. Here is a list of events. Keep in mind that this is not the full list of available events yet. Feel free to contribute to update the document by adding descriptions of more events here. #### `command`[​](#command "Direct link to command") This event is emitted whenever WebdriverIO sends a WebDriver Classic command. It contains the following information: * `command`: the command name, e.g. `navigateTo` * `method`: the HTTP method used to send the command request, e.g. `POST` * `endpoint`: the command endpoint, e.g. `/session/fc8dbda381a8bea36a225bd5fd0c069b/url` * `body`: the command payload, e.g. `{ url: 'https://webdriver.io' }` #### `result`[​](#result "Direct link to result") This event is emitted whenever WebdriverIO receives a result of a WebDriver Classic command. It contains the same information as the `command` event with the addition of the following information: * `result`: the command result #### `bidiCommand`[​](#bidicommand "Direct link to bidicommand") This event is emitted whenever WebdriverIO sends a WebDriver Bidi command to the browser driver. It contains information about: * `method`: WebDriver Bidi command method * `params`: associated command parameter (see [API](/docs/api/webdriverBidi.md)) * `id`: the command id, the same as in the `bidiResult` event of this command #### `bidiResult`[​](#bidiresult "Direct link to bidiresult") In case of a successful command execution, the event payload will be: * `type`: `success` * `id`: the command id * `result`: the command result (see [API](/docs/api/webdriverBidi.md)) In case of a command error, the event payload will be: * `type`: `error` * `id`: the command id * `error`: the error code, e.g. `invalid argument` * `message`: details about the error * `stacktrace`: a stack trace #### `request.start`[​](#requeststart "Direct link to requeststart") This event is fired before a WebDriver request is sent to the driver. It contains information about the request and its payload. ``` browser.on('request.start', (ev: RequestInit) => { // ... }) ``` #### `request.end`[​](#requestend "Direct link to requestend") This event is fired once the request to the driver received a response. The event object either contains the response body as result or an error if the WebDriver command failed. ``` browser.on('request.end', (ev: { result: unknown, error?: Error }) => { // ... }) ``` #### `request.retry`[​](#requestretry "Direct link to requestretry") The retry event can notify you when WebdriverIO attempts to retry running the command, e.g. due to a network issue. It contains information about the error that caused the retry and the amount of retries already done. ``` browser.on('request.retry', (ev: { error: Error, retryCount: number }) => { // ... }) ``` #### `request.performance`[​](#requestperformance "Direct link to requestperformance") This is an event to measure WebDriver level operations. Whenever WebdriverIO sends a request to the WebDriver backend, this event will be emitted with some useful information: * `durationMillisecond`: Time duration of the request in millisecond. * `error`: Error object if the request failed. * `request`: Request object. You can find url, method, headers, etc. * `retryCount`: If it's `0`, the request was the first attempt. It will increase when WebDriverIO retries under the hood. * `success`: Boolean to represent the request was succeeded or not. If it's `false`, `error` property will be provided as well. An example event: ``` Object { "durationMillisecond": 0.01770925521850586, "error": [Error: Timeout], "request": Object { ... }, "retryCount": 0, "success": false, }, ``` ### Custom Commands[​](#custom-commands "Direct link to Custom Commands") You can set custom commands on the browser scope to abstract away workflows that are commonly used. Check out our guide on [Custom Commands](/docs/customcommands.md#adding-custom-commands) for more information. --- Source: https://webdriver.io/docs/api/browser/$$.md # $$ `$$` fetches every element that matches a selector. It returns a `WebdriverIO.ElementArray` immediately: a real array (`Array.isArray` is `true`) that stays thenable until the query finishes. `custom$$`, `react$$` and `shadow$$` return the same kind of list, including when you call them on an element (`$('parent').$$('child')`). Await the list when you want it resolved. `length` is then a number, each index is an element, and a normal `for...of` loop works: ``` const buttons = await $$('button') console.log(buttons.length) // 3 for (const button of buttons) { console.log(await button.getText()) } ``` The query does not run until something reads the list (`await`, `for await`, `.length`, an index, or an iterator method such as `map`). Until then: * `length` is a `Promise<number>`. Use `await $$('button').length`, not `$$('button').length > 0`. * `$$('button')[0]` is a chainable element, so `await $$('button')[0].getText()` works without awaiting the list first. * `for await (const button of $$('button'))` yields each element. * `for (const button of $$('button'))` throws `Cannot synchronously iterate over an element list that has not resolved yet`. Await the list first, or use `for await`. An index past the end of the list waits and refetches until `waitforTimeout`, the same way a missing single element does. That wait still happens after the list has resolved (`const items = await $$('li'); await items[items.length]`). A [`slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) or a `filter` does not: `$$('li').slice(0, 2)[3]` stays outside that window, and an index past a filtered list does not resolve to an element the filter excluded. `.at()` uses the same index conversion as a plain array, so `.at(1.5)` is element 1 and `.at(NaN)` is element 0. When the list still does not reach the index after that wait, the item is a "not found" element, like `$('.missing')`: `isDisplayed()` and `isExisting()` give `false`, and a matcher such as `expect($$('li')[5]).not.toBeDisplayed()` passes. A command that needs the element, for example `click()`, throws `Index out of bounds! $$(li) returned only 3 elements.` The index already waited, so that command does not wait a second time: it looks for the item once more, and uses it if the list now reaches the index. To wait for an item that can appear later, call `waitForExist()` or `expect(item).toExist()` before the command. Using the wdio testrunner this command is a global variable, see [Globals](https://webdriver.io/docs/api/globals) for more information. Using WebdriverIO within a [standalone](https://webdriver.io/docs/setuptypes#standalone-mode) script it will be located on the browser object instead (e.g. `browser.$$`). You can chain `$` or `$$` together without wrapping individual commands into `await` in order to walk down the DOM tree, e.g.: ``` const imageSrc = await $$('div')[1].nextElement().$$('img')[2].getAttribute('src') ``` ### Iterating over elements[​](#iterating-over-elements "Direct link to Iterating over elements") The list also provides asynchronous versions of the `Array` iteration methods `forEach`, `map`, `find`, `findIndex`, `some`, `every`, `filter` and `reduce`. They accept `async` callbacks and can be called on `$$` directly. `filter` and `filterSeries` return a new `ElementArray`, so the selector and the command that found the elements are kept: ``` const texts = await $$('h3').map((h3) => h3.getText()) for await (const img of $$('img')) { console.log(await img.getAttribute('src')) } ``` Every method except `reduce` also has a `*Series` variant (`forEachSeries`, `mapSeries`, and so on). The base method runs all callbacks **concurrently**, while the `*Series` variant runs **one callback at a time**, in list order. `reduce` always runs one callback at a time. Use a `*Series` variant when the order of your interactions with the page matters. The concurrent `find` and `findIndex` resolve with the first match to finish, which is not necessarily the earliest match in the list, and the concurrent `find`, `findIndex`, `some` and `every` keep running the remaining callbacks after the result is known. Use the `*Series` variant to get the earliest match and stop there. info For more information on how to select specific elements, check out the [Selectors](/docs/selectors.md) guide. ## Usage[​](#usage "Direct link to Usage") ``` await browser.$$(selector) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------- | ------------------ | -------------------------------------------------- | | `selector` | `String, Function` | selector or JS Function to fetch multiple elements | ## Examples[​](#examples "Direct link to Examples") example.html ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/59c122c809d44d343c231bde2af7e8456c8f086c/queryElements/example.html >) multipleElements.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/59c122c809d44d343c231bde2af7e8456c8f086c/queryElements/multipleElements.js#L6-L7 >) multipleElements.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/59c122c809d44d343c231bde2af7e8456c8f086c/queryElements/multipleElements.js#L15-L24 >) multipleElements.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/59c122c809d44d343c231bde2af7e8456c8f086c/queryElements/multipleElements.js#L32-L39 >) ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.ElementArray>** --- Source: https://webdriver.io/docs/api/browser/$.md # $ The `$` command is a short and handy way in order to fetch a single element on the page. You can also pass in an object as selector where the object contains a property `element-6066-11e4-a52e-4f735466cecf` with the value of a reference to an element. The command will then transform the reference to an extended WebdriverIO element. Note: chaining `$` and `$$` commands only make sense when you use multiple selector strategies. You will otherwise make unnecessary requests that slow down the test (e.g. `$('body').$('div')` will trigger two request whereas `$('body div')` does literally the same with just one request) **Note:** only use these element objects if you are certain they still exist on the page, e.g. using the `isExisting` command. WebdriverIO is unable to refetch them given that there are no selector information available. As of v10 this command is **strict**: if the selector resolves to more than one element it throws a `StrictSelectorError` rather than silently returning the first match. Use `$$` when you expect multiple elements, pass `{ strict: false }` to opt out for a single call, or set `strictSelectors: false` in your config to opt out globally. See the [Selectors](/docs/selectors.md#strict-mode) guide for details. Using the wdio testrunner this command is a global variable, see [Globals](https://webdriver.io/docs/api/globals) for more information. Using WebdriverIO within a [standalone](https://webdriver.io/docs/setuptypes#standalone-mode) script it will be located on the browser object instead (e.g. `browser.$$`). You can chain `$` or `$$` together without wrapping individual commands into `await` in order to walk down the DOM tree, e.g.: ``` const imageSrc = await $$('div')[1].nextElement().$$('img')[2].getAttribute('src') ``` info For more information on how to select specific elements, check out the [Selectors](/docs/selectors.md) guide. ## Usage[​](#usage "Direct link to Usage") ``` await browser.$(selector, { strict }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | -------------------------------- | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | `selector` | `String, Function, Matcher` | selector, JS Function, or Matcher object to fetch a certain element | | `options`<br />*optional* | `Object` | command options | | `options.strict`<br />*optional* | `Boolean` | throw if the selector matches more than one element (default: the `strictSelectors` config option, which defaults to `true`) | ## Examples[​](#examples "Direct link to Examples") example.html ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/59c122c809d44d343c231bde2af7e8456c8f086c/queryElements/example.html >) singleElements.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/59c122c809d44d343c231bde2af7e8456c8f086c/queryElements/singleElements.js#L9-L10 >) singleElements.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/59c122c809d44d343c231bde2af7e8456c8f086c/queryElements/singleElements.js#L16-L25 >) singleElements.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/59c122c809d44d343c231bde2af7e8456c8f086c/queryElements/singleElements.js#L42-L46 >) $.js ``` it('should use Androids DataMatcher or ViewMatcher selector', async () => { const menuItem = await $({ "name": "hasEntry", "args": ["title", "ViewTitle"], "class": "androidx.test.espresso.matcher.ViewMatchers" }); await menuItem.click(); const menuItem = await $({ "name": "hasEntry", "args": ["title", "ViewTitle"] }); await menuItem.click(); }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.Element>** --- Source: https://webdriver.io/docs/api/browser/action.md # action The action command is a low-level interface for providing virtualized device input actions to the web browser. For simple key presses, use [`browser.keys()`](https://webdriver.io/docs/api/browser/keys) instead. To perform multiple action chains at once, such as holding `Control` while clicking, use [`browser.actions()`](https://webdriver.io/docs/api/browser/actions). In addition to high level commands such like `scrollIntoView`, `doubleClick`, the Actions API provides granular control over exactly what designated input devices can do. WebdriverIO provides an interface for 3 kinds of input sources: * a key input for keyboard devices * a pointer input for a mouse, pen or touch devices * and wheel inputs for scroll wheel devices Every chain of action commands has to be completed calling `perform` in order to trigger the set of actions. This causes actions [to be released](https://w3c.github.io/webdriver/#release-actions) and events to be fired. You can skip this by passing in `true` (e.g. `browser.actions(...).perform(true)`). info Support for this command and specific actions can differ based on the environment. Progress on the development can be followed on [wpt.fyi](https://wpt.fyi/results/webdriver/tests/perform_actions?label=experimental\&label=master\&aligned). For mobile you might want to use Appium specific gesture commands on [iOS](https://appium.github.io/appium-xcuitest-driver/latest/guides/gestures/) and [Android](https://appium.github.io/appium-uiautomator2-driver/latest/reference/execute-methods/#gestures). ### Key input source[​](#key-input-source "Direct link to Key input source") A key input source is an input source that is associated with a keyboard-type device. It can be triggered by using the `key` type parameters. e.g.: ``` browser.action('key') ``` It returns a `KeyAction` object that supports the following actions: * `down(value: string)`: generates a key down action * `up(value: string)`: generates a key up action * `pause(ms: number)`: indicate that an input source does nothing during a particular tick #### Special Characters[​](#special-characters "Direct link to Special Characters") If you like to use special characters like e.g. `Control`, `Page Up` or `Shift`, make sure to import the [`Key`](/docs/api/modules.md#key) object from the `webdriverio` package like so: ``` import { Key } from 'webdriverio' ``` The `Key` object provides constants for all special keys including `Key.Ctrl` (cross-platform), `Key.Enter`, `Key.Tab`, `Key.ArrowLeft`, arrow keys, function keys, and more. See the [Key API docs](/docs/api/modules.md#key) for a complete list. ### Pointer input source[​](#pointer-input-source "Direct link to Pointer input source") A pointer input source is an input source that is associated with a pointer-type input device. The type can be specified when invoking the `action` command, e.g.: ``` browser.action('pointer', { parameters: { pointerType: 'mouse' } // "mouse" is default value, also possible: "pen" or "touch" }) ``` It returns a `PointerAction` object that supports the following actions: * `down (button: 'left' | 'middle' | 'right')`: creates an action to press a single key * `down (params: PointerActionParams)`: creates an action to press a single key with detailed parameters * `move (x: number, y: number)`: Creates an action for moving the pointer `x` and `y` pixels from the viewport * `move (params: PointerActionMoveParams)`: Creates an action for moving the pointer `x` and `y` pixels from the specified `origin`. The `origin` may be defined as the pointers current position (e.g. "pointer"), the viewport (e.g. "viewport") or the center of a specific element. * `up (button: 'left' | 'middle' | 'right')`: creates an action to release a single key * `up (params: PointerActionUpParams)`: creates an action to release a single key with detailed parameters * `cancel()`: An action that cancels this pointer's current input. * `pause(ms: number)`: indicate that an input source does nothing during a particular tick You can find detailed information on the [`PointerActionParams`](https://github.com/webdriverio/webdriverio/blob/8ca026c75bf7c27ef9d574f0ec48d8bc13658602/packages/webdriverio/src/utils/actions/pointer.ts#L20-L35), [`PointerActionMoveParams`](https://github.com/webdriverio/webdriverio/blob/8ca026c75bf7c27ef9d574f0ec48d8bc13658602/packages/webdriverio/src/utils/actions/pointer.ts#L20-L42) and [`PointerActionUpParams`](https://github.com/webdriverio/webdriverio/blob/8ca026c75bf7c27ef9d574f0ec48d8bc13658602/packages/webdriverio/src/utils/actions/pointer.ts#L13-L19) parameter types in the project type definition. ### Wheel input source[​](#wheel-input-source "Direct link to Wheel input source") A wheel input source is an input source that is associated with a wheel-type input device. ``` browser.action('wheel') ``` It returns a `WheelAction` object that supports the following actions: * `scroll (params: ScrollParams)`: scrolls a page to given coordinates or origin * `pause(ms: number)`: indicate that an input source does nothing during a particular tick You can find detailed information on the [`ScrollParams`](https://github.com/webdriverio/webdriverio/blob/8ca026c75bf7c27ef9d574f0ec48d8bc13658602/packages/webdriverio/src/utils/actions/wheel.ts#L4-L29) parameter type in the project type definition. ## Usage[​](#usage "Direct link to Usage") ``` browser.action() ``` ## Examples[​](#examples "Direct link to Examples") pointer-action.js ``` it('drag and drop using pointer action command', async () => { const origin = await $('#source') const targetOrigin = await $('#target') return browser.action('pointer') .move({ duration: 0, origin, x: 0, y: 0 }) .down({ button: 0 }) // left button .pause(10) .move({ duration: 0, origin: targetOrigin }) .up({ button: 0 }) .perform() }); ``` key-action.js ``` import { Key } from 'webdriverio' it('should emit key events using key action commands', async () => { const elem = await $('input') await elem.click() // make element active await browser.action('key') .down('f') .down('o') .down('o') .up('f') .up('o') .up('o') .perform() console.log(await elem.getValue()) // returns "foo" // copy value out of input element await browser.action('key') .down(Key.Ctrl).down('c') .pause(10) .up(Key.Ctrl).up('c') .perform() }) ``` wheel-action.js ``` it('should scroll using wheel action commands', async () => { console.log(await browser.execute(() => window.scrollY)) // returns 0 await browser.action('wheel').scroll({ deltaX: 0, deltaY: 500, duration: 200 }).perform() console.log(await browser.execute(() => window.scrollY)) // returns 500 }) ``` --- Source: https://webdriver.io/docs/api/browser/actions.md # actions Allows to run multiple action interactions at once, e.g. to simulate a pinch zoom or hold a modifier key while clicking. Build each action chain with [`browser.action()`](/docs/api/browser/action.md), then pass the chains to this command. ## Usage[​](#usage "Direct link to Usage") ``` await browser.actions() ``` ## Example[​](#example "Direct link to Example") action.js ``` it('run multiple actions at once for a pinch zoom', async () => { await browser.actions([ browser.action('pointer') .move(500, 500) .down() .move(250, 250) .up(), browser.action('pointer') .move(500, 500) .down() .move(750, 750) .up() ]) }); ``` --- Source: https://webdriver.io/docs/api/browser/addCommand.md # addCommand The browser method `addCommand` helps you to write your own set of commands. info You can find more information on adding custom commands in the [custom command](/docs/customcommands.md#adding-custom-commands) guide. ## Usage[​](#usage "Direct link to Usage") ``` browser.addCommand(name, callback, { attachToElement, disableElementImplicitWait }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------------------------------------------------- | ---------- | ------------------------------------------------------- | | `name` | `string` | name of the custom command | | `callback` | `Function` | function to be called | | `options`<br />*optional* | `Object` | options object with the following properties: | | `options.attachToElement`<br />*optional* | `Boolean` | extend the Element object instead of the Browser object | | `options.disableElementImplicitWait`<br />*optional* | `Boolean` | disable implicit wait for element commands | ## Example[​](#example "Direct link to Example") execute.js ``` // Basic usage with browser scope await browser.addCommand('getUrlAndTitle', async function (customParam) { // `this` refers to the `browser` scope return { url: await this.getUrl(), title: await this.getTitle(), customParam: customParam } }) // Element scope using options object (RECOMMENDED) await browser.addCommand('waitAndClick', async function () { // `this` refers to the `element` scope await this.waitForClickable() await this.click() }, { attachToElement: true }) // Advanced usage with options await browser.addCommand('fastClick', async function () { // `this` refers to the `element` scope await this.click() }, { attachToElement: true, disableElementImplicitWait: true // Skip implicit wait for faster execution }) //usage it('should use my add command', async () => { await browser.url('https://webdriver.io') const result = await browser.getUrlAndTitle('foobar') assert.strictEqual(result.url, 'https://webdriver.io') assert.strictEqual(result.title, 'WebdriverIO · Next-gen browser and mobile automation test framework for Node.js | WebdriverIO') assert.strictEqual(result.customParam, 'foobar') // Using element commands const element = await $('button') await element.waitAndClick() await element.fastClick() }) ``` --- Source: https://webdriver.io/docs/api/browser/addInitScript.md # addInitScript Adds a script which would be evaluated in one of the following scenarios: * Whenever the page is navigated. * Whenever the child frame is attached or navigated. In this case, the script is evaluated in the context of the newly attached frame. The script is evaluated after the document was created but before any of its scripts were run. In order to remove the initialization script from the page again, call the function that got returned by this function. This is useful to amend the JavaScript environment, e.g. to seed Math.random. ## Usage[​](#usage "Direct link to Usage") ``` await browser.addInitScript(script, args) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | -------- | ------------------------- | ------------------------------------------------ | | `script` | `Function` | function to be injected as initialization script | | `args` | `number, string, boolean` | parameters for the script | ## Examples[​](#examples "Direct link to Examples") addInitScript.js ``` const script = await browser.addInitScript((seed) => { Math.random = () => seed }, 42) await browser.url('https://webdriver.io') console.log(await browser.execute(() => Math.random())) // returns 42 await reset() await browser.url('https://webdriver.io') console.log(await browser.execute(() => Math.random())) // returns a random number hermore you can also use the `emit` function to send data back to the Node.js environment. is useful if you want to observe certain events in the browser environment, e.g.: ``` addInitScriptWithEmit.js ``` const script = await browser.addInitScript((emit) => { const observer = new MutationObserver((mutations) => { for (const mutation of mutations) { emit(mutation.target.nodeName) } }) observer.observe(document, { childList: true, subtree: true }) }) script.on('data', (data) => { console.log(data) // prints: BODY, DIV, P, ... }) ``` --- Source: https://webdriver.io/docs/api/browser/back.md # back Go one step back in the joint session history of the current top-level browsing context. This is equivalent to pressing the browser back button or calling `window.history.back()`. The command takes no arguments and resolves with no value. On a WebDriver BiDi session it calls [`browsingContext.traverseHistory`](https://w3c.github.io/webdriver-bidi/#command-browsingContext-traverseHistory) with `delta: -1` for the top-level context. A frame selected with [`switchFrame`](/docs/api/browser/switchFrame.md) does not change that target. After the traversal is accepted, the command waits for the same document readiness [`url`](/docs/api/browser/url.md) maps from `pageLoadStrategy`: * `none` does not wait * `eager` waits for `browsingContext.domContentLoaded` * `normal` (the default) waits for `browsingContext.load` The wait uses the session page-load timeout (`timeouts.pageLoad`, 300000 ms when it has not been set). A same-document traversal, such as a fragment change, finishes without a load event. A back-forward cache restore commits a document that is already complete and does not emit `browsingContext.load`; the command returns once that document's `readyState` matches the strategy. A classic session posts to the WebDriver [back](/docs/api/webdriver.md#back) endpoint. There is no previous entry in either mode when the command rejects with `no such history entry`. ## Usage[​](#usage "Direct link to Usage") ``` await browser.back() ``` ## Example[​](#example "Direct link to Example") back.js ``` it('should go back and forward', async () => { await browser.url('https://webdriver.io') await browser.url('https://webdriver.io/docs/gettingstarted') await browser.back() console.log(await browser.getUrl()) // outputs the first page await browser.forward() console.log(await browser.getUrl()) // outputs the second page }); ``` --- Source: https://webdriver.io/docs/api/browser/browsingContexts.md # browsingContexts Get every open tab and window of the session as a [browsing context](/docs/api/browsingContext.md), in the order the browser reports them. This includes tabs the page opened itself, e.g. through `target="_blank"` or `window.open()`. Frames are not in this list, get them with [`frame()`](/docs/api/browsingContext/frame.md) on their tab. Only available in a WebDriver BiDi session. ## Usage[​](#usage "Direct link to Usage") ``` await browser.browsingContexts() ``` ## Example[​](#example "Direct link to Example") browsingContexts.js ``` it('finds a tab the page opened', async () => { const page = await browser.url('https://the-internet.herokuapp.com/windows') await page.$('a[href="/windows/new"]').click() const tab = await browser.waitUntil(async () => ( (await browser.browsingContexts()).find((context) => context.url.endsWith('/windows/new')) )) console.log(await tab.$('h3').getText()) // outputs: "New Window" }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<BrowsingContext\[]>** **`return`:** the open tabs and windows --- Source: https://webdriver.io/docs/api/browser/call.md # call You can use `call` to execute any async action within your test spec. It accepts promises and stops the execution until the promise has been resolved. info With WebdriverIO deprecating synchronous usage (see [RFC](https://github.com/webdriverio/webdriverio/discussions/6702)) this command is not very useful anymore. ## Usage[​](#usage "Direct link to Usage") ``` await browser.call(callback) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------- | ---------- | --------------------- | | `callback` | `Function` | function to be called | ## Example[​](#example "Direct link to Example") call.js ``` it('some testing here', async () => { await browser.url('http://google.com') // make an asynchronous call using any 3rd party library supporting promises // e.g. call to backend or db to inject fixture data await browser.call(() => { return somePromiseLibrary.someMethod().then(() => { // ... }) }) // example for async call to 3rd party library that doesn't support promises const result = await browser.call(() => { return new Promise((resolve, reject) => { someOtherNodeLibrary.someMethod(param1, (err, res) => { if (err) { return reject(err) } resolve(res) }) }) }) }); ``` --- Source: https://webdriver.io/docs/api/browser/custom$$.md # custom$$ The `customs$$` allows you to use a custom strategy declared by using `browser.addLocatorStrategy`. It returns a [`WebdriverIO.ElementArray`](/docs/api/browser/$$.md), the same list as [`$$`](/docs/api/browser/$$.md): await it, or use `for await` and the async array methods before it resolves. Read more on custom selector strategies in the [Selector docs](/docs/selectors.md#custom-selector-strategies). ## Usage[​](#usage "Direct link to Usage") ``` await browser.custom$$(strategyName, strategyArguments) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------- | -------- | ------- | | `strategyName` | `string` | | | `strategyArguments` | `*` | | ## Example[​](#example "Direct link to Example") example.js ``` it('should get all the plugin wrapper buttons', async () => { await browser.url('https://webdriver.io') await browser.addLocatorStrategy('myStrategy', (selector) => { return document.querySelectorAll(selector) }) const pluginWrapper = await browser.custom$$('myStrategy', '.pluginWrapper') console.log(await pluginWrapper.length) // 4 }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.ElementArray>** --- Source: https://webdriver.io/docs/api/browser/custom$.md # custom$ The `custom$` allows you to use a custom strategy declared by using `browser.addLocatorStrategy`. Read more on custom selector stratgies in the [Selector docs](/docs/selectors.md#custom-selector-strategies). ## Usage[​](#usage "Direct link to Usage") ``` await browser.custom$(strategyName, strategyArguments) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------- | -------- | ------- | | `strategyName` | `string` | | | `strategyArguments` | `*` | | ## Examples[​](#examples "Direct link to Examples") customStrategy.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/f5730428ec3605e856e90bf58be17c9c9da891de/queryElements/customStrategy.js#L2-L11 >) example.html ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/f5730428ec3605e856e90bf58be17c9c9da891de/queryElements/example.html#L8-L12 >) customStrategy.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/f5730428ec3605e856e90bf58be17c9c9da891de/queryElements/customStrategy.js#L16-L19 >) example.js ``` it('should fetch the project title', async () => { await browser.url('https://webdriver.io') browser.addLocatorStrategy('myStrat', (selector) => { return document.querySelectorAll(selector) }) const projectTitle = await browser.custom$('myStrat', '.projectTitle') console.log(await projectTitle.getText()) // WEBDRIVER I/O }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.Element>** --- Source: https://webdriver.io/docs/api/browser/debug.md # debug This command helps you to debug your integration tests. It stops the running browser and gives you time to jump into it and check the state of your application (e.g. using dev tools). Your terminal transforms into a [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) interface that will allow you to try out certain commands, find elements and test actions on them. [![WebdriverIO REPL](https://webdriver.io/img/repl.gif)](https://webdriver.io/img/repl.gif) If you run the WDIO testrunner make sure you increase the timeout property of the test framework you are using (e.g. Mocha or Jasmine) in order to prevent test termination due to a test timeout. Also avoid executing the command with multiple capabilities running at the same time. ## Usage[​](#usage "Direct link to Usage") ``` await browser.debug() ``` ## Example[​](#example "Direct link to Example") debug.js ``` it('should demonstrate the debug command', async () => { await $('#input').setValue('FOO') await browser.debug() // jumping into the browser and change value of #input to 'BAR' const value = await $('#input').getValue() console.log(value) // outputs: "BAR" }) ``` --- Source: https://webdriver.io/docs/api/browser/deleteCookies.md # deleteCookies Delete cookies visible to the current page. By providing a cookie name it just removes the single cookie or more when multiple names are passed. With `wdio:experimentalBiDiCommands` and in a parallel test, the command uses the cookies of the window: it deletes the cookies that the page sees (domain and path) or, with a `domain` in the filter, the cookies of that domain, whatever page is open. Without a `domain` in the filter, it deletes no cookie on a page with no host (for example `about:blank`). ## Usage[​](#usage "Direct link to Usage") ``` await browser.deleteCookies(filter) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | -------- | ----------------------- | ------------------------------------------------------------------------------------------- | | `filter` | `StorageCookieFilter[]` | Use the filter property to identify and delete specific cookies based on matching criteria. | ## Examples[​](#examples "Direct link to Examples") example.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/deleteCookies/example.js#L9-L29 >) example.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/e8b147e88e7a38351b0918b4f7efbd9ae292201d/deleteCookies/example.js#L31-L35 >) --- Source: https://webdriver.io/docs/api/browser/downloadFile.md # downloadFile Download a file from the remote computer running Selenium node to local file system by using the [`downloadFile`](https://webdriver.io/docs/api/selenium#downloadFile) command. info Note that this command is only supported if you use a [Selenium Grid](https://www.selenium.dev/documentation/en/grid/) with Chrome, Edge or Firefox and have the `se:downloadsEnabled` flag set in the capabilities. ## Usage[​](#usage "Direct link to Usage") ``` await browser.downloadFile(fileName, targetDirectory) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ----------------- | -------- | --------------------------------- | | `fileName` | `string` | remote path to file | | `targetDirectory` | `string` | target location on local computer | --- Source: https://webdriver.io/docs/api/browser/emulate.md # emulate Emulation commands that take `contexts` require a top-level traversable. A held top-level context is its own target. On the browser it is the current top-level context, never a frame the user has switched into. ## Usage[​](#usage "Direct link to Usage") ``` await browser.emulate() ``` --- Source: https://webdriver.io/docs/api/browser/execute.md # execute Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. The executed script is assumed to be synchronous and the result of evaluating the script is returned to the client. An `async` function is awaited on both WebDriver Classic and BiDi, which replaces `executeAsync`. The script argument defines the script to execute in the form of a function body. The value returned by that function will be returned to the client. The function will be invoked with the provided args array and the values may be accessed via the arguments object in the order specified. Arguments may be any JSON-primitive, array, or JSON object. JSON objects that define a WebElement reference will be converted to the corresponding DOM element. Likewise, any WebElements in the script result will be returned to the client as WebElement JSON objects. BiDi sessions preserve `Blob` and `File` results. The value arrives in the test as a `Blob` or `File`; read it with `text()` or `arrayBuffer()`. A `Blob` or `File` nested in an array, plain object, class instance, `Map`, or `Set` is preserved the same way. A `FileList` that contains files is returned as an array of `File` objects. A cyclic reference inside a value that also contains a `Blob` or `File` is returned as `null`. ## Usage[​](#usage "Direct link to Usage") ``` await browser.execute(script, arguments) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------------------------- | ------------------ | ---------------------- | | `script` | `String, Function` | The script to execute. | | `arguments`<br />*optional* | `*` | script arguments | ## Examples[​](#examples "Direct link to Examples") execute.js ``` it('should inject javascript on the page', async () => { const result = await browser.execute((a, b, c, d) => { // browser context - you may not access client or console return a + b + c + d }, 1, 2, 3, 4) // node.js context - client and console are available console.log(result) // outputs: 10 }); ``` blob.js ``` it('should return a blob from the browser', async () => { const blob = await browser.execute(() => new Blob(['hello'], { type: 'text/plain' })) console.log(blob.type) // outputs: text/plain console.log(await blob.text()) // outputs: hello }); ``` ## Returns[​](#returns "Direct link to Returns") * **<\*>** **`return`:** The script result. --- Source: https://webdriver.io/docs/api/browser/forward.md # forward Go one step forward in the joint session history of the current top-level browsing context. This is equivalent to pressing the browser forward button or calling `window.history.forward()`. The command takes no arguments and resolves with no value. On a WebDriver BiDi session it calls [`browsingContext.traverseHistory`](https://w3c.github.io/webdriver-bidi/#command-browsingContext-traverseHistory) with `delta: 1` for the top-level context. A frame selected with [`switchFrame`](/docs/api/browser/switchFrame.md) does not change that target. After the traversal is accepted, the command waits for the same document readiness [`url`](/docs/api/browser/url.md) maps from `pageLoadStrategy`: * `none` does not wait * `eager` waits for `browsingContext.domContentLoaded` * `normal` (the default) waits for `browsingContext.load` The wait uses the session page-load timeout (`timeouts.pageLoad`, 300000 ms when it has not been set). A same-document traversal, such as a fragment change, finishes without a load event. A back-forward cache restore commits a document that is already complete and does not emit `browsingContext.load`; the command returns once that document's `readyState` matches the strategy. A classic session posts to the WebDriver [forward](/docs/api/webdriver.md#forward) endpoint. There is no next entry in either mode when the command rejects with `no such history entry`. ## Usage[​](#usage "Direct link to Usage") ``` await browser.forward() ``` ## Example[​](#example "Direct link to Example") forward.js ``` it('should go back and forward', async () => { await browser.url('https://webdriver.io') await browser.url('https://webdriver.io/docs/gettingstarted') await browser.back() await browser.forward() console.log(await browser.getUrl()) // outputs the second page }); ``` --- Source: https://webdriver.io/docs/api/browser/getCookies.md # getCookies Retrieve a [cookie](https://w3c.github.io/webdriver/webdriver-spec.html#cookies) visible to the current page. You can query a specific cookie by providing the cookie name or retrieve all. ## Usage[​](#usage "Direct link to Usage") ``` await browser.getCookies(filter, sourceOrigin) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | -------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | `remote.StorageCookieFilter` | an object that allows to filter for cookies with specific attributes | | `sourceOrigin` | `string, null` | an optional source origin to fetch cookies for, if not provided it will default to the current page's origin, if explicitly set to null it will fetch cookies without a partition (only supported in BiDi). With `wdio:experimentalBiDiCommands` and in a parallel test, the commands use the cookies of the window: without `sourceOrigin`, the cookies that the page sees (domain and path) or, with a `domain` in the filter, the cookies of that domain, with `sourceOrigin`, the WebDriver BiDi storage partition of that origin, and with null, all cookies of the window | ## Example[​](#example "Direct link to Example") getCookies.js ``` it('should return a cookie for me', async () => { await browser.setCookies([ {name: 'test', value: '123'}, {name: 'test2', value: '456'} ]) const testCookie = await browser.getCookies({ name: 'test' }) console.log(testCookie); // outputs: [{ name: 'test', value: '123' }] const allCookies = await browser.getCookies() console.log(allCookies); // outputs: // [ // { name: 'test', value: '123' }, // { name: 'test2', value: '456' } // ] // filter cookies by domain const stagingCookies = await browser.getCookies({ domain: 'staging.myapplication.com' }) }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<Cookie\[]>** **`return`:** requested cookies --- Source: https://webdriver.io/docs/api/browser/getPuppeteer.md # getPuppeteer Get the [Puppeteer Browser instance](https://pptr.dev/#?product=Puppeteer\&version=v5.1.0\&show=api-class-browser) to run commands with Puppeteer. Note that all Puppeteer commands are asynchronous by default so in order to interchange between sync and async execution make sure to wrap your Puppeteer calls within a `browser.call` commands as shown in the example. info Note that using Puppeteer requires support for Chrome DevTools protocol and e.g. can not be used when running automated tests in the cloud. Chrome DevTools protocol is not installed by default, use `npm install puppeteer-core` to install it. Find out more in the [Automation Protocols](/docs/automationProtocols.md) section. info Note: Puppeteer is currently **not** supported when running [component tests](/docs/component-testing.md). ## Usage[​](#usage "Direct link to Usage") ``` await browser.getPuppeteer() ``` ## Example[​](#example "Direct link to Example") getPuppeteer.test.js ``` it('should allow me to use Puppeteer', async () => { // WebDriver command await browser.url('https://webdriver.io') const puppeteerBrowser = await browser.getPuppeteer() // switch to Puppeteer const metrics = await browser.call(async () => { const pages = await puppeteerBrowser.pages() pages[0].setGeolocation({ latitude: 59.95, longitude: 30.31667 }) return pages[0].metrics() }) console.log(metrics.LayoutCount) // returns LayoutCount value }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<PuppeteerBrowser>** **`return`:** initiated puppeteer instance connected to the browser --- Source: https://webdriver.io/docs/api/browser/getWindowSize.md # getWindowSize Returns browser window size. ## Usage[​](#usage "Direct link to Usage") ``` await browser.getWindowSize() ``` ## Example[​](#example "Direct link to Example") getWindowSize.js ``` it('should return browser window size', async () => { const windowSize = await browser.getWindowSize(); console.log(windowSize); // outputs `{ width: 1280, height: 767 }` }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<Object>** **`return`:** `{ x, y, width, height }` for W3C or `{ width, height }` for non W3C browser --- Source: https://webdriver.io/docs/api/browser/installExtension.md # installExtension Same hosts `wdio session` treats as a local browser in `packages/wdio-session/src/actions/interact.ts`. ## Usage[​](#usage "Direct link to Usage") ``` await browser.installExtension() ``` --- Source: https://webdriver.io/docs/api/browser/keys.md # keys Send a sequence of key strokes to the "active" element. You can make an input element active by just clicking on it. To use special characters like "ArrowLeft", "Enter", or "Backspace", import the `Key` object from the WebdriverIO package: ``` import { Key } from 'webdriverio' ``` The `Key` object provides constants for all special keys including: * Navigation: `Key.ArrowLeft`, `Key.ArrowUp`, `Key.ArrowRight`, `Key.ArrowDown`, `Key.PageUp`, `Key.PageDown`, `Key.Home`, `Key.End` * Editing: `Key.Enter`, `Key.Tab`, `Key.Backspace`, `Key.Delete`, `Key.Insert` * Modifiers: `Key.Ctrl` (cross-platform), `Key.Shift`, `Key.Alt`, `Key.Control`, `Key.Command` * Function keys: `Key.F1` through `Key.F12` * Numpad: `Key.Numpad0` through `Key.Numpad9`, `Key.Multiply`, `Key.Add`, `Key.Subtract`, `Key.Divide` * And more: `Key.Escape`, `Key.Space`, `Key.Clear`, `Key.Pause`, etc. See the [Key API docs](/docs/api/modules.md#key) for a complete list. Modifier keys like `Control`, `Shift`, `Alt` and `Command` will stay pressed throughout the sequence and will be released at the end. To combine keyboard input with pointer actions, build separate input-source chains with [`browser.action()`](https://webdriver.io/docs/api/browser/action) and submit them together with [`browser.actions()`](https://webdriver.io/docs/api/browser/actions). Cross-Platform Modifier The `Key.Ctrl` constant provides a convenient way to use the "control" modifier across different operating systems. On macOS, it maps to the `Command` key, while on Windows and Linux it maps to the `Control` key. This is useful for keyboard shortcuts like select-all (`[Key.Ctrl, 'a']`), copy, or paste. ## Usage[​](#usage "Direct link to Usage") ``` await browser.keys(value) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------- | ------------------ | ------------------------------------------------------------------ | | `value` | `String, String[]` | The sequence of keys to type. An array or string must be provided. | ## Example[​](#example "Direct link to Example") keys.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/355434bdef13d29608d6d5fbfbeaa034c8a2aa74/keys/keys.js#L1-L17 >) --- Source: https://webdriver.io/docs/api/browser/mock.md # mock Mock the response of a request. You can define a mock based on a matching [URLPattern](https://developer.mozilla.org/en-US/docs/Web/API/URLPattern) and corresponding header and status code. Calling the mock method returns a stub object that you can use to modify the response of the web resource. With the stub object you can then either return a custom response or have the request fail. There are 3 ways to modify the response: * return a custom JSON object (for stubbing API request) * replace web resource with a local file (serve a modified JavaScript file) or * redirect resource to a different url info Note that using the `mock` command requires support for WebDriver Bidi. That is usually the case when running tests locally in a Chromium based browser or on Firefox as well as if you use a Selenium Grid v4 or higher. If you run tests in the cloud, make sure that your cloud provider supports WebDriver Bidi. info The `URLPattern` is an experimental technology and not yet supported in some environments, e.g. Node.js. We recommend to import [a polyfill](https://www.npmjs.com/package/urlpattern-polyfill) until the feature is more widely supported. info A second `mock` with the same URL pattern and the same filter options replaces the first one: the first mock is restored, so it no longer changes requests or records calls. In a URL pattern, `*` already matches any characters, `/` included, and in a string pattern WebdriverIO changes `**` to `*`: `'**' + '/api'` and `'*' + '/api'` are the same pattern. To keep both mocks, give them different filter options. WebdriverIO does not change a `URLPattern` object: use a single `*` in it, as repeated wildcards before fixed text can make the match very slow and freeze a test. info On a [multi-remote](https://webdriver.io/docs/multiremote) browser, `mock` returns a [`MultiRemoteMock`](https://webdriver.io/docs/api/mock#multi-remote) instead of a single mock. `instances` lists the browser names, `getInstance(name)` returns that browser's mock, and `respond()`, `restore()`, and the other mock methods run on every instance. Captured requests stay on each mock: `mock.getInstance('myChromeBrowser').calls`. ## Usage[​](#usage "Direct link to Usage") ``` await browser.mock(url, { method, requestHeaders, responseHeaders, postData, statusCode }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ----------------------------------------------- | -------------------- | -------------------------------------------- | | `url` | `String, URLPattern` | url to mock | | `filterOptions`<br />*optional* | `MockFilterOptions` | filter mock resource by additional options | | `filterOptions.method`<br />*optional* | `String, Function` | filter resource by HTTP method | | `filterOptions.requestHeaders`<br />*optional* | `Object, Function` | filter resource by specific request headers | | `filterOptions.responseHeaders`<br />*optional* | `Object, Function` | filter resource by specific response headers | | `filterOptions.postData`<br />*optional* | `String, Function` | filter resource by request postData | | `filterOptions.statusCode`<br />*optional* | `Number, Function` | filter resource by response statusCode | ## Example[​](#example "Direct link to Example") mock.js ``` it('should mock network resources', async () => { // via static string const userListMock = await browser.mock('*' + '/users/list') // you can also specifying the mock even more by filtering resources // by request or response headers, status code, postData, e.g. mock only responses with specific // header set and statusCode const strictMock = await browser.mock('*', { // mock all json responses statusCode: 200, requestHeaders: { 'Content-Type': 'application/json' }, responseHeaders: { 'Cache-Control': 'no-cache' }, postData: 'foobar' }) // comparator function const apiV1Mock = await browser.mock('*' + '/api/v1', { statusCode: (statusCode) => statusCode >= 200 && statusCode <= 203, requestHeaders: (headers) => headers['Authorization'] && headers['Authorization'].startsWith('Bearer '), responseHeaders: (headers) => headers['Impersonation'], postData: (data) => typeof data === 'string' && data.includes('foo') }) }) it('should modify API responses', async () => { // filter by method const todoMock = await browser.mock('*' + '/todos', { method: 'get' }) // mock an endpoint with a fixed fixture todoMock.respond([{ title: 'Injected Todo', order: null, completed: false, url: "http://todo-backend-express-knex.herokuapp.com/916" }]) // respond with different status code or header todoMock.respond([{ title: 'Injected Todo', order: null, completed: false, url: "http://todo-backend-express-knex.herokuapp.com/916" }], { statusCode: 404, headers: { 'x-custom-header': 'foobar' } }) }) it('should modify text assets', async () => { const scriptMock = await browser.mock('*' + '/script.min.js') scriptMock.respond('./tests/fixtures/script.js') }) it('should redirect web resources', async () => { const headerMock = await browser.mock('*' + '/header.png') headerMock.respond('https://media.giphy.com/media/F9hQLAVhWnL56/giphy.gif') const pageMock = await browser.mock('https://google.com/') pageMock.respond('https://webdriver.io') await browser.url('https://google.com') console.log(await browser.getTitle()) // returns "WebdriverIO · Next-gen browser and mobile automation test framework for Node.js" }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<Mock>** **`return`:** a mock object to modify the response --- Source: https://webdriver.io/docs/api/browser/mockClearAll.md # mockClearAll Resets all information stored in all registered mocks of the session. On a browsing context, it resets only the mocks made for that tab or window. Inside a parallel test, it resets only the mocks that the test created, also on tabs it opened. ## Usage[​](#usage "Direct link to Usage") ``` await browser.mockClearAll() ``` ## Example[​](#example "Direct link to Example") mockClearAll.js ``` it('should clear all mocks', async () => { const docMock = await browser.mock('**', { headers: { 'Content-Type': 'text/html' } }) const jsMock = await browser.mock('**', { headers: { 'Content-Type': 'application/javascript' } }) await browser.url('https://guinea-pig.webdriver.io/') console.log(docMock.calls.length, jsMock.calls.length) // returns "1 4" await browser.url('https://guinea-pig.webdriver.io/') console.log(docMock.calls.length, jsMock.calls.length) // returns "2 4" (JavaScript comes from cache) await browser.mockClearAll() console.log(docMock.calls.length, jsMock.calls.length) // returns "0 0" }) ``` --- Source: https://webdriver.io/docs/api/browser/mockRestoreAll.md # mockRestoreAll Restores all mock information and behavior stored in all registered mocks of the session. On a browsing context, it restores only the mocks made for that tab or window. Inside a parallel test, it restores only the mocks that the test created, also on tabs it opened. ## Usage[​](#usage "Direct link to Usage") ``` await browser.mockRestoreAll() ``` ## Example[​](#example "Direct link to Example") mockRestoreAll.js ``` it('should restore all mocks', async () => { const googleMock = await browser.mock('https://google.com/') googleMock.respond('https://webdriver.io') const wdioMock = await browser.mock('https://webdriver.io') wdioMock.respond('http://json.org') await browser.url('https://google.com/') console.log(await browser.getTitle()) // JSON await browser.mockRestoreAll() await browser.url('https://google.com/') console.log(await browser.getTitle()) // Google }) ``` --- Source: https://webdriver.io/docs/api/browser/navigateInContext.md # navigateInContext The desired state the requested resource should be in before finishing the command. ## Usage[​](#usage "Direct link to Usage") ``` await browser.navigateInContext() ``` --- Source: https://webdriver.io/docs/api/browser/newWindow.md # newWindow Open a new window or tab and wait until its page has loaded, the equivalent of `window.open()`. This command does not work in mobile environments. In a WebDriver BiDi session (the default since v10) it returns the new [browsing context](/docs/api/browsingContext.md) and does not switch to it: run commands on the returned context, while `browser.url()` keeps navigating the first one. In a WebDriver Classic session the command switches to the new window and returns `{ handle, type }`. ## Usage[​](#usage "Direct link to Usage") ``` await browser.newWindow(url, { type, referenceContext }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------------------------ | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `url` | `string` | website URL to open | | `options`<br />*optional* | `NewWindowOptions` | newWindow command options | | `options.type`<br />*optional* | `string` | type of new window: 'tab' or 'window' | | `options.referenceContext`<br />*optional* | `string, BrowsingContext` | top-level browsing context to open the new tab or window from (BiDi only). In parallel mode, the default is the window of the test | ## Example[​](#example "Direct link to Example") newWindow\.js ``` it('should open a new tab', async () => { const page = await browser.url('https://webdriver.io') const tab = await browser.newWindow('https://webdriver.io/docs/api', { type: 'tab' }) console.log(await tab.getTitle()) // the title of the API page console.log(await page.getTitle()) // the first tab still answers commands await tab.closeWindow() }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<BrowsingContext|Object>** **`return`:** In a BiDi session, the new browsing context. In a Classic session, `{handle, type}`. ## Throws[​](#throws "Direct link to Throws") * **Error**: If `url` is invalid, if the command is used on mobile, or `type` is not 'tab' or 'window'. --- Source: https://webdriver.io/docs/api/browser/overwriteCommand.md # overwriteCommand The browser method `overwriteCommand` helps you to overwrite the browser's and element's native commands like `pause` and `click`. info You can view more information on this in the [custom command](/docs/customcommands.md#overwriting-native-commands) section. ## Usage[​](#usage "Direct link to Usage") ``` browser.overwriteCommand(name, callback, { attachToElement }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ----------------------------------------- | ---------- | ------------------------------------------------------- | | `name` | `string` | name of the original command | | `callback` | `Function` | pass original function | | `options`<br />*optional* | `Object` | options object | | `options.attachToElement`<br />*optional* | `Boolean` | extend the Element object instead of the Browser object | ## Example[​](#example "Direct link to Example") execute.js ``` // print milliseconds before pause and return its value. await browser.overwriteCommand('pause', function (origPauseFunction, ms) { console.log(`Sleeping for ${ms}`) origPauseFunction(ms) return ms }) // overwrite an element command await browser.overwriteCommand('click', function (origClickFunction) { console.log('clicking') return origClickFunction() }, { attachToElement: true }) // usage it('should use my overwrite command', async () => { await browser.url('https://webdriver.io') await browser.pause(1000) // outputs "Sleeping for 1000" }) ``` --- Source: https://webdriver.io/docs/api/browser/pause.md # pause Pauses execution for a specific amount of time. It is recommended to not use this command to wait for an element to show up. In order to avoid flaky test results it is better to use commands like [`waitForExist`](/docs/api/element/waitForExist.md) or other waitFor\* commands. ## Usage[​](#usage "Direct link to Usage") ``` await browser.pause(milliseconds) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | -------------- | -------- | ---------- | | `milliseconds` | `number` | time in ms | ## Example[​](#example "Direct link to Example") pause.js ``` it('should pause the execution', async () => { const starttime = new Date().getTime() await browser.pause(3000) const endtime = new Date().getTime() console.log(endtime - starttime) // outputs: 3000 }); ``` --- Source: https://webdriver.io/docs/api/browser/react$$.md # react$$ The `react$$` command is a useful command to query multiple React Components by their actual name and filter them by props and state. It returns a [`WebdriverIO.ElementArray`](/docs/api/browser/$$.md), the same list as [`$$`](/docs/api/browser/$$.md). info The command works with applications using React v16 to v19, with `createRoot` or `ReactDOM.render`. Read more about React selectors in the [Selectors](/docs/selectors.md#react-selectors) guide. ## Usage[​](#usage "Direct link to Usage") ``` await browser.react$$(selector, { props, state }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------------- | --------------------------------------------- | -------------------------------------- | | `selector` | `string` | of React component | | `options`<br />*optional* | `ReactSelectorOptions` | React selector options | | `options.props`<br />*optional* | `Object` | React props the element should contain | | `options.state`<br />*optional* | `Array<any>, number, string, object, boolean` | React state the element should be in | ## Example[​](#example "Direct link to Example") pause.js ``` it('should calculate 7 * 6', async () => { await browser.url('https://ahfarmer.github.io/calculator/'); const orangeButtons = await browser.react$$('t', { props: { orange: true } }) console.log(await orangeButtons.map((btn) => btn.getText())); // prints "[ '÷', 'x', '-', '+', '=' ]" }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.ElementArray>** --- Source: https://webdriver.io/docs/api/browser/react$.md # react$ The `react$` command is a useful command to query React Components by their actual name and filter them by props and state. info The command works with applications using React v16 to v19, with `createRoot` or `ReactDOM.render`. Read more about React selectors in the [Selectors](/docs/selectors.md#react-selectors) guide. ## Usage[​](#usage "Direct link to Usage") ``` await browser.react$(selector, { props, state }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------------- | --------------------------------------------- | -------------------------------------- | | `selector` | `string` | of React component | | `options`<br />*optional* | `ReactSelectorOptions` | React selector options | | `options.props`<br />*optional* | `Object` | React props the element should contain | | `options.state`<br />*optional* | `Array<any>, number, string, object, boolean` | React state the element should be in | ## Example[​](#example "Direct link to Example") pause.js ``` it('should calculate 7 * 6', async () => { await browser.url('https://ahfarmer.github.io/calculator/'); const appWrapper = await $('div#root') await browser.react$('t', { props: { name: '7' } }).click() await browser.react$('t', { props: { name: 'x' } }).click() await browser.react$('t', { props: { name: '6' } }).click() await browser.react$('t', { props: { name: '=' } }).click() console.log(await $('.component-display').getText()); // prints "42" }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.Element>** --- Source: https://webdriver.io/docs/api/browser/reloadSession.md # reloadSession Creates a new Selenium session with your current capabilities. This is useful if you test highly stateful application where you need to clean the browser session between the tests in your spec file to avoid creating hundreds of single test files with WDIO. Be careful though, this command affects your test time tremendously since spawning new Selenium sessions is very time consuming especially when using cloud services. Connection parameters such as hostname, port, protocol, etc. can be added along side browserName when you want to connect to a different remote service. This is useful in a situation, for example, where you start a test in native app and need to verify data in web app. If you start from remote service, you can pass in 0.0.0.0 for hostname if you want to switch to local drivers. The mocks of the old session are restored before it ends: they stop answering requests and their recorded `calls` are cleared, so assertions like `toBeRequested()` on such a mock fail after the reload. Create the mocks you need again after `reloadSession()`. ## Usage[​](#usage "Direct link to Usage") ``` await browser.reloadSession(newCapabilities) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------------------------------- | -------------------------- | ----------------------------------------- | | `newCapabilities`<br />*optional* | `WebdriverIO.Capabilities` | new capabilities to create a session with | ## Example[​](#example "Direct link to Example") reloadSync.js ``` it('should reload my session with current capabilities', async () => { console.log(browser.sessionId) // outputs: e042b3f3cd5a479da4e171825e96e655 await browser.reloadSession() console.log(browser.sessionId) // outputs: 9a0d9bf9d4864160aa982c50cf18a573 }) it('should reload my session with new capabilities', async () => { console.log(browser.capabilities.browserName) // outputs: chrome await browser.reloadSession({ browserName: 'firefox' }) console.log(browser.capabilities.browserName) // outputs: firefox }) it('should reload my session with new remote', async () => { console.log(browser.capabilities.browserName) // outputs: chrome await browser.reloadSession({ protocol: 'https', host: '0.0.0.1', port: 4444, path: '/wd/hub', browserName: 'firefox' }) console.log(browser.capabilities.browserName) // outputs: firefox }) ``` --- Source: https://webdriver.io/docs/api/browser/restore.md # restore This command restores specific or all emulated behaviors that were set using the `emulate` command. ## Usage[​](#usage "Direct link to Usage") ``` await browser.restore() ``` ## Example[​](#example "Direct link to Example") restore.js ``` before(async () => { await browser.emulate('geolocation', { latitude: 52.52, longitude: 13.405 }) await browser.emulate('userAgent', 'foobar') await browser.emulate('colorScheme', 'dark') await browser.emulate('onLine', false) }) it('should restore all emulated behavior', async () => { await browser.url('https://webdriver.io') // test within an emulated environment... }) after(async () => { // restore all emulated behavior await browser.restore() // or only restore specific emulated behavior // await browser.restore(['geolocation', 'userAgent']) }) ``` --- Source: https://webdriver.io/docs/api/browser/savePDF.md # savePDF Prints the page of the current browsing context to a PDF file on your OS. `savePDF(filepath, options?)` writes the PDF and returns the same bytes as a `Buffer`. `filepath` is resolved from the execution directory and must end with `.pdf`. A WebDriver BiDi session (`browser.isBidi`) renders the PDF with [`browsingContext.print`](https://w3c.github.io/webdriver-bidi/#command-browsingContext-print). That is how Chrome, Edge, and Firefox print, headed and headless. Headed and headless Chrome both return a non-empty PDF on this path. Only options you set are sent, so the browser keeps its defaults for the rest. `context` is the current top-level browsing context. If the browser rejects the command with `unsupported operation`, that error is returned as-is. The command does not fall back to Classic `printPage`. A WebDriver Classic session renders the PDF with [`printPage`](https://w3c.github.io/webdriver/#print-page). Chrome's Classic endpoint was limited to [headless mode](/docs/capabilities.md#run-browser-headless) ([crbug 753118](https://bugs.chromium.org/p/chromium/issues/detail?id=753118)). That limit is specific to Classic `printPage`. Current Chrome can also print from a headed Classic session; an older Chrome that still refuses it should use a BiDi session or run Classic Chrome headless. Lengths are centimeters. Defaults match both protocols: `portrait`, scale `1`, background `false`, shrink-to-fit `true`, page `21.59` × `27.94` cm, and margins of `1` cm. `pageRanges` entries are page numbers or range strings such as `'1-3'`. ## Usage[​](#usage "Direct link to Usage") ``` await browser.savePDF(filepath, { orientation, scale, background, width, height, top, bottom, left, right, shrinkToFit, pageRanges }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------------------- | ----------------------- | ----------------------------------------------------------------------------------------- | | `filepath` | `string` | path to the generated PDF (`.pdf` suffix is required) relative to the execution directory | | `options`<br />*optional* | `PDFPrintOptions` | print options, in centimeters | | `options.orientation`<br />*optional* | `string` | page orientation: `portrait` or `landscape`. Default: `portrait` | | `options.scale`<br />*optional* | `number` | page scale from `0.1` to `2`. Default: `1` | | `options.background`<br />*optional* | `boolean` | include the page background. Default: `false` | | `options.width`<br />*optional* | `number` | page width in cm. Default: `21.59` | | `options.height`<br />*optional* | `number` | page height in cm. Default: `27.94` | | `options.top`<br />*optional* | `number` | top margin in cm. Default: `1` | | `options.bottom`<br />*optional* | `number` | bottom margin in cm. Default: `1` | | `options.left`<br />*optional* | `number` | left margin in cm. Default: `1` | | `options.right`<br />*optional* | `number` | right margin in cm. Default: `1` | | `options.shrinkToFit`<br />*optional* | `boolean` | shrink the page to fit. Default: `true` | | `options.pageRanges`<br />*optional* | `Array<string, number>` | pages to include, as numbers or range strings such as `'1-3'`. Default: `[]` | ## Example[​](#example "Direct link to Example") savePDF.js ``` it('should save a PDF of the browser view', async () => { const pdf = await browser.savePDF('./some/path/page.pdf'); console.log(pdf.subarray(0, 5).toString()); // outputs: "%PDF-" }); it('should save a landscape PDF with a custom margin', async () => { await browser.savePDF('./some/path/landscape.pdf', { orientation: 'landscape', left: 2 }); }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<Buffer>** **`return`:** PDF buffer ## Throws[​](#throws "Direct link to Throws") * **Error**: if `filepath` is not a string ending in `.pdf`, or if `orientation` is not `portrait` or `landscape` --- Source: https://webdriver.io/docs/api/browser/saveRecordingScreen.md # saveRecordingScreen Save a video started by [`startRecordingScreen`](/docs/api/appium.md#startrecordingscreen) command to file. info This command is only supported for mobile sessions running on [Appium](https://appium.github.io/appium.io/docs/en/commands/device/recording-screen/start-recording-screen/). ## Usage[​](#usage "Direct link to Usage") ``` await browser.saveRecordingScreen(filepath) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------- | -------- | ----------------------------------------------------------------------- | | `filepath` | `String` | full or relative to the execution directory path to the generated video | ## Example[​](#example "Direct link to Example") saveRecordingScreen.js ``` it('should save a video', async () => { await browser.startRecordingScreen() await $('~BUTTON').click() await browser.saveRecordingScreen('./some/path/video.mp4') }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<Buffer>** **`return`:** video buffer --- Source: https://webdriver.io/docs/api/browser/saveScreenshot.md # saveScreenshot Save a screenshot of the current browsing context to a PNG file on your OS. Be aware that some browser drivers take screenshots of the whole document (e.g. Geckodriver with Firefox) and others only of the current viewport (e.g. Chromedriver with Chrome). ## Usage[​](#usage "Direct link to Usage") ``` await browser.saveScreenshot(filepath, { fullPage, format, quality, clip }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------------------------------------- | --------- | ------------------------------------------------------------------------------------------- | | `filepath` | `String` | path to the generated image (`.png` suffix is required) relative to the execution directory | | `options` | `Object` | screenshot options | | `options.fullPage=false`<br />*optional* | `Boolean` | whether to take a screenshot of the full page or just the current viewport | | `options.format='png'`<br />*optional* | `String` | the format of the screenshot (either `png` or `jpeg`) | | `options.quality=100`<br />*optional* | `Number` | the quality of the screenshot in case of JPEG format in range 0-100 percent | | `options.clip`<br />*optional* | `Object` | clipping a rectangle of the screenshot | ## Examples[​](#examples "Direct link to Examples") saveScreenshot.js ``` it('should save a screenshot of the browser viewport', async () => { await browser.saveScreenshot('./some/path/screenshot.png'); }); it('should save a screenshot of the full page', async () => { await browser.saveScreenshot('./some/path/screenshot.png', { fullPage: true }); }); it('should save a screenshot of a specific rectangle', async () => { await browser.saveScreenshot('./some/path/screenshot.png', { clip: { x: 0, y: 0, width: 100, height: 100 } }); }); it('should save a screenshot of the full page in JPEG format', async () => { await browser.saveScreenshot('./some/path/screenshot.jpeg', { fullPage: true, format: 'jpeg' }); }); it('should save a screenshot of the full page in JPEG format with quality 50', async () => { await browser.saveScreenshot('./some/path/screenshot.jpeg', { fullPage: true, format: 'jpeg', quality: 50 }); }); running from a hook, make sure to explicitly define the hook as async: ``` wdio.conf.js ``` afterTest: async function(test) { await browser.saveScreenshot('./some/path/screenshot.png'); } ``` ## Returns[​](#returns "Direct link to Returns") * **\<Buffer>** **`return`:** screenshot buffer --- Source: https://webdriver.io/docs/api/browser/scroll.md # scroll Scroll within the browser viewport. Note that `x` and `y` coordinates are relative to the current scroll positon, therefore `browser.scroll(0, 0)` is a non operation. ## Usage[​](#usage "Direct link to Usage") ``` await browser.scroll(x, y) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------------------- | -------- | ----------------------------------------- | | `x=0`<br />*optional* | `number` | horizontal scroll position (default: `0`) | | `y=0`<br />*optional* | `number` | vertical scroll position (default: `0`) | ## Example[​](#example "Direct link to Example") scroll.js ``` it('should demonstrate the scroll command', async () => { await browser.url('https://webdriver.io') console.log(await browser.execute(() => window.scrollY)) // returns 0 await browser.scroll(0, 200) console.log(await browser.execute(() => window.scrollY)) // returns 200 }); ``` --- Source: https://webdriver.io/docs/api/browser/setCookies.md # setCookies Sets one or more [cookies](https://w3c.github.io/webdriver/#cookies) for the current page. Make sure you are on the page that should receive the cookie. You can't set a cookie for an arbitrary page without being on that page. ## Usage[​](#usage "Direct link to Usage") ``` await browser.setCookies({ name, value, path, domain, secure, httpOnly, expiry, sameSite }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------------------------------- | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `cookie` | `Array<WebDriverCookie>, WebDriverCookie` | cookie object or object array. | | `cookie.name`<br />*optional* | `String` | The name of the cookie. | | `cookie.value`<br />*optional* | `String` | The cookie value. | | `cookie.path`<br />*optional* | `String` | The cookie path. Defaults to "/" if omitted when adding a cookie. | | `cookie.domain`<br />*optional* | `String` | The domain the cookie is visible to. Defaults to the current browsing context’s active document’s URL domain if omitted when adding a cookie. With `wdio:experimentalBiDiCommands` and in a parallel test, the domain goes to WebDriver BiDi as given: `example.com` is a host-only cookie, `.example.com` also goes to the subdomains. | | `cookie.secure`<br />*optional* | `Boolean` | Whether the cookie is a secure cookie. Defaults to false if omitted when adding a cookie. | | `cookie.httpOnly`<br />*optional* | `Boolean` | Whether the cookie is an HTTP only cookie. Defaults to false if omitted when adding a cookie. | | `cookie.expiry`<br />*optional* | `Number` | When the cookie expires, specified in seconds since Unix Epoch. Must not be set if omitted when adding a cookie. | | `cookie.sameSite`<br />*optional* | `String` | Whether the cookie applies to a SameSite policy. Defaults to None if omitted when adding a cookie. Can be set to "Lax", "Strict" or "None", in any case. | ## Example[​](#example "Direct link to Example") setCookies.js ``` it('should set a cookie for the page', async () => { await browser.url('/') // set a single cookie await browser.setCookies({ name: 'test1', value: 'one' // The below options are optional // path: '/foo', // The cookie path. Defaults to "/" // domain: '.example.com', // The domain the cookie is visible to. Defaults to the current browsing context’s active document’s URL domain // secure: true, // Whether the cookie is a secure cookie. Defaults to false // httpOnly: true, // Whether the cookie is an HTTP only cookie. Defaults to false // expiry: 1551393875 // When the cookie expires, specified in seconds since Unix Epoch }) // set multiple cookies await browser.setCookies([ {name: 'test2', value: 'two'}, {name: 'test3', value: 'three'} ]) const cookies = await browser.getCookies() console.log(cookies); // outputs: // [ // {name: 'test1', value: 'one', domain: 'www.example.com'}, // {name: 'test2', value: 'two', domain: 'www.example.com'}, // {name: 'test3', value: 'three', domain: 'www.example.com'} // ] }); ``` --- Source: https://webdriver.io/docs/api/browser/setTimeout.md # setTimeout Sets the timeouts associated with the current session, timeout durations control such behaviour as timeouts on script injection, document navigation, and element retrieval. For more information and examples, see [timeouts guide](https://webdriver.io/docs/timeouts#selenium-timeouts). info It is not recommended to set `implicit` timeouts as they impact WebdriverIO's behavior and can cause errors in certain commands, e.g. `waitForExist` with reverse flag. WebDriver BiDi has no script timeout, so in a BiDi session WebdriverIO applies the `script` timeout to [`execute`](/docs/api/browser/execute.md) itself: a script that does not finish in time fails with a `script timeout` error, as with WebDriver Classic. Every BiDi command also stops after [`bidiResponseTimeout`](/docs/configuration.md#bidiresponsetimeout) (180 seconds by default), so a longer `script` timeout needs a longer `bidiResponseTimeout` too. ## Usage[​](#usage "Direct link to Usage") ``` await browser.setTimeout({ implicit, pageLoad, script }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ----------------------------------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `timeouts` | `Timeouts` | Object containing session timeout values | | `timeouts.implicit`<br />*optional* | `Number` | Time in milliseconds to retry the element location strategy when finding an element. | | `timeouts.pageLoad`<br />*optional* | `Number` | Time in milliseconds to wait for the document to finish loading. | | `timeouts.script`<br />*optional* | `Number` | Scripts injected with [`execute`](https://webdriver.io/docs/api/browser/execute) will run until they hit the script timeout duration, which is also given in milliseconds. Async functions are awaited and count against this timeout. | ## Example[​](#example "Direct link to Example") setTimeout.js ``` it('should change timeout duration for session with long code duration', async () => { await browser.setTimeout({ 'pageLoad': 10000, 'script': 60000 }); // Execute code which takes a long time await browser.execute(async () => { console.log('Wake me up before you go!'); await new Promise((resolve) => setTimeout(resolve, 59000)); }); }); ``` --- Source: https://webdriver.io/docs/api/browser/setViewport.md # setViewport Resizes the browser viewport within the browser. As oppose to `setWindowSize`, this command changes the viewport size, not the window size. ## Usage[​](#usage "Direct link to Usage") ``` await browser.setViewport({ width, height, devicePixelRatio }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | -------------------------- | -------------------- | --------------------------- | | `options` | `SetViewportOptions` | command arguments | | `options.width` | `number` | viewport width in pixels | | `options.height` | `number` | viewport height in pixels | | `options.devicePixelRatio` | `number` | pixel ratio of the viewport | ## Returns[​](#returns "Direct link to Returns") * **<`Promise<void>`>** --- Source: https://webdriver.io/docs/api/browser/setWindowSize.md # setWindowSize Resizes browser window outer size according to provided width and height. Based on your operating system some browser windows might now allow you so have a smaller width than `500px`. If you want to mimic the viewport of e.g. an iPhone you should consider using the `setViewport` command. ## Usage[​](#usage "Direct link to Usage") ``` await browser.setWindowSize(width, height) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | -------- | -------- | ------------------------------------------ | | `width` | `number` | browser will be resized to provided width | | `height` | `number` | browser will be resized to provided height | ## Returns[​](#returns "Direct link to Returns") * **\<Null|Object>** **`return`:** Null for *NO*W3C browser and Object `{x, y, width, height}` for W3C browser --- Source: https://webdriver.io/docs/api/browser/switchFrame.md # switchFrame Switch the Classic session into a frame. In a WebDriver BiDi session this command throws. Hold the browsing context from `browser.url()` or `browser.newWindow()` and call `context.frame()`. `context.parent` is the frame you came from. There is no `switchFrame(null)`. In a Classic session, pass an element or `null` for the top frame. A string or a function is rejected. ## Usage[​](#usage "Direct link to Usage") ``` await browser.switchFrame(context) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------- | --------------- | --------------------------------------------------------- | | `context` | `Element, null` | frame element, or `null` for the top frame (Classic only) | ## Example[​](#example "Direct link to Example") switchFrame.js ``` // Classic await browser.switchFrame($('iframe')) await browser.switchFrame(null) // BiDi const page = await browser.url('https://example.com') const child = await page.frame('iframe') console.log(await child.getTitle()) ``` ## Returns[​](#returns "Direct link to Returns") * **\<void>** --- Source: https://webdriver.io/docs/api/browser/switchWindow.md # switchWindow Switch focus to a particular tab / window (Classic sessions). In a WebDriver BiDi session this command throws. `browser.url()` and `browser.newWindow()` return the browsing context, and `browser.browsingContexts()` lists the open top-level contexts. Commands run on the context you hold. ## Usage[​](#usage "Direct link to Usage") ``` await browser.switchWindow(matcher) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------- | ---------------- | ------------------------------------------------------------------------------------------------------------- | | `matcher` | `String, RegExp` | String or regular expression that matches either the page title or URL, the window name, or the window handle | ## Example[​](#example "Direct link to Example") switchWindow\.js ``` it('should switch to another window', async () => { // Classic await browser.url('https://google.com') const handle = await browser.getWindowHandle() await browser.newWindow('https://webdriver.io') await browser.switchWindow('google.com') await browser.switchWindow(handle) // BiDi const google = await browser.url('https://google.com') const docs = await browser.newWindow('https://webdriver.io') console.log(await docs.getTitle()) console.log(await google.getTitle()) }); ``` --- Source: https://webdriver.io/docs/api/browser/throttleCPU.md # throttleCPU Throttles the CPU to emulate a slower processor. info Note that using the `throttleCPU` command requires support for Chrome DevTools protocol and e.g. can not be used when running automated tests in the cloud. Chrome DevTools protocol is not installed by default, use `npm install puppeteer-core` to install it. Find out more in the [Automation Protocols](/docs/automationProtocols.md) section. ## Usage[​](#usage "Direct link to Usage") ``` await browser.throttleCPU(factor) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | -------- | -------- | --------------------------------------------------------- | | `factor` | `number` | slowdown factor (1 is no throttle, 2 is 2x slowdown, etc) | ## Example[​](#example "Direct link to Example") throttleCPU.js ``` it('should throttle the CPU', async () => { await browser.throttleCPU(2) // 2x slowdown }); ``` --- Source: https://webdriver.io/docs/api/browser/throttleNetwork.md # throttleNetwork Throttle the network capabilities of the browser. This can help to emulate certain scenarios where a user loses their internet connection and your app needs to address that. There are many presets available with default configurations for ease of use. They are `offline`, `GPRS`, `Regular2G`, `Good2G`, `Regular3G`, `Good3G`, `Regular4G`, `DSL`, `WiFi`, `online`. You can see the values for these presets [in the source code](https://github.com/webdriverio/webdriverio/blob/6824e4eb118a8d20685f12f4bc42f13fd56f8a25/packages/webdriverio/src/commands/browser/throttleNetwork.js#L29). info Service workers initiate requests through their own network stack. This command applies the throttling conditions to every service worker that is registered at the time of the call. If your app registers a service worker afterwards, call `throttleNetwork` again to cover it. Note that using the `throttleNetwork` command requires support for Chrome DevTools protocol and e.g. can not be used when running automated tests in the cloud. Chrome DevTools protocol is not installed by default, use `npm install puppeteer-core` to install it. Find out more in the [Automation Protocols](/docs/automationProtocols.md) section. ## Usage[​](#usage "Direct link to Usage") ``` await browser.throttleNetwork({ offline, latency, downloadThroughput, uploadThroughput }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------------------------- | ----------------- | ------------------------------------------------------------------------------------ | | `params` | `ThrottleOptions` | parameters for throttling | | `params.offline` | `boolean` | True to emulate internet disconnection. | | `params.latency` | `number` | Minimum latency from request sent to response headers received (ms). | | `params.downloadThroughput` | `number` | Maximal aggregated download throughput (bytes/sec). -1 disables download throttling. | | `params.uploadThroughput` | `number` | Maximal aggregated upload throughput (bytes/sec). -1 disables upload throttling. | ## Example[​](#example "Direct link to Example") throttleNetwork.js ``` it('should throttle the network', async () => { // via static string preset await browser.throttleNetwork('Regular3G') // via custom values await browser.throttleNetwork({ offline: false, downloadThroughput: 200 * 1024 / 8, uploadThroughput: 200 * 1024 / 8, latency: 20 }) }); ``` --- Source: https://webdriver.io/docs/api/browser/uninstallExtension.md # uninstallExtension Uninstall a web extension that was installed with [`installExtension`](/docs/api/browser/installExtension.md). Pass the extension id string that `installExtension` returned. There is no restore-function wrapper: the id is what you keep, and this command matches [`webExtension.uninstall`](https://w3c.github.io/webdriver-bidi/#command-webExtension-uninstall). ## Usage[​](#usage "Direct link to Usage") ``` await browser.uninstallExtension(extensionId) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------- | -------- | ------------------------------------------- | | `extensionId` | `string` | extension id returned by `installExtension` | ## Example[​](#example "Direct link to Example") uninstallExtension.js ``` const id = await browser.installExtension('./dist') await browser.uninstallExtension(id) ``` --- Source: https://webdriver.io/docs/api/browser/url.md # url The `url` command loads an URL in the browser. If a baseUrl is specified in the config, it will be prepended to the url parameter using node's url.resolve() method. Calling `browser.url('...')` with the same url as last time will trigger a page reload. However, if the url contains a hash, the browser will not trigger a new navigation and the user has to [refresh](/docs/api/webdriver.md#refresh) the page to trigger one. In a WebDriver BiDi session the command returns the browsing context it navigated. That is the session's initial top-level context: a later `browser.url()` navigates the same context, and load metadata is `context.request`. In a Classic session the command still returns `void`. `context.request` contains information about the request and response data of the page load: ``` interface WebdriverIO.Request { id?: string url: string timestamp: number navigation?: string redirectChain?: string[], headers: Record<string, string> cookies?: NetworkCookie[] \/** * Error message if request failed *\/ error?: string response?: { fromCache: boolean headers: Record<string, string> mimeType: string status: number }, /** * List of all requests that were made due to the main request. * Note: the list may be incomplete and does not contain request that were * made after the command has finished. * * The property will be undefined if the request is not a document request * that was initiated by the browser. *\/ children?: Request[] } ``` The command supports the following options: note These features unfortunately won't be available to you if your remote environment doesn't support WebDriver Bidi. You can check if Bidi is support in your session by looking into the `browser.isBidi` property. ### wait[​](#wait "Direct link to wait") The desired state the requested resource should be in before finishing the command. It supports the following states: * `none`: no wait after the page request is made and the response is received * `interactive`: wait until the page is interactive * `complete`: wait until the DOM tree of the page is fully loaded * `networkIdle`: wait until there are no pending network requests ### headers[​](#headers "Direct link to headers") Headers to be sent with the request. **Default:** `{}` ### auth[​](#auth "Direct link to auth") Basic authentication credentials. Note: this will overwrite the existing `Authorization` header if provided in the `headers` option. ### timeout[​](#timeout "Direct link to timeout") If set to a number, the command will wait for the specified amount of milliseconds for the page to load all responses before returning. Note: for this to have an impact, it requires the `wait` option to be set to `networkIdle`. **Default:** `5000` ## Usage[​](#usage "Direct link to Usage") ``` await browser.url(url, { wait, timeout, onBeforeLoad, auth, headers }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | -------------------------------------- | -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `url`<br />*optional* | `string` | the URL to navigate to | | `options`<br />*optional* | `UrlOptions` | navigation options | | `options.wait`<br />*optional* | `'none', 'interactive', 'networkIdle', 'complete'` | The desired state the requested resource should be in before finishing the command. Default: 'complete' | | `options.timeout`<br />*optional* | `number` | If set to a number, the command will wait for the specified amount of milliseconds for the page to load<br />all responses before returning. Default: 5000 | | `options.onBeforeLoad`<br />*optional* | `Function` | A function that is being called before your page has loaded all of its resources. It allows you to easily<br />mock the environment, e.g. overwrite Web APIs that your application uses. | | `options.auth`<br />*optional* | `{user: string, pass: string}` | basic authentication credentials | | `options.headers`<br />*optional* | `Record<string, string>` | headers to be sent with the request | ## Examples[​](#examples "Direct link to Examples") url.js ``` // navigate to a new URL const context = await browser.url('https://webdriver.io'); console.log(context.url); // outputs: "https://webdriver.io" console.log(context.request?.response?.status); // outputs: 200 console.log(context.request?.response?.headers); // outputs: { 'content-type': 'text/html; charset=UTF-8' } ``` baseUrlResolutions.js ``` // With a base URL of http://example.com/site, the following url parameters resolve as such: // When providing a scheme: // https://webdriver.io await browser.url('https://webdriver.io'); // When not starting with a slash, the URL resolves relative to the baseUrl // http://example.com/site/relative await browser.url('relative'); // When starting with a slash, the URL resolves relative to the root path of the baseUrl // http://example.com/rootRelative await browser.url('/rootRelative'); ``` basicAuth.js ``` // navigate to a URL with basic authentication await browser.url('https://the-internet.herokuapp.com/basic_auth', { auth: { user pass } }); await expect($('p=Congratulations! You must have the proper credentials.').toBeDisplayed(); ``` onBeforeLoad.js ``` // navigate to a URL and mock the battery API await browser.url('https://pazguille.github.io/demo-battery-api/', { onBeforeLoad (win) { // mock "navigator.battery" property // returning mock charge object win.navigator.getBattery = () => Promise.resolve({ level: 0.5, charging: false, chargingTime: Infinity, dischargingTime: 3600, // seconds }) } }) // now we can assert actual text - we are charged at 50% await expect($('.battery-percentage')).toHaveText('50%') // and has enough juice for 1 hour await expect($('.battery-remaining')).toHaveText('01:00) ``` ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.BrowsingContext>** **`returns`:** the [browsing context](/docs/api/browsingContext.md) that was navigated. In a WebDriver Classic --- Source: https://webdriver.io/docs/api/browser/waitUntil.md # waitUntil This wait command is your universal weapon if you want to wait on something. It expects a condition and waits until that condition is fulfilled with a truthy value to be returned. A common example is to wait until a certain element contains a certain text (see example). ## Usage[​](#usage "Direct link to Usage") ``` await browser.waitUntil(condition, { timeout, timeoutMsg, interval }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------------------ | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- | | `condition` | `Function` | condition to wait on until returning a truthy value | | `options`<br />*optional* | `WaitUntilOptions` | command options | | `options.timeout`<br />*optional* | `Number` | time in ms (default set based on [`waitforTimeout`](/docs/configuration.md#waitfortimeout) config value) | | `options.timeoutMsg`<br />*optional* | `String, Function` | error message to throw when waitUntil times out. A function is evaluated only after the timeout, so the message can include state from that moment. | | `options.interval`<br />*optional* | `Number` | interval between condition checks (default set based on [`waitforInterval`](/docs/configuration.md#waitforinterval) config value) | ## Examples[​](#examples "Direct link to Examples") index.html ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/0bfb2b8d212b627a2659b10f4449184b657e1d59/waitUntil/index.html#L3-L8 >) waitUntilExample.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/0c9252b0a4f7e18a34cece74e5798c1fe464c120/waitUntil/waitUntilExample.js#L16-L24 >) ## Returns[​](#returns "Direct link to Returns") * **\<Boolean>** **`return`:** true if condition is fulfilled --- Source: https://webdriver.io/docs/api/browsingContext.md # The BrowsingContext Object A browsing context is a tab, a window or a frame that you hold as an object. Commands you call on it run in that tab or frame, while the session and every other context stay where they are. Since v10 this is how WebdriverIO works with tabs, windows and frames in a WebDriver BiDi session, and it replaces `switchWindow()` and `switchFrame()` there. test/specs/tabs.e2e.ts ``` import { browser, expect } from '@wdio/globals' describe('browsing contexts', () => { it('works with two tabs and a frame at the same time', async () => { const page = await browser.url('https://the-internet.herokuapp.com/nested_frames') const docs = await browser.newWindow('https://webdriver.io/docs/api', { type: 'tab' }) const top = await page.frame({ selector: 'frame[name="frame-top"]' }) const middle = await top.frame({ selector: 'frame[name="frame-middle"]' }) await expect(middle.$('#content')).toHaveText('MIDDLE') await expect(docs.$('h1')).toBeDisplayed() console.log(await page.getTitle(), await docs.getTitle()) }) }) ``` ## Get a browsing context[​](#get-a-browsing-context "Direct link to Get a browsing context") | Call | Returns | | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | | [`browser.url(url)`](/docs/api/browser/url.md) | The session's first top-level context, after navigating it. `browser.url()` always navigates this one. | | [`browser.newWindow(url, { type })`](/docs/api/browser/newWindow.md) | A new tab (`type: 'tab'`) or window, once its page has loaded. The session does not switch to it. | | [`browser.browsingContexts()`](/docs/api/browser/browsingContexts.md) | Every open top-level context (tabs and windows, not frames), e.g. a tab the page opened itself. | | [`context.frame(query)`](/docs/api/browsingContext/frame.md) | A frame of a context, also cross-origin and nested ones. | Hold on to the object and call commands on it. There is no "current" tab or frame to switch between, so contexts can also be used in parallel: ``` const [titleA, titleB] = await Promise.all([pageA.getTitle(), pageB.getTitle()]) ``` ## WebDriver BiDi and Classic sessions[​](#webdriver-bidi-and-classic-sessions "Direct link to WebDriver BiDi and Classic sessions") Browsing contexts need a WebDriver BiDi session, which is the default since v10 for Chrome, Edge and Firefox. In a WebDriver Classic session, e.g. with Appium or Safari, there is only the session's current context. There: * `browser.url()` returns a stand-in for the browser. Commands like `$`, `execute` or `getTitle` run on the browser, `url`, `isFrame` and `parent` describe the current page, and `contextId` is `undefined`. * `frame()`, `navigate()` and `activate()` reject and name the Classic command to use instead: [`browser.switchFrame()`](/docs/api/browser/switchFrame.md), [`browser.url()`](/docs/api/browser/url.md) or [`browser.switchWindow()`](/docs/api/browser/switchWindow.md). Check `browser.isBidi` when the same code runs in both kinds of session. ## Properties[​](#properties "Direct link to Properties") | Name | Type | Details | | -------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `contextId` | `String` | The WebDriver BiDi browsing context id. `undefined` in a Classic session. | | `url` | `String` | The URL the context was last navigated to with `browser.url()`, `navigate()` or `newWindow()`. Navigations the page does itself (links, `location`, `history.pushState`) only show after [`getUrl()`](/docs/api/browsingContext/getUrl.md). | | `isFrame` | `Boolean` | `true` for a frame, `false` for a tab or window. | | `parent` | `BrowsingContext \| undefined` | For a frame, the context `frame()` was called on (or the frame in between, for a frame nested deeper). `undefined` for a tab or window. | | `browser` | `Browser` | The [browser object](/docs/api/browser.md) of the session. | | `request` | `Request \| undefined` | Load information of the last navigation through `browser.url()` or `navigate()`: URL, headers, response, redirects and the requests the page made. | | `sessionId` | `String` | Session id, the same as `browser.sessionId`. | | `capabilities` | `Object` | Session capabilities, the same as `browser.capabilities`. | | `options` | `Object` | WebdriverIO options, the same as `browser.options`. | | `isBidi` | `Boolean` | Whether the session uses WebDriver BiDi. | | `isMobile` | `Boolean` | Whether the session automates a mobile device. | ## Methods[​](#methods "Direct link to Methods") ### Commands of a browsing context[​](#commands-of-a-browsing-context "Direct link to Commands of a browsing context") These commands act on the context they are called on. Each has its own reference page. | Command | Details | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | [`frame`](/docs/api/browsingContext/frame.md) | Get a frame of this context as a browsing context of its own. | | [`navigate`](/docs/api/browsingContext/navigate.md) | Navigate this context, with the same options as `browser.url()`. | | [`refresh`](/docs/api/browsingContext/refresh.md) | Reload this context. A frame reloads only its own document. | | [`back`](/docs/api/browsingContext/back.md) / [`forward`](/docs/api/browsingContext/forward.md) | Move through the history of this tab or window. | | [`activate`](/docs/api/browsingContext/activate.md) | Bring this tab or window to the front. | | [`closeWindow`](/docs/api/browsingContext/closeWindow.md) | Close this tab or window. | | [`getTitle`](/docs/api/browsingContext/getTitle.md) / [`getUrl`](/docs/api/browsingContext/getUrl.md) | Read the title or URL of the document shown in this context. | | [`acceptAlert`](/docs/api/browsingContext/acceptAlert.md) / [`dismissAlert`](/docs/api/browsingContext/dismissAlert.md) / [`getAlertText`](/docs/api/browsingContext/getAlertText.md) | Answer or read the user prompt open in this context. | ### Browser commands that run in a context[​](#browser-commands-that-run-in-a-context "Direct link to Browser commands that run in a context") These are the [browser commands](/docs/api/browser.md) of the same name, applied to this context instead of the session's first one. They take the same arguments. | Command | In a browsing context | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | [`$`](/docs/api/browser/$.md), [`$$`](/docs/api/browser/$$.md), [`custom$`](/docs/api/browser/custom$.md), [`custom$$`](/docs/api/browser/custom$$.md), [`react$`](/docs/api/browser/react$.md), [`react$$`](/docs/api/browser/react$$.md) | Find elements in this context's document. | | [`execute`](/docs/api/browser/execute.md) | Run a script in this context's document. | | [`action`](/docs/api/browser/action.md), [`actions`](/docs/api/browser/actions.md), [`keys`](/docs/api/browser/keys.md), [`scroll`](/docs/api/browser/scroll.md) | Send input to this context, also when it is a background tab. | | [`saveScreenshot`](/docs/api/browser/saveScreenshot.md), [`savePDF`](/docs/api/browser/savePDF.md) | Capture this context. | | [`getCookies`](/docs/api/browser/getCookies.md), [`setCookies`](/docs/api/browser/setCookies.md), [`deleteCookies`](/docs/api/browser/deleteCookies.md) | Read and change the cookies of this context's storage partition. | | [`setViewport`](/docs/api/browser/setViewport.md) | Resize the viewport of this tab or window. | | [`addInitScript`](/docs/api/browser/addInitScript.md) | Run a script before the page scripts, in this tab or window only. | | [`mock`](/docs/api/browser/mock.md), [`mockClearAll`](/docs/api/browser/mockClearAll.md), [`mockRestoreAll`](/docs/api/browser/mockRestoreAll.md) | Mock the requests of this tab or window only. A mock ends when its tab closes. `mockClearAll` and `mockRestoreAll` only touch the mocks of this tab. | | [`emulate`](/docs/api/browser/emulate.md) | Emulate a device property, e.g. geolocation or the clock, in this tab or window only. | | [`restore`](/docs/api/browser/restore.md) | Restore emulations, the same as `browser.restore()`. | | [`waitUntil`](/docs/api/browser/waitUntil.md), [`pause`](/docs/api/browser/pause.md) | The same as on the browser. | test/specs/mock.e2e.ts ``` import { browser, expect } from '@wdio/globals' it('mocks the requests of one tab only', async () => { const page = await browser.url('https://webdriver.io') const tab = await browser.newWindow('https://webdriver.io', { type: 'tab' }) const mock = await tab.mock('**/api/users') mock.respond([{ name: 'Mocked user' }]) // requests of `tab` get the mocked response, requests of `page` reach the server }) ``` When a session-wide mock from `browser.mock()` has the same URL, the mock of the tab answers in its tab and the session-wide mock answers in all other tabs. This is true in both orders of creation. A mock of the tab that only records requests, or that used up its `once` calls (`respondOnce`), does not block the session-wide mock. A mock of a tab can wait for the response, for example with a `statusCode` filter. In Chrome, the session-wide mock answers when the response does not match that filter. In Firefox, a mock that waits for the response cannot send a body after the request left. It gives way to a session-wide mock that answers early, and WebdriverIO logs one warning for that mock. See [Which mock answers a request](/docs/api/mock.md#which-mock-answers-a-request). ### Top-level only[​](#top-level-only "Direct link to Top-level only") A frame shares its tab's history, viewport, network and emulation, so these commands reject on a frame with `` `<command>` is only available on a top-level browsing context ``. Call them on the tab: `frame.parent` until `parent` is `undefined`, or the context you called `frame()` on. `back`, `forward`, `activate`, `closeWindow`, `setViewport`, `addInitScript`, `mock`, `mockClearAll`, `mockRestoreAll`, `emulate`, `restore` ### Not available on a browsing context[​](#not-available-on-a-browsing-context "Direct link to Not available on a browsing context") Session commands, such as `deleteSession`, `newWindow` or `browsingContexts`, are only on the [browser object](/docs/api/browser.md). Custom commands are too: [`addCommand`](/docs/customcommands.md) and `overwriteCommand` reject on a context, register them on `browser`. ### Events[​](#events "Direct link to Events") `on`, `once`, `off`, `emit`, `removeListener` and `removeAllListeners` register listeners on the browser, so the events are those of the whole session. For example, a [`dialog`](/docs/api/dialog.md) event fires for a prompt in any tab or frame. ## Elements of a browsing context[​](#elements-of-a-browsing-context "Direct link to Elements of a browsing context") An element you get through a context belongs to that context. Element commands such as `click`, `setValue` or `getText` run in that context's document, also when it is a background tab or a frame. They follow the WebDriver spec like the drivers do, so they return the same results and the same errors (e.g. `element click intercepted`) as for an element of the page in front. `getComputedRole` and `getComputedLabel` reject for an element of a context other than the session's first one. ``` const page = await browser.url('https://the-internet.herokuapp.com/nested_frames') const bottom = await page.frame({ selector: 'frame[name="frame-bottom"]' }) const body = await bottom.$('body') console.log(await body.getText()) // outputs: "BOTTOM" ``` ## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting") | Error | Cause and fix | | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- | | `` `switchFrame` was removed for WebDriver BiDi sessions in WebdriverIO v10. `` | Call [`frame()`](/docs/api/browsingContext/frame.md) on the context returned by `browser.url()` or `browser.newWindow()`. | | `` `switchWindow` was removed for WebDriver BiDi sessions in WebdriverIO v10. `` | Hold the context returned by `browser.url()` or `browser.newWindow()`, or find one with `browser.browsingContexts()`. | | `` `frame()` needs a WebDriver BiDi session, but this session uses WebDriver Classic `` | The session is a Classic session (e.g. Appium or Safari). Use the Classic command the message names. | | `` `<command>` is only available on a top-level browsing context `` | The command was called on a frame. Call it on the frame's tab, see [Top-level only](#top-level-only). | | `` `addCommand` is only available on the browser, not on a browsing context `` | Register custom commands on `browser`. | | `no such frame: the frame "…" was discarded because the page it belongs to navigated away` | The page that contained the frame navigated. Get the frame again with `frame()` on the new page. | ## Related[​](#related "Direct link to Related") * [The Browser Object](/docs/api/browser.md) * [Migrate to v10: `switchToFrame`](/docs/v10-migration.md#switchtoframe) * [Dialogs](/docs/api/dialog.md) --- Source: https://webdriver.io/docs/api/browsingContext/acceptAlert.md # acceptAlert Accept the user prompt (`alert`, `confirm` or `prompt`) that is open in this browsing context. Prompts in other tabs stay open. WebdriverIO dismisses prompts automatically unless something listens to the `dialog` event, so register a listener first. In a listener you can also answer with the [dialog object](/docs/api/dialog.md) directly. ## Usage[​](#usage "Direct link to Usage") ``` const context = await browser.url('https://webdriver.io') await context.acceptAlert(userText) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | -------------------------- | -------- | ----------------------------- | | `userText`<br />*optional* | `string` | text to enter into a `prompt` | ## Example[​](#example "Direct link to Example") acceptAlert.js ``` it('accepts a confirm in a background tab', async () => { browser.on('dialog', () => {}) // keep prompts open await browser.url('https://webdriver.io') const tab = await browser.newWindow('https://webdriver.io', { type: 'tab' }) const opened = new Promise((resolve) => browser.once('dialog', resolve)) await tab.execute(() => setTimeout(() => window.confirm('Continue?'))) await opened await tab.acceptAlert() }) ``` --- Source: https://webdriver.io/docs/api/browsingContext/activate.md # activate Bring the tab or window of this browsing context to the front and focus it. Commands run in every held browsing context whether it is in front or not, so you only need this when the page reacts to focus or visibility, or before a visual check. It does not change which context `browser.url()` navigates. Only a top-level browsing context can be activated, a frame rejects. ## Usage[​](#usage "Direct link to Usage") ``` const context = await browser.url('https://webdriver.io') await context.activate() ``` ## Example[​](#example "Direct link to Example") activate.js ``` it('brings a background tab to the front', async () => { const page = await browser.url('https://webdriver.io') const tab = await browser.newWindow('https://webdriver.io/docs/api', { type: 'tab' }) await page.activate() // the first tab is in front again console.log(await tab.getTitle()) // the tab behind it still answers commands }) ``` --- Source: https://webdriver.io/docs/api/browsingContext/back.md # back Go back one entry in the history of this tab or window, like the browser's back button, and wait until that page is ready (following the `pageLoadStrategy` capability, like `browser.back()`). Other tabs keep their page. Only a top-level browsing context has its own history, a frame rejects. ## Usage[​](#usage "Direct link to Usage") ``` const context = await browser.url('https://webdriver.io') await context.back() ``` ## Example[​](#example "Direct link to Example") back.js ``` it('goes back in one tab', async () => { const page = await browser.url('https://webdriver.io') await page.navigate('https://webdriver.io/docs/api') await page.back() console.log(await page.getUrl()) // outputs: "https://webdriver.io/" }) ``` --- Source: https://webdriver.io/docs/api/browsingContext/closeWindow.md # closeWindow Close the tab or window of this browsing context. Other tabs and windows stay open, and the session keeps running as long as one of them is left. Commands on the closed context, and on frames of it, reject afterwards. Mocks made on the context end with it. Only a top-level browsing context can be closed, a frame rejects. ## Usage[​](#usage "Direct link to Usage") ``` const context = await browser.url('https://webdriver.io') await context.closeWindow() ``` ## Example[​](#example "Direct link to Example") closeWindow\.js ``` it('closes a tab it opened', async () => { const page = await browser.url('https://webdriver.io') const tab = await browser.newWindow('https://webdriver.io/docs/api', { type: 'tab' }) await tab.closeWindow() console.log((await browser.browsingContexts()).length) // outputs: 1 console.log(await page.getTitle()) // the first tab is unchanged }) ``` --- Source: https://webdriver.io/docs/api/browsingContext/dismissAlert.md # dismissAlert Dismiss the user prompt (`alert`, `confirm` or `prompt`) that is open in this browsing context, like pressing "Cancel". Prompts in other tabs stay open. WebdriverIO dismisses prompts automatically unless something listens to the `dialog` event, so register a listener first when you want to answer yourself. ## Usage[​](#usage "Direct link to Usage") ``` const context = await browser.url('https://webdriver.io') await context.dismissAlert() ``` ## Example[​](#example "Direct link to Example") dismissAlert.js ``` it('dismisses a confirm in one tab only', async () => { browser.on('dialog', () => {}) // keep prompts open const page = await browser.url('https://webdriver.io') const opened = new Promise((resolve) => browser.once('dialog', resolve)) await page.execute(() => setTimeout(() => window.confirm('Leave?'))) await opened await page.dismissAlert() }) ``` --- Source: https://webdriver.io/docs/api/browsingContext/forward.md # forward Go forward one entry in the history of this tab or window, like the browser's forward button, and wait until that page is ready (following the `pageLoadStrategy` capability, like `browser.forward()`). Other tabs keep their page. Only a top-level browsing context has its own history, a frame rejects. ## Usage[​](#usage "Direct link to Usage") ``` const context = await browser.url('https://webdriver.io') await context.forward() ``` ## Example[​](#example "Direct link to Example") forward.js ``` it('goes forward in one tab', async () => { const page = await browser.url('https://webdriver.io') await page.navigate('https://webdriver.io/docs/api') await page.back() await page.forward() console.log(await page.getUrl()) // outputs: "https://webdriver.io/docs/api/" }) ``` --- Source: https://webdriver.io/docs/api/browsingContext/frame.md # frame Get a frame (`<iframe>` or `<frame>`) of this browsing context as a browsing context of its own. Commands on the returned context run in the frame's document, also for cross-origin frames, while this context and every other one stay usable. Since v10 this replaces `switchFrame()` in a WebDriver BiDi session. Say how to find the frame with a query, the recommended form: * `{ selector }`: the frame element a CSS or XPath selector finds in this document * `{ url }`: the first frame, at any depth, whose URL equals the string or matches the RegExp * `{ id }`: the frame with this browsing context id It also takes a frame element, or a predicate that is called with the `context` id and `url` of each descendant frame. A string is a shorthand that guesses: a selector when it finds a frame element, then a frame URL (or a part of it), then a context id. `parent` on the result is the context `frame()` was called on for a direct child frame, or the frame in between when the match is nested deeper. ## Usage[​](#usage "Direct link to Usage") ``` const context = await browser.url('https://webdriver.io') await context.frame(target) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | -------- | --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | `target` | `FrameQuery, WebdriverIO.Element, Function, string` | the frame to get: a query (`{ selector }`, `{ url }` or `{ id }`), a frame element, a predicate, or a string shorthand | ## Examples[​](#examples "Direct link to Examples") frame.js ``` it('works with nested frames', async () => { const page = await browser.url('https://the-internet.herokuapp.com/nested_frames') const top = await page.frame({ selector: 'frame[name="frame-top"]' }) const middle = await top.frame({ selector: 'frame[name="frame-middle"]' }) console.log(await middle.$('#content').getText()) // outputs: "MIDDLE" console.log(middle.parent?.contextId === top.contextId) // outputs: true console.log(await page.getTitle()) // the page itself is still usable }) ``` frameQueries.js ``` it('finds frames by url, id or predicate', async () => { const page = await browser.url('https://the-internet.herokuapp.com/nested_frames') const top = await page.frame({ url: /frame_top/ }) const left = await top.frame({ url: /frame_left/ }) const sameFrame = await page.frame({ id: left.contextId }) console.log(await sameFrame.$('body').getText()) // outputs: "LEFT" const bottom = await page.frame(({ url }) => url.endsWith('/frame_bottom')) console.log(await bottom.$('body').getText()) // outputs: "BOTTOM" }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.BrowsingContext>** **`return`:** the browsing context of the frame ## Throws[​](#throws "Direct link to Throws") * **Error**: When no frame matches before the `waitforTimeout` passes, or when a selector finds an element that is not a frame. --- Source: https://webdriver.io/docs/api/browsingContext/getAlertText.md # getAlertText Get the message of the user prompt (`alert`, `confirm` or `prompt`) that is open in this browsing context. Rejects with `no such alert` when none is open. WebdriverIO dismisses prompts automatically unless something listens to the `dialog` event, so register a listener first. ## Usage[​](#usage "Direct link to Usage") ``` const context = await browser.url('https://webdriver.io') await context.getAlertText() ``` ## Example[​](#example "Direct link to Example") getAlertText.js ``` it('reads the message of a prompt', async () => { browser.on('dialog', () => {}) // keep prompts open const page = await browser.url('https://webdriver.io') const opened = new Promise((resolve) => browser.once('dialog', resolve)) await page.execute(() => setTimeout(() => window.alert('Saved'))) await opened console.log(await page.getAlertText()) // outputs: "Saved" await page.acceptAlert() }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<string>** **`return`:** the prompt message --- Source: https://webdriver.io/docs/api/browsingContext/getTitle.md # getTitle Get the title of the document shown in this browsing context. For a frame this is the title of the frame's own document. ## Usage[​](#usage "Direct link to Usage") ``` const context = await browser.url('https://webdriver.io') await context.getTitle() ``` ## Example[​](#example "Direct link to Example") getTitle.js ``` it('reads the title of a background tab', async () => { await browser.url('https://webdriver.io') const tab = await browser.newWindow('https://webdriver.io/docs/api', { type: 'tab' }) console.log(await tab.getTitle()) // outputs the title of the API page }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<string>** **`return`:** the document title --- Source: https://webdriver.io/docs/api/browsingContext/getUrl.md # getUrl Get the URL of the document shown in this browsing context, read from the page. It also updates the `url` property, which otherwise holds the URL the context was last navigated to and does not follow navigations the page did itself. ## Usage[​](#usage "Direct link to Usage") ``` const context = await browser.url('https://webdriver.io') await context.getUrl() ``` ## Example[​](#example "Direct link to Example") getUrl.js ``` it('reads the url after the page changed it', async () => { const page = await browser.url('https://webdriver.io') await page.execute(() => history.pushState({}, '', '/docs/api')) console.log(page.url) // outputs: "https://webdriver.io", the url it was navigated to console.log(await page.getUrl()) // outputs: "https://webdriver.io/docs/api" console.log(page.url) // outputs: "https://webdriver.io/docs/api" }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<string>** **`return`:** the document URL --- Source: https://webdriver.io/docs/api/browsingContext/navigate.md # navigate Navigate this browsing context to a URL and wait until the page has loaded. It works for a tab, a window or a frame. Only this context navigates: other tabs keep their page, and the parents of a frame stay where they are. `browser.url()` always navigates the session's first top-level browsing context, so use `navigate()` for any other one. It takes the same options as [`browser.url()`](/docs/api/browser/url.md), and a relative URL resolves against the `baseUrl` option. Returns this context, with `url` and `request` updated. ## Usage[​](#usage "Direct link to Usage") ``` const context = await browser.url('https://webdriver.io') await context.navigate(url, { wait, timeout, onBeforeLoad, auth, headers }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | -------------------------------------- | ------------------- | --------------------------------------------------------------------------------------- | | `url` | `string` | the URL to navigate to, absolute or relative to `baseUrl` | | `options`<br />*optional* | `UrlCommandOptions` | navigation options, the same as for `browser.url()` | | `options.wait`<br />*optional* | `string` | the readiness to wait for: `none`, `interactive`, `complete` (default) or `networkIdle` | | `options.timeout`<br />*optional* | `number` | how long to wait for the page to load, in milliseconds | | `options.onBeforeLoad`<br />*optional* | `Function` | a function that runs in the page before its own scripts | | `options.auth`<br />*optional* | `Object` | basic authentication credentials, `{ user, pass }` | | `options.headers`<br />*optional* | `Object` | headers to send with the request | ## Example[​](#example "Direct link to Example") navigate.js ``` it('navigates one tab without touching the other', async () => { const page = await browser.url('https://webdriver.io') const tab = await browser.newWindow('https://webdriver.io', { type: 'tab' }) await tab.navigate('https://webdriver.io/docs/api', { wait: 'interactive' }) console.log(tab.url) // outputs: "https://webdriver.io/docs/api" console.log(await page.getUrl()) // outputs: "https://webdriver.io/" }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.BrowsingContext>** **`return`:** this browsing context --- Source: https://webdriver.io/docs/api/browsingContext/refresh.md # refresh Reload the document of this browsing context and wait until the new document has loaded. Other tabs and frames are not reloaded. A frame reloads only its own document and keeps its browsing context, so the object you hold stays usable. ## Usage[​](#usage "Direct link to Usage") ``` const context = await browser.url('https://webdriver.io') await context.refresh() ``` ## Example[​](#example "Direct link to Example") refresh.js ``` it('reloads one frame', async () => { const page = await browser.url('https://the-internet.herokuapp.com/nested_frames') const bottom = await page.frame({ selector: 'frame[name="frame-bottom"]' }) await bottom.refresh() console.log(await bottom.$('body').getText()) // outputs: "BOTTOM", the frame is still usable }) ``` --- Source: https://webdriver.io/docs/api/element.md # The Element Object An Element Object is an object representing an element on the remote user agent, e.g. a [DOM Node](https://developer.mozilla.org/en-US/docs/Web/API/Element) when running a session within a browser or [a mobile element](https://developer.apple.com/documentation/swift/sequence/element) for mobile. It can be received using one of the many element query commands, e.g. [`$`](/docs/api/element/$.md), [`custom$`](/docs/api/element/custom$.md), [`react$`](/docs/api/element/react$.md) or [`shadow$`](/docs/api/element/shadow$.md). ## Properties[​](#properties "Direct link to Properties") An element object has the following properties: | Name | Type | Details | | ----------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `sessionId` | `String` | Session id assigned from the remote server. | | `elementId` | `String` | Associated [web element reference](https://w3c.github.io/webdriver/#elements) that can be used to interact with the element on the protocol level | | `selector` | `String` | [Selector](/docs/selectors.md) used to query the element. | | `parent` | `Object` | Either the [Browser Object](/docs/api/browser.md) when element was fetched from the it (e.g. `const elem = browser.$('selector')`) or an [Element Object](/docs/api/element.md) if it was fetched from an element scope (e.g. `elem.$('selector')`) | | `options` | `Object` | WebdriverIO [options](/docs/configuration.md) depending on how the browser object was created. See more [setup types](/docs/setuptypes.md). | ## Methods[​](#methods "Direct link to Methods") An element object provides all methods from the protocol section, e.g. [WebDriver](/docs/api/webdriver.md) protocol as well as commands listed within the element section. Available protocol commands depend on the type of session. If you run an automated browser session, none of the Appium [commands](/docs/api/appium.md) will be available and vice versa. In addition to that the following commands are available: | Name | Parameters | Details | | ------------------ | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `addCommand` | - `commandName` (Type: `String`)<br />- `fn` (Type: `Function`) | Allows to define custom commands that can be called from the browser object for composition purposes. Read more in the [Custom Command](/docs/customcommands.md) guide. | | `overwriteCommand` | - `commandName` (Type: `String`)<br />- `fn` (Type: `Function`) | Allows to overwrite any browser command with custom functionality. Use carefully as it can confuse framework users. Read more in the [Custom Command](/docs/customcommands.md#overwriting-native-commands) guide. | ## Remarks[​](#remarks "Direct link to Remarks") ### Element Chain[​](#element-chain "Direct link to Element Chain") When working with elements WebdriverIO provides special syntax to simplify querying them and composite complex nested element lookups. As element objects allow you to find elements within their tree branch using common query methods, users can fetch nested elements as follows: ``` const header = await $('#header') const headline = await header.$('#headline') console.log(await headline.getText()) // outputs "I am a headline" ``` With deep nested structures assigning any nested element to an array to then use it can be quite verbose. Therefore WebdriverIO has the concept of chained element queries that allow fetching nested elements like this: ``` console.log(await $('#header').$('#headline').getText()) ``` This also works when fetching a set of elements, e.g.: ``` // get the text of the 3rd headline within the 2nd header console.log(await $$('#header')[1].$$('#headline')[2].getText()) ``` When working with a set of elements this can be especially useful when trying to interact with them, so instead of doing: ``` const elems = await $$('div') const locations = await Promise.all( elems.map((el) => el.getLocation()) ) ``` You can directly call Array methods on the element chain, e.g.: ``` const location = await $$('div').map((el) => el.getLocation()) ``` same as: ``` const divs = await $$('div') const location = await divs.map((el) => el.getLocation()) ``` WebdriverIO uses a custom implementation that supports asynchronous iterators under the hood so all commands from their API are also supported for these use cases. **Note:** all async iterators return a promise even if your callback doesn't return one, e.g.: ``` const divs = await $$('div') console.log(divs.map((div) => div.selector)) // ❌ returns "Promise<string>[]" console.log(await divs.map((div) => div.selector)) // ✅ returns "string[]" ``` ### Custom Commands[​](#custom-commands "Direct link to Custom Commands") You can set custom commands on the browser scope to abstract away workflows that are commonly used. Check out our guide on [Custom Commands](/docs/customcommands.md#adding-custom-commands) for more information. --- Source: https://webdriver.io/docs/api/element/$$.md # $$ The `$$` command fetches every element that matches a selector, starting from this element. It returns a `WebdriverIO.ElementArray`: a real array (`Array.isArray` is `true`) that stays thenable until the query finishes. Await it for a resolved list (`length` is then a number), or use it directly with `for await`, `await el.$$('.item').length`, and `el.$$('.item')[0]`. A synchronous `for...of` throws until the list has resolved. info As opposed to the [`$$`](/docs/api/browser/$$.md) attached to the [browser object](/docs/api/browser.md) this command queries elements based on a root element. You can chain `$` or `$$` together without wrapping individual commands into `await` in order to walk down the DOM tree, e.g.: ``` const imageSrc = await $$('div')[1].nextElement().$$('img')[2].getAttribute('src') ``` WebdriverIO seamlessly traverses shadow roots when using the `$` or `$$` commands, regardless of the nesting level or shadow root mode, for example: ``` await browser.url('https://ionicframework.com/docs/usage/v8/datetime/basic/demo.html?ionic:mode=md') await browser.$('button[aria-label="Sunday, August 4"]').click() await browser.$('.aux-input').getValue() ``` It is also possible to use async iterators to loop over the result of the query, e.g.: ``` // print all image sources for await (const img of $$('img')) { console.log(await img.getAttribute('src')) } ``` The result also provides asynchronous versions of the `Array` iteration methods, like `map` and `mapSeries`. See [Iterating over elements](/docs/api/browser/$$.md#iterating-over-elements) for how they work. info For more information on how to select specific elements, check out the [Selectors](/docs/selectors.md) guide. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).$$(selector) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------- | --------------------------- | ------------------------------------------------------------------- | | `selector` | `String, Function, Matcher` | selector, JS Function, or Matcher object to fetch multiple elements | ## Examples[​](#examples "Direct link to Examples") example.html ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/59c122c809d44d343c231bde2af7e8456c8f086c/queryElements/example.html >) multipleElements.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/59c122c809d44d343c231bde2af7e8456c8f086c/queryElements/multipleElements.js#L6-L7 >) multipleElements.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/59c122c809d44d343c231bde2af7e8456c8f086c/queryElements/multipleElements.js#L15-L24 >) multipleElements.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/59c122c809d44d343c231bde2af7e8456c8f086c/queryElements/multipleElements.js#L32-L39 >) ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.ElementArray>** --- Source: https://webdriver.io/docs/api/element/$.md # $ The `$` command is a short and handy way in order to fetch a single element on the page. info As opposed to the [`$`](/docs/api/browser/$.md) attached to the [browser object](/docs/api/browser.md) this command queries an element based on a root element. You can also pass in an object as selector where the object contains a property `element-6066-11e4-a52e-4f735466cecf` with the value of a reference to an element. The command will then transform the reference to an extended WebdriverIO element. Note: chaining `$` and `$$` commands only make sense when you use multiple selector strategies. You will otherwise make unnecessary requests that slow down the test (e.g. `$('body').$('div')` will trigger two request whereas `$('body div')` does literally the same with just one request) You can chain `$` or `$$` together without wrapping individual commands into `await` in order to walk down the DOM tree, e.g.: ``` const imageSrc = await $$('div')[1].nextElement().$$('img')[2].getAttribute('src') ``` WebdriverIO seamlessly traverses shadow roots when using the `$` or `$$` commands, regardless of the nesting level or shadow root mode, for example: ``` await browser.url('https://ionicframework.com/docs/usage/v8/datetime/basic/demo.html?ionic:mode=md') await browser.$('button[aria-label="Sunday, August 4"]').click() await browser.$('.aux-input').getValue() ``` As of v10 this command is **strict**: if the selector resolves to more than one element within this element it throws a `StrictSelectorError` rather than silently returning the first match. Use `$$` when you expect multiple elements, pass `{ strict: false }` to opt out for a single call, or set `strictSelectors: false` in your config to opt out globally. info For more information on how to select specific elements, check out the [Selectors](/docs/selectors.md) guide. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).$(selector, { strict }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | -------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `selector` | `String, Function, Matcher` | selector, JS Function, or Matcher object to fetch a certain element | | `options`<br />*optional* | `Object` | command options | | `options.strict`<br />*optional* | `Boolean` | throw if the selector matches more than one element within this element (default: the `strictSelectors` config option, which defaults to `true`) | ## Examples[​](#examples "Direct link to Examples") example.html ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/59c122c809d44d343c231bde2af7e8456c8f086c/queryElements/example.html >) singleElements.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/59c122c809d44d343c231bde2af7e8456c8f086c/queryElements/singleElements.js#L9-L10 >) singleElements.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/59c122c809d44d343c231bde2af7e8456c8f086c/queryElements/singleElements.js#L16-L25 >) singleElements.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/59c122c809d44d343c231bde2af7e8456c8f086c/queryElements/singleElements.js#L42-L46 >) $.js ``` it('should use Androids DataMatcher or ViewMatcher selector', async () => { const menuItem = await $({ "name": "hasEntry", "args": ["title", "ViewTitle"], "class": "androidx.test.espresso.matcher.ViewMatchers" }); await menuItem.click(); const menuItem = await $({ "name": "hasEntry", "args": ["title", "ViewTitle"] }); await menuItem.click(); }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.Element>** --- Source: https://webdriver.io/docs/api/element/addValue.md # addValue Add a value to an input or textarea element found by given selector. info If you like to use special characters, e.g. to copy and paste a value from one input to another, use the [`keys`](/docs/api/browser/keys.md) command with the [`Key`](/docs/api/modules.md#key) object. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).addValue(value, additional) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------ | ---------------- | --------------------------------- | | `value` | `string, number` | value to be added | | `additional` | `InputOptions` | options, exclusive to Webdriverio | ## Example[​](#example "Direct link to Example") addValue.js ``` it('should demonstrate the addValue command', async () => { let input = await $('.input') await input.addValue('test') await input.addValue(123) value = await input.getValue() assert(value === 'test123') // true }) ``` --- Source: https://webdriver.io/docs/api/element/clearValue.md # clearValue Clear the value of an input or textarea element. Make sure you can interact with the element before using this command. You can't clear an input element that is disabled or in readonly mode. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).clearValue() ``` ## Example[​](#example "Direct link to Example") clearValue.js ``` it('should demonstrate the clearValue command', async () => { const elem = await $('.input') await elem.setValue('test123') const value = await elem.getValue() console.log(value) // returns 'test123' await elem.clearValue() value = await elem.getValue() assert(value === ''); // true }) ``` --- Source: https://webdriver.io/docs/api/element/click.md # click Click on an element. This issues a WebDriver `click` command for the selected element , which generally scrolls to and then clicks the selected element when no options are passed. When options object is passed it uses action class instead of webdriver click which give added capabilities like passing button type, coordinates etc. By default, when using options a release action command is send after performing the click action, pass `option.skipRelease=true` to skip this action. Before the actions, when the pointer would not hit the element at its center (it is outside the window, hidden by a scroll container or covered by a fixed header or footer), the element is scrolled to the center of the window and of its scroll containers (to the bottom or the top when something covers it at the center), and the page gets its `scroll` events before the click. An element that the pointer already hits is not scrolled. In Firefox, and in Safari and web views on iOS with Appium, a click without options does the same before the WebDriver `click` command, because geckodriver and Appium scroll and click without giving the page its `scroll` events first. With an Appium XCUITest driver older than 12.18.2, a click on iOS that scrolls waits 100 ms more. When something intercepts a click without options in any browser (for example a sticky header), the element is brought under the pointer in the same way and clicked again. info If you have fixed-position elements (such as a fixed header or footer) that cover up the selected element after it is scrolled within the viewport, the click will be issued at the given coordinates, but will be received by your fixed (overlaying) element. In these cased the following error is thrown: ``` Element is not clickable at point (x, x). Other element would receive the click: ..." ``` To work around this, try to find the overlaying element and remove it via `execute` command so it doesn't interfere the click. You also can try to scroll to the element yourself using `scroll` with an offset appropriate for your scenario. info The click command can also be used to simulate a long press on a mobile device. This is done by setting the `duration`. See the example below for more information. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).click({ button, x, y, skipRelease, duration }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | `options`<br />*optional* | `ClickOptions` | Click options (optional) | | `options.button`<br />*optional* | `string, number` | Can be one of `[0, "left", 1, "middle", 2, "right"]`<br />**WEB-ONLY** (Desktop/Mobile) | | `options.x`<br />*optional* | `number` | Clicks X horizontal pixels away from location of the element (from center point of element)<br />**WEB and Native** (Desktop/Mobile) | | `options.y`<br />*optional* | `number` | Clicks Y vertical pixels away from location of the element (from center point of element)<br />**WEB and Native support** (Desktop/Mobile) | | `options.skipRelease`<br />*optional* | `boolean` | Boolean (optional)<br />**WEB-ONLY** (Desktop/Mobile) | | `options.duration`<br />*optional* | `number` | Duration of the click, aka "LongPress"<br />**MOBILE-NATIVE-APP-ONLY** (Mobile) | ## Examples[​](#examples "Direct link to Examples") example.html ``` <button id="myButton" onclick="document.getElementById('someText').innerHTML='I was clicked'">Click me</button> <div id="someText">I was not clicked</div> ``` click.js ``` it('should demonstrate the click command', async () => { const myButton = await $('#myButton') await myButton.click() const myText = await $('#someText') const text = await myText.getText() assert(text === 'I was clicked') // true }) ``` example.js ``` it('should fetch menu links and visit each page', async () => { const links = await $$('#menu a') await links.forEach(async (link) => { await link.click() }) }) ``` example.html ``` <button id="myButton">Click me</button> ``` example.js ``` it('should demonstrate a click using an offset', async () => { const myButton = await $('#myButton') await myButton.click({ x: 30 }) // clicks 30 horizontal pixels away from location of the button (from center point of element) }) ``` example.html ``` <button id="myButton">Click me</button> ``` example.js ``` it('should demonstrate a right click passed as string', async () => { const myButton = await $('#myButton') await myButton.click({ button: 'right' }) // opens the contextmenu at the location of the button }) it('should demonstrate a right click passed as number while adding an offset', async () => { const myButton = await $('#myButton') await myButton.click({ button: 2, x: 30, y: 40 }) // opens the contextmenu 30 horizontal and 40 vertical pixels away from location of the button (from the center of element) }) it('should skip sending releaseAction command that cause unexpected alert closure', async () => { const myButton = await $('#myButton') await myButton.click({ button: 2, x: 30, y: 40, skipRelease:true }) // skips sending releaseActions }) ``` longpress.example.js ``` it('should be able to open the contacts menu on iOS by executing a longPress', async () => { const contacts = await $('~Contacts') // opens the Contacts menu on iOS where you can quickly create // a new contact, edit your home screen, or remove the app await contacts.click({ duration: 2000 }) }) ``` --- Source: https://webdriver.io/docs/api/element/custom$$.md # custom$$ The `customs$$` allows you to use a custom strategy declared by using `browser.addLocatorStrategy`. It returns a [`WebdriverIO.ElementArray`](/docs/api/browser/$$.md), the same list as [`$$`](/docs/api/browser/$$.md). Read more on custom selector stratgies in the [Selector docs](/docs/selectors.md#custom-selector-strategies). ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).custom$$(strategyName, strategyArguments) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------- | -------- | ------- | | `strategyName` | `string` | | | `strategyArguments` | `*` | | ## Example[​](#example "Direct link to Example") example.js ``` it('should get all the plugin wrapper buttons', async () => { await browser.url('https://webdriver.io') await browser.addLocatorStrategy('myStrat', (selector) => { return document.querySelectorAll(selector) }) const pluginRowBlock = await browser.custom$('myStrat', '.pluginRowBlock') const pluginWrapper = await pluginRowBlock.custom$$('myStrat', '.pluginWrapper') console.log(pluginWrapper.length) // 4 }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.ElementArray>** --- Source: https://webdriver.io/docs/api/element/custom$.md # custom$ The `custom$` allows you to use a custom strategy declared by using `browser.addLocatorStrategy`. Read more on custom selector stratgies in the [Selector docs](/docs/selectors.md#custom-selector-strategies). ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).custom$(strategyName, strategyArguments) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------- | -------- | ------- | | `strategyName` | `string` | | | `strategyArguments` | `*` | | ## Examples[​](#examples "Direct link to Examples") customStrategy.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/f5730428ec3605e856e90bf58be17c9c9da891de/queryElements/customStrategy.js#L2-L11 >) example.html ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/f5730428ec3605e856e90bf58be17c9c9da891de/queryElements/example.html#L8-L12 >) customStrategy.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/f5730428ec3605e856e90bf58be17c9c9da891de/queryElements/customStrategy.js#L16-L19 >) example.js ``` it('should fetch the project title', async () => { await browser.url('https://webdriver.io') await browser.addLocatorStrategy('myStrat', (selector) => { return document.querySelectorAll(selector) }) const header = await browser.custom$('myStrat', 'header') const projectTitle = await header.custom$('myStrat', '.projectTitle') console.log(projectTitle.getText()) // WEBDRIVER I/O }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.Element>** --- Source: https://webdriver.io/docs/api/element/doubleClick.md # doubleClick Double-click on an element. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).doubleClick() ``` ## Examples[​](#examples "Direct link to Examples") example.html ``` <button id="myButton" ondblclick="document.getElementById('someText').innerHTML='I was dblclicked'">Click me</button> <div id="someText">I was not clicked</div> ``` doubleClick.js ``` it('should demonstrate the doubleClick command', async () => { const myButton = await $('#myButton') await myButton.doubleClick() const value = await myButton.getText() assert(value === 'I was dblclicked') // true }) ``` --- Source: https://webdriver.io/docs/api/element/dragAndDrop.md # dragAndDrop Drag an item to a destination element or position. info The functionality of this command highly depends on the way drag and drop is implemented in your app. If you experience issues please post your example in [#4134](https://github.com/webdriverio/webdriverio/issues/4134). ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).dragAndDrop(target, { duration }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------------------------------- | -------------------------------- | ----------------------------------------------------- | | `target` | `Element, DragAndDropCoordinate` | destination element or object with x and y properties | | `options`<br />*optional* | `DragAndDropOptions` | dragAndDrop command options | | `options.duration`<br />*optional* | `Number` | how long the drag should take place | ## Example[​](#example "Direct link to Example") example.test.js ``` it('should demonstrate the dragAndDrop command', async () => { const elem = $('#someElem') const target = $('#someTarget') // drag and drop to other element await elem.dragAndDrop(target) // drag and drop relative from current position await elem.dragAndDrop({ x: 100, y: 200 }) }) ``` --- Source: https://webdriver.io/docs/api/element/execute.md # execute Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame using the given element as scope, because it is on the element scope it means that WebdriverIO will automatically wait for the element to exist before executing the script. The executed script is assumed to be synchronous and the result of evaluating the script is returned to the client. An `async` function is awaited, which replaces `executeAsync`. The script argument defines the script to execute in the form of a function body. The value returned by that function will be returned to the client. The function will be invoked with the provided args array and the values may be accessed via the arguments object in the order specified. Arguments may be any JSON-primitive, array, or JSON object. JSON objects that define a WebElement reference will be converted to the corresponding DOM element. Likewise, any WebElements in the script result will be returned to the client as WebElement JSON objects. BiDi sessions preserve `Blob` and `File` results the same way `browser.execute` does, including values nested in arrays, plain objects, class instances, `Map`, `Set`, and `FileList`. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).execute(script, arguments) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------------------------- | ------------------ | ---------------------- | | `script` | `String, Function` | The script to execute. | | `arguments`<br />*optional* | `*` | script arguments | ## Example[​](#example "Direct link to Example") execute.js ``` it('should wait for the element to exist, then executes javascript on the page with the element as first argument', async () => { const text = await $('div').execute((elem, a, b, c, d) => { return elem.textContent + a + b + c + d }, 1, 2, 3, 4); // node.js context - client and console are available console.log(text); // outputs "Hello World1234" }); ``` ## Returns[​](#returns "Direct link to Returns") * **<\*>** **`return`:** The script result. --- Source: https://webdriver.io/docs/api/element/getAttribute.md # getAttribute Get an attribute from a DOM-element based on the attribute name. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).getAttribute(attributeName) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------------- | -------- | ------------------- | | `attributeName` | `string` | requested attribute | ## Examples[​](#examples "Direct link to Examples") index.html ``` <form action="/submit" method="post" class="loginForm"> <input type="text" name="name" placeholder="username"></input> <input type="text" name="password" placeholder="password"></input> <input type="submit" name="submit" value="submit"></input> </form> ``` getAttribute.js ``` it('should demonstrate the getAttribute command', async () => { const form = await $('form') const attr = await form.getAttribute('method') console.log(attr) // outputs: "post" }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<String|null>** **`return`:** The value of the attribute, or null if it is not set on the element. --- Source: https://webdriver.io/docs/api/element/getCSSProperty.md # getCSSProperty Get a css property from a DOM-element selected by given selector. The return value is formatted to be testable. Colors gets parsed via [rgb2hex](https://www.npmjs.org/package/rgb2hex) and all other properties get parsed via [css-value](https://www.npmjs.org/package/css-value). info Note that shorthand CSS properties (e.g. `background`, `font`, `border`, `margin`, `padding`, `list-style`, `outline`, `pause`, `cue`) will be expanded to fetch all longhand properties resulting in multiple WebDriver calls. If you are interested in a specific longhand property it is recommended to query for that instead. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).getCSSProperty(cssProperty, pseudoElement) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------------- | --------------- | ------------------ | | `cssProperty` | `string` | css property name | | `pseudoElement` | `PseudoElement` | css pseudo element | ## Examples[​](#examples "Direct link to Examples") example.html ``` <label id="myLabel" for="input" style="color: #0088cc; font-family: helvetica, arial, freesans, clean, sans-serif, width: 100px">Some Label</label> ``` getCSSProperty.js ``` it('should demonstrate the getCSSProperty command', async () => { const elem = await $('#myLabel') const color = await elem.getCSSProperty('color') console.log(color) // outputs the following: // { // property: 'color', // value: 'rgba(0, 136, 204, 1)', // parsed: { // hex: '#0088cc', // alpha: 1, // type: 'color', // rgba: 'rgba(0, 136, 204, 1)' // } // } const font = await elem.getCSSProperty('font-family') console.log(font) // outputs the following: // { // property: 'font-family', // value: 'helvetica', // parsed: { // value: [ 'helvetica', 'arial', 'freesans', 'clean', 'sans-serif' ], // type: 'font', // string: 'helvetica, arial, freesans, clean, sans-serif' // } // } var width = await elem.getCSSProperty('width', '::before') console.log(width) // outputs the following: // { // property: 'width', // value: '100px', // parsed: { // type: 'number', // string: '100px', // unit: 'px', // value: 100 // } // } }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<CSSProperty>** **`return`:** The specified css of the element --- Source: https://webdriver.io/docs/api/element/getComputedLabel.md # getComputedLabel Get the computed WAI-ARIA label of an element. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).getComputedLabel() ``` ## Example[​](#example "Direct link to Example") getComputedLabel.js ``` it('should demonstrate the getComputedLabel command', async () => { await browser.url('https://www.google.com/ncr') const elem = await $('*[name="q"]'); console.log(await elem.getComputedLabel()); // outputs: "Search" }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<String>** **`return`:** the computed WAI-ARIA label --- Source: https://webdriver.io/docs/api/element/getComputedRole.md # getComputedRole Get the computed WAI-ARIA label of an element. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).getComputedRole() ``` ## Example[​](#example "Direct link to Example") getComputedRole.js ``` it('should demonstrate the getComputedRole command', async () => { await browser.url('https://www.google.com/ncr') const elem = await $('*[name="q"]'); console.log(await elem.getComputedRole()); // outputs: "combobox" }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<String>** **`return`:** the computed WAI-ARIA label --- Source: https://webdriver.io/docs/api/element/getElement.md # getElement Access `WebdriverIO.Element` properties like `selector` or `elementId` from the element reference. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).getElement() ``` ## Example[​](#example "Direct link to Example") getElement.ts ``` it('should allow me to inspect WebdriverIO.Element properties', async () => { const elem = await $('#elem').getElement(); console.log(elem.selector); // outputs: '#elem' }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.Element>** --- Source: https://webdriver.io/docs/api/element/getElements.md # getElements Access `WebdriverIO.ElementArray` properties like `length` or `selector` from the elements reference. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).getElements() ``` ## Example[​](#example "Direct link to Example") getElements.ts ``` it('should allow me to inspect WebdriverIO.Element properties', async () => { const divs = await $$('div').getElements(); console.log(divs.length); // outputs: 43 }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.ElementArray>** --- Source: https://webdriver.io/docs/api/element/getHTML.md # getHTML Get source code of specified DOM element by selector. By default, it automatically pierces through all shadow roots of elements contained by the element. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).getHTML({ includeSelectorTag, pierceShadowRoot, removeCommentNodes, prettify }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | -------------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------- | | `options` | `GetHTMLOptions` | command options | | `options.includeSelectorTag`<br />*optional* | `boolean` | if true it includes the selector element tag (default: `true`) | | `options.pierceShadowRoot`<br />*optional* | `boolean` | if true it includes content of the shadow roots of all web components in the DOM (default: `true`) | | `options.removeCommentNodes`<br />*optional* | `boolean` | if true it removes all comment nodes from the HTML, e.g. `<!--?lit$206212805$--><!--?lit$206212805$-->` (default: `true`) | | `options.prettify`<br />*optional* | `boolean` | if true, the html output will be prettified (default: `true`) | ## Examples[​](#examples "Direct link to Examples") index.html ``` <div id="test"> <span>Lorem ipsum dolor amet</span> </div> ``` getHTML.js ``` it('should get html for certain elements', async () => { var outerHTML = await $('#test').getHTML(); console.log(outerHTML); // outputs: // "<div id="test"><span>Lorem ipsum dolor amet</span></div>" var innerHTML = await $('#test').getHTML({ includeSelectorTag: false }); console.log(innerHTML); // outputs: // "<span>Lorem ipsum dolor amet</span>" }); ``` getHTMLShadow\.js ``` it('allows to snapshot shadow dom', async () => { await browser.url('https://ionicframework.com/docs/usage/v8/button/basic/demo.html?ionic:mode=md') // get snapshot of web component without its styles const snapshot = await $('ion-button').getHTML({ excludeElements: ['style'] }) // assert snapshot await expect(snapshot).toMatchInlineSnapshot(` <ion-button class="md button button-solid ion-activatable ion-focusable hydrated">Default <template shadowrootmode="open"> <button type="button" class="button-native" part="native"> <span class="button-inner"> <slot name="icon-only"></slot> <slot name="start"></slot> <slot></slot> <slot name="end"></slot> </span> <ion-ripple-effect role="presentation" class="md hydrated"> <template shadowrootmode="open"></template> </ion-ripple-effect> </button> </template> </ion-button> `) }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<Promise>** **`return`:** the HTML of the specified element (as a string) --- Source: https://webdriver.io/docs/api/element/getLocation.md # getLocation Determine an element’s location on the page. The point (0, 0) refers to the upper-left corner of the page. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).getLocation(prop) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------ | -------- | ---------------------------------------------------------------------- | | `prop` | `string` | can be "x" or "y" to get a result value directly for easier assertions | ## Example[​](#example "Direct link to Example") getLocation.js ``` it('should demonstrate the getLocation function', async () => { await browser.url('http://github.com'); const logo = await $('.octicon-mark-github') const location = await logo.getLocation(); console.log(location); // outputs: { x: 150, y: 20 } const xLocation = await logo.getLocation('x') console.log(xLocation); // outputs: 150 const yLocation = await logo.getLocation('y') console.log(yLocation); // outputs: 20 }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<Object|Number>** **`return`:** The X and Y coordinates for the element on the page `{x:number, y:number}` --- Source: https://webdriver.io/docs/api/element/getProperty.md # getProperty The Get Element Property command will return the result of getting a property of an element. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).getProperty(property) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------- | -------- | ---------------------------- | | `property` | `string` | name of the element property | ## Example[​](#example "Direct link to Example") getProperty.js ``` it('should demonstrate the getProperty command', async () => { var elem = await $('body') var tag = await elem.getProperty('tagName') console.log(tag) // outputs: "BODY" }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<unknown>** **`return`:** the value of the property of the selected element --- Source: https://webdriver.io/docs/api/element/getSize.md # getSize Get the width and height for an DOM-element. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).getSize(prop) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------------------- | -------- | ------------------------------------------------- | | `prop`<br />*optional* | `String` | size to receive \[optional] ("width" or "height") | ## Example[​](#example "Direct link to Example") getSize.js ``` it('should demonstrate the getSize command', async () => { await browser.url('http://github.com') const logo = await $('.octicon-mark-github') const size = await logo.getSize() console.log(size) // outputs: { width: 32, height: 32 } const width = await logo.getSize('width') console.log(width) // outputs: 32 const height = await logo.getSize('height') console.log(height) // outputs: 32 }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<Object|Number>** **`return`:** requested element size (`{ width: <Number>, height: <Number> }`) or actual width/height as number if prop param is given --- Source: https://webdriver.io/docs/api/element/getTagName.md # getTagName Get tag name of a DOM-element. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).getTagName() ``` ## Examples[​](#examples "Direct link to Examples") index.html ``` <div id="elem">Lorem ipsum</div> ``` getTagName.js ``` it('should demonstrate the getTagName command', async () => { const elem = await $('#elem'); const tagName = await elem.getTagName(); console.log(tagName); // outputs: "div" }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<String>** **`return`:** the element's tag name, as a lowercase string --- Source: https://webdriver.io/docs/api/element/getText.md # getText Get the text content from a DOM-element. Make sure the element you want to request the text from [is interactable](http://www.w3.org/TR/webdriver/#interactable) otherwise you will get an empty string as return value. If the element is disabled or not visible and you still want to receive the text content use [getHTML](https://webdriver.io/docs/api/element/getHTML) as a workaround. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).getText() ``` ## Examples[​](#examples "Direct link to Examples") index.html ``` <div id="elem"> Lorem ipsum <strong>dolor</strong> sit amet,<br /> consetetur sadipscing elitr </div> <span style="display: none">I am invisible</span> ``` getText.js ``` it('should demonstrate the getText function', async () => { const elem = await $('#elem'); console.log(await elem.getText()); // outputs the following: // "Lorem ipsum dolor sit amet,consetetur sadipscing elitr" const span = await $('span'); console.log(await span.getText()); // outputs "" (empty string) since element is not interactable }); it('get content from table cell', async () => { await browser.url('http://the-internet.herokuapp.com/tables'); const rows = await $$('#table1 tr'); const columns = await rows[1].$$('td'); // get columns of 2nd row console.log(await columns[2].getText()); // get text of 3rd column }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<String>** **`return`:** content of selected element (all HTML tags are removed) --- Source: https://webdriver.io/docs/api/element/getValue.md # getValue Get the value of a `<textarea>`, `<select>` or text `<input>` found by given selector. If multiple elements are found via the given selector, an array of values is returned instead. For input with checkbox or radio type use isSelected. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).getValue() ``` ## Examples[​](#examples "Direct link to Examples") index.html ``` <input type="text" value="John Doe" id="username"> ``` getValue.js ``` it('should demonstrate the getValue command', async () => { const inputUser = await $('#username'); const value = await inputUser.getValue(); console.log(value); // outputs: "John Doe" }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<String>** **`return`:** requested element(s) value --- Source: https://webdriver.io/docs/api/element/isClickable.md # isClickable An element is considered to be clickable when the following conditions are met: * the element exists * the element is displayed * the element is not disabled * the element is within the viewport * the element can be scrolled into the viewport * the element's center is not overlapped with another element otherwise return false. info Please note that `isClickable` works only in web browser and in mobile webviews, it doesn't work in mobile app native context. Also, As opposed to other element commands WebdriverIO will not wait for the element to exist to execute this command. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).isClickable() ``` ## Example[​](#example "Direct link to Example") isClickable.js ``` it('should detect if an element is clickable', async () => { const el = await $('#el') let clickable = await el.isClickable(); console.log(clickable); // outputs: true or false // wait for element to be clickable await browser.waitUntil(() => el.isClickable()) }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<Boolean>** **`return`:** true if element is clickable --- Source: https://webdriver.io/docs/api/element/isDisplayed.md # isDisplayed Return true if the selected DOM-element is displayed (even when the element is outside the viewport). It is using the [`checkVisibility`](https://developer.mozilla.org/en-US/docs/Web/API/Element/checkVisibility#visibilityproperty) method provided by the browser to determine if an element is being displayed or not. Since WebdriverIO acts as a real user, the default values for the `contentVisibilityAuto`, `opacityProperty`, and `visibilityProperty` flags are set to `true` to default to a more strict behavior. This means that the command will check if the element is visible due to the value of its `content-visibility`, `opacity`, and `visibility` properties. If you want to also verify that the element is also within the viewport, provide the `withinViewport` flag to the command. info As opposed to other element commands WebdriverIO will not wait for the element to exist to execute this command. WebdriverIO, when conducting browser tests, utilizes a [custom script](https://github.com/webdriverio/webdriverio/blob/59d349ca847950354d02b9e548f60cc50e7871f0/packages/webdriverio/src/scripts/isElementDisplayed.ts) specifically designed to assess the visibility of elements. This script is key in determining whether an element is displayed on the page. Conversely, for native mobile testing scenarios with Appium, WebdriverIO defers to the [`isElementDisplayed`](https://appium.io/docs/en/2.1/reference/interfaces/appium_types.ExternalDriver/#elementdisplayed) command provided by Appium. This command evaluates the visibility of elements using criteria established by the underlying Appium driver, ensuring accurate and driver-specific assessments for mobile applications. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).isDisplayed(withinViewport, contentVisibilityAuto, opacityProperty, visibilityProperty) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | -------------------------------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | `withinViewport=false`<br />*optional* | `Boolean` | `true` to check if the element is within the viewport. `false` by default. | | `contentVisibilityAuto=true`<br />*optional* | `Boolean` | `true` to check if the element content-visibility property has (or inherits) the value auto, and it is currently skipping its rendering. `true` by default. | | `opacityProperty=true`<br />*optional* | `Boolean` | `true` to check if the element opacity property has (or inherits) a value of 0. `true` by default. | | `visibilityProperty=true`<br />*optional* | `Boolean` | `true` to check if the element is invisible due to the value of its visibility property. `true` by default. | ## Examples[​](#examples "Direct link to Examples") index.html ``` <div id="noSize"></div> <div id="noSizeWithContent">Hello World!</div> <div id="notDisplayed" style="width: 10px; height: 10px; display: none"></div> <div id="notVisible" style="width: 10px; height: 10px; visibility: hidden"></div> <div id="zeroOpacity" style="width: 10px; height: 10px; opacity: 0"></div> <div id="notInViewport" style="width: 10px; height: 10px; position:fixed; top: 999999; left: 999999"></div> ``` isDisplayed.js ``` it('should detect if an element is displayed', async () => { elem = await $('#notExisting'); isDisplayed = await elem.isDisplayed(); console.log(isDisplayed); // outputs: false let elem = await $('#noSize'); let isDisplayed = await elem.isDisplayed(); console.log(isDisplayed); // outputs: false let elem = await $('#noSizeWithContent'); let isDisplayed = await elem.isDisplayed(); console.log(isDisplayed); // outputs: true let elem = await $('#notDisplayed'); let isDisplayed = await elem.isDisplayed(); console.log(isDisplayed); // outputs: false elem = await $('#notVisible'); isDisplayed = await elem.isDisplayed(); console.log(isDisplayed); // outputs: false elem = await $('#zeroOpacity'); isDisplayed = await elem.isDisplayed(); console.log(isDisplayed); // outputs: false elem = await $('#notInViewport'); isDisplayed = await elem.isDisplayed(); console.log(isDisplayed); // outputs: true }); isDisplayedWithinViewport.js it('should detect if an element is visible within the viewport', async () => { let isDisplayedInViewport = await $('#notDisplayed').isDisplayed({ withinViewport: true }); console.log(isDisplayedInViewport); // outputs: false isDisplayedInViewport = await $('#notVisible').isDisplayed({ withinViewport: true }); console.log(isDisplayedInViewport); // outputs: false isDisplayedInViewport = await $('#notExisting').isDisplayed({ withinViewport: true }); console.log(isDisplayedInViewport); // outputs: false isDisplayedInViewport = await $('#notInViewport').isDisplayed({ withinViewport: true }); console.log(isDisplayedInViewport); // outputs: false isDisplayedInViewport = await $('#zeroOpacity').isDisplayed({ withinViewport: true }); console.log(isDisplayedInViewport); // outputs: false }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<Boolean>** **`return`:** true if element is displayed --- Source: https://webdriver.io/docs/api/element/isEnabled.md # isEnabled Return true or false if the selected DOM-element is enabled. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).isEnabled() ``` ## Examples[​](#examples "Direct link to Examples") index.html ``` <input type="text" name="inputField" class="input1"> <input type="text" name="inputField" class="input2" disabled> <input type="text" name="inputField" class="input3" disabled="disabled"> ``` isEnabled.js ``` it('should detect if an element is enabled', async () => { let elem = await $('.input1') let isEnabled = await elem.isEnabled(); console.log(isEnabled); // outputs: true elem = await $('.input2') isEnabled = await elem.isEnabled(); console.log(isEnabled2); // outputs: false elem = await $('.input3') isEnabled = await elem.isEnabled(); console.log(isEnabled3); // outputs: false }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<Boolean>** **`return`:** true if element(s)\* (is|are) enabled --- Source: https://webdriver.io/docs/api/element/isEqual.md # isEqual Return true if the selected element matches with the provided one. info As the other element commands, `isEqual` compares the elements that are on the page now. When the page renders an element again (for example a React re-render), the command finds it again with its selector, once and without a wait. An element that is gone is not equal. A strict element that matches more than once then throws a `StrictSelectorError`, as the other checks do. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).isEqual(el) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---- | --------- | ----------------------- | | `el` | `Element` | element to compare with | ## Example[​](#example "Direct link to Example") isEqual.js ``` it('should detect if an element is clickable', async () => { const el = await $('#el') const sameEl = await $('#el') const anotherEl = await $('#anotherEl') el.isEqual(sameEl) // outputs: true el.isEqual(anotherEl) // outputs: false }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<Boolean>** **`return`:** true if elements are equal --- Source: https://webdriver.io/docs/api/element/isExisting.md # isExisting Returns true if element exists in the DOM. info As opposed to other element commands WebdriverIO will not wait for the element to exist to execute this command. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).isExisting() ``` ## Examples[​](#examples "Direct link to Examples") index.html ``` <div id="notDisplayed" style="display: none"></div> <div id="notVisible" style="visibility: hidden"></div> <div id="notInViewport" style="position:absolute; left: 9999999"></div> <div id="zeroOpacity" style="opacity: 0"></div> ``` isExisting.js ``` it('should detect if elements are existing', async () => { let elem = await $('#someRandomNonExistingElement') let isExisting = await elem.isExisting() console.log(isExisting); // outputs: false elem = await $('#notDisplayed') isExisting = await elem.isExisting() console.log(isExisting); // outputs: true elem = await $('#notVisible') isExisting = await elem.isExisting() console.log(isExisting); // outputs: true elem = await $('#notInViewport') isExisting = await elem.isExisting() console.log(isExisting); // outputs: true elem = await $('#zeroOpacity') isExisting = await elem.isExisting() console.log(isExisting); // outputs: true }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<Boolean>** **`return`:** true if element(s)\* \[is|are] existing --- Source: https://webdriver.io/docs/api/element/isFocused.md # isFocused Return true or false if the selected DOM-element currently has focus. If the selector matches multiple elements, it will return true if one of the elements has focus. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).isFocused() ``` ## Examples[​](#examples "Direct link to Examples") index.html ``` <input name="login" autofocus="" /> ``` hasFocus.js ``` it('should detect the focus of an element', async () => { await browser.url('/'); const loginInput = await $('[name="login"]'); console.log(await loginInput.isFocused()); // outputs: false await loginInput.click(); console.log(await loginInput.isFocused()); // outputs: true }) ``` ## Returns[​](#returns "Direct link to Returns") * **\<Boolean>** **`return`:** true if one of the matching elements has focus --- Source: https://webdriver.io/docs/api/element/isSelected.md # isSelected Will return true or false whether or not an `<option>` or `<input>` element of type checkbox or radio is currently selected. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).isSelected() ``` ## Examples[​](#examples "Direct link to Examples") index.html ``` <select name="selectbox" id="selectbox"> <option value="John Doe">John Doe</option> <option value="Layla Terry" selected="selected">Layla Terry</option> <option value="Bill Gilbert">Bill Gilbert"</option> </select> ``` isSelected.js ``` it('should detect if an element is selected', async () => { let element = await $('[value="Layla Terry"]'); console.log(await element.isSelected()); // outputs: true element = await $('[value="Bill Gilbert"]') console.log(await element.isSelected()); // outputs: false }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<Boolean>** **`return`:** true if element is selected --- Source: https://webdriver.io/docs/api/element/isStable.md # isStable Will return true when the element is stable (not animating) or false when unstable (currently animating). We generally recommend disabling animations in your test environment instead of using this command, but this method is provided for cases where that's not feasible. **Note:** This command is only available for desktop and mobile browsers, not for native mobile apps. **Background/Inactive Tab Issue:** This command will fail with an error if the browser tab is inactive (minimized, in background, or hidden) because animations don't run in inactive tabs due to browser performance optimizations. To work around this issue, you can add Chrome options to prevent background throttling: ``` // In your wdio.conf.js capabilities: [{ browserName: 'chrome', 'goog:chromeOptions': { args: [ '--disable-backgrounding-occluded-windows', '--disable-renderer-backgrounding' ] } }] ``` ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).isStable() ``` ## Examples[​](#examples "Direct link to Examples") index.html ``` <head> <style> div { width: 200px; height: 200px; background-color: red; } #has-animation { animation: 3s 0s alternate slidein; } @keyframes slidein { from { margin-left: 100%; width: 300%; } to { margin-left: 0%; width: 100%; } } </style> </head> <body> <div #has-animation></div> <div #has-no-animation></div> </body> ``` isStable.js ``` it('should detect if an element is stable', async () => { let element = await $('#has-animation'); console.log(await element.isStable()); // outputs: false element = await $('#has-no-animation') console.log(await element.isStable()); // outputs: true }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<Boolean>** **`return`:** true if element is stable, false if unstable --- Source: https://webdriver.io/docs/api/element/moveTo.md # moveTo Move the mouse by an offset of the specified element. If no element is specified, the move is relative to the current mouse cursor. If an element is provided but no offset, the mouse will be moved to the center of the element. If the element is not visible, it will be scrolled into view. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).moveTo({ xOffset, yOffset }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `options`<br />*optional* | `MoveToOptions` | moveTo command options | | `options.xOffset`<br />*optional* | `Number` | X offset to move to, relative to the center of the element. If not specified, the mouse will move to the center of the element. | | `options.yOffset`<br />*optional* | `Number` | Y offset to move to, relative to the center of the element. If not specified, the mouse will move to the center of the element. | --- Source: https://webdriver.io/docs/api/element/nextElement.md # nextElement Returns the next sibling element of the selected DOM-element. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).nextElement() ``` ## Examples[​](#examples "Direct link to Examples") index.html ``` <div class="parent"> <p>Sibling One</p> <p>Sibling Two</p> <p>Sibling Three</p> </div> ``` nextElement.js ``` it('should get text from next sibling element', async () => { const elem = await $$('p'); const nextElement = await elem[1].nextElement() console.log(await nextElement.getText()); // outputs: "Sibling Three" }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.Element>** --- Source: https://webdriver.io/docs/api/element/parentElement.md # parentElement Returns the parent element of the selected DOM-element. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).parentElement() ``` ## Examples[​](#examples "Direct link to Examples") index.html ``` <div class="parent"> <p>Sibling One</p> <p>Sibling Two</p> <p>Sibling Three</p> </div> ``` parentElement.js ``` it('should get class from parent element', async () => { const elem = await $$('p'); const parent = await elem[2].parentElement() console.log(await parent.getAttribute('class')); // outputs: "parent" }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.Element>** --- Source: https://webdriver.io/docs/api/element/previousElement.md # previousElement Returns the previous sibling element of the selected DOM-element. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).previousElement() ``` ## Examples[​](#examples "Direct link to Examples") index.html ``` <div class="parent"> <p>Sibling One</p> <p>Sibling Two</p> <p>Sibling Three</p> </div> ``` previousElement.js ``` it('should get text from previous sibling element', async () => { const elem = await $$('p'); const previousElem = await elem[1].previousElement() console.log(await previousElem.getText()); // outputs: "Sibling One" }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.Element>** --- Source: https://webdriver.io/docs/api/element/react$$.md # react$$ The `react$$` command is a useful command to query multiple React Components by their actual name and filter them by props and state. It returns a [`WebdriverIO.ElementArray`](/docs/api/browser/$$.md), the same list as [`$$`](/docs/api/browser/$$.md). info The command works with applications using React v16 to v19, with `createRoot` or `ReactDOM.render`. Read more about React selectors in the [Selectors](/docs/selectors.md#react-selectors) guide. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).react$$(selector, { props, state }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------------- | --------------------------------------------- | -------------------------------------- | | `selector` | `string` | of React component | | `options`<br />*optional* | `ReactSelectorOptions` | React selector options | | `options.props`<br />*optional* | `Object` | React props the element should contain | | `options.state`<br />*optional* | `Array<any>, number, string, object, boolean` | React state the element should be in | ## Example[​](#example "Direct link to Example") pause.js ``` it('should calculate 7 * 6', async () => { await browser.url('https://ahfarmer.github.io/calculator/'); const orangeButtons = await browser.react$$('t', { props: { orange: true } }) console.log(await orangeButtons.map((btn) => btn.getText())); // prints "[ '÷', 'x', '-', '+', '=' ]" }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.ElementArray>** --- Source: https://webdriver.io/docs/api/element/react$.md # react$ The `react$` command is a useful command to query React Components by their actual name and filter them by props and state. info The command works with applications using React v16 to v19, with `createRoot` or `ReactDOM.render`. Read more about React selectors in the [Selectors](/docs/selectors.md#react-selectors) guide. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).react$(selector, { props, state }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------------- | --------------------------------------------- | -------------------------------------- | | `selector` | `string` | of React component | | `options`<br />*optional* | `ReactSelectorOptions` | React selector options | | `options.props`<br />*optional* | `Object` | React props the element should contain | | `options.state`<br />*optional* | `Array<any>, number, string, object, boolean` | React state the element should be in | ## Example[​](#example "Direct link to Example") pause.js ``` it('should calculate 7 * 6', async () => { await browser.url('https://ahfarmer.github.io/calculator/'); const appWrapper = await browser.$('div#root') await browser.react$('t', { props: { name: '7' } }).click() await browser.react$('t', { props: { name: 'x' } }).click() await browser.react$('t', { props: { name: '6' } }).click() await browser.react$('t', { props: { name: '=' } }).click() console.log(await $('.component-display').getText()); // prints "42" }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.Element>** --- Source: https://webdriver.io/docs/api/element/saveScreenshot.md # saveScreenshot Save a screenshot of an element to a PNG file on your OS. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).saveScreenshot(filename) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------- | -------- | ------------------------------------------------------------------------------------------- | | `filename` | `String` | path to the generated image (`.png` suffix is required) relative to the execution directory | ## Example[​](#example "Direct link to Example") saveScreenshot.js ``` it('should save a screenshot of the browser view', async () => { const elem = await $('#someElem'); await elem.saveScreenshot('./some/path/elemScreenshot.png'); }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<Buffer>** **`return`:** screenshot buffer --- Source: https://webdriver.io/docs/api/element/scrollIntoView.md # scrollIntoView Scroll element into viewport for Desktop/Mobile Web **AND** Mobile Native Apps. info Scrolling for Mobile Native Apps is done based on the mobile `swipe` command. info On Desktop/Mobile Web, browsers apply wheel-driven scrolling asynchronously, so this command waits until the scroll position stops changing before resolving. This ensures the element is actually in its final position by the time subsequent commands run. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).scrollIntoView({ behavior, block, inline, direction, maxScrolls, duration, scrollableElement, percent }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------------------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `options`<br />*optional* | `object, boolean` | options for `Element.scrollIntoView()`. Default for desktop/mobile web:<br />`{ block: 'start', inline: 'nearest' }`<br />Default for Mobile Native App<br />`{ maxScrolls: 10, scrollDirection: 'down' }` | | **Desktop/Mobile Web Only** | | | | `options.behavior`<br />*optional* | `string` | See [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView).<br />**WEB-ONLY** (Desktop/Mobile) | | `options.block`<br />*optional* | `string` | See [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView).<br />**WEB-ONLY** (Desktop/Mobile) | | `options.inline`<br />*optional* | `string` | See [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView).<br />**WEB-ONLY** (Desktop/Mobile) | | **Mobile Native App Only** | | | | `options.direction`<br />*optional* | `string` | Can be one of `down`, `up`, `left` or `right`, default is `up`.<br />**MOBILE-NATIVE-APP-ONLY** | | `options.maxScrolls`<br />*optional* | `number` | The max amount of scrolls until it will stop searching for the element, default is `10`.<br />**MOBILE-NATIVE-APP-ONLY** | | `options.duration`<br />*optional* | `number` | The duration in milliseconds for the swipe. Default is `1500` ms. The lower the value, the faster the swipe.<br />**MOBILE-NATIVE-APP-ONLY** | | `options.scrollableElement`<br />*optional* | `Element` | Element that is used to scroll within. If no element is provided it will use the following selector for iOS `-ios predicate string:type == "XCUIElementTypeApplication"` and the following for Android `//android.widget.ScrollView'`. If more elements match the default selector, then by default it will pick the first matching element.<br />**MOBILE-NATIVE-APP-ONLY** | | `options.percent`<br />*optional* | `number` | The percentage of the (default) scrollable element to swipe. This is a value between 0 and 1. Default is `0.95`.<br />**NEVER** swipe from the exact top\|bottom\|left\|right of the screen, you might trigger for example the notification bar or other OS/App features which can lead to unexpected results.<br />**MOBILE-NATIVE-APP-ONLY** | ## Examples[​](#examples "Direct link to Examples") desktop.mobile.web.scrollIntoView\.js ``` it('should demonstrate the desktop/mobile web scrollIntoView command', async () => { const elem = await $('#myElement'); // scroll to specific element await elem.scrollIntoView(); // center element within the viewport await elem.scrollIntoView({ block: 'center', inline: 'center' }); }); ``` mobile.native.app.scrollIntoView\.js ``` it('should demonstrate the mobile native app scrollIntoView command', async () => { const elem = await $('#myElement'); // scroll to a specific element in the default scrollable element for Android or iOS for a maximum of 10 scrolls await elem.scrollIntoView(); // Scroll to the left in the scrollable element called '#scrollable' for a maximum of 5 scrolls await elem.scrollIntoView({ direction: 'left', maxScrolls: 5, scrollableElement: $('#scrollable') }); }); ``` --- Source: https://webdriver.io/docs/api/element/selectByAttribute.md # selectByAttribute Select option with a specific value. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).selectByAttribute(attribute, value) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ----------- | ---------------- | ------------------------------------------- | | `attribute` | `string` | attribute of option element to get selected | | `value` | `String, Number` | value of option element to get selected | ## Examples[​](#examples "Direct link to Examples") example.html ``` <select id="selectbox"> <option value="someValue0">uno</option> <option value="someValue1">dos</option> <option value="someValue2">tres</option> <option value="someValue3">cuatro</option> <option value="someValue4">cinco</option> <option name="someName5" value="someValue5">seis</option> </select> ``` selectByAttribute.js ``` it('Should demonstrate the selectByAttribute command', async () => { const selectBox = await $('#selectbox'); const value = await selectBox.getValue(); console.log(value); // returns "someValue0" await selectBox.selectByAttribute('value', 'someValue3'); console.log(await selectBox.getValue()); // returns "someValue3" await selectBox.selectByAttribute('name', 'someName5'); console.log(await selectBox.getValue()); // returns "someValue5" }); ``` --- Source: https://webdriver.io/docs/api/element/selectByIndex.md # selectByIndex Select option with a specific index. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).selectByIndex(index) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------- | -------- | ------------ | | `index` | `number` | option index | ## Examples[​](#examples "Direct link to Examples") example.html ``` <select id="selectbox"> <option value="someValue0">uno</option> <option value="someValue1">dos</option> <option value="someValue2">tres</option> <option value="someValue3">cuatro</option> <option value="someValue4">cinco</option> <option value="someValue5">seis</option> </select> ``` selectByIndex.js ``` it('Should demonstrate the selectByIndex command', async () => { const selectBox = await $('#selectbox'); console.log(await selectBox.getValue()); // returns "someValue0" await selectBox.selectByIndex(4); console.log(await selectBox.getValue()); // returns "someValue4" }); ``` --- Source: https://webdriver.io/docs/api/element/selectByVisibleText.md # selectByVisibleText Select option with displayed text matching the argument. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).selectByVisibleText(text) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------ | ---------------- | -------------------------------------- | | `text` | `String, Number` | text of option element to get selected | ## Examples[​](#examples "Direct link to Examples") example.html ``` <select id="selectbox"> <option value="someValue0">uno</option> <option value="someValue1">dos</option> <option value="someValue2">tres</option> <option value="someValue3">cuatro</option> <option value="someValue4">cinco</option> <option value="someValue5">seis</option> </select> ``` selectByVisibleText.js ``` it('demonstrate the selectByVisibleText command', async () => { const selectBox = await $('#selectbox'); console.log(await selectBox.getText('option:checked')); // returns "uno" await selectBox.selectByVisibleText('cuatro'); console.log(await selectBox.getText('option:checked')); // returns "cuatro" }) ``` --- Source: https://webdriver.io/docs/api/element/setFiles.md # setFiles Set the files of an `<input type="file">` with the WebDriver BiDi [`input.setFiles`](https://w3c.github.io/webdriver-bidi/#command-input-setFiles) command. The paths are opened by the browser. They are not copied and not uploaded. A relative path is resolved against `process.cwd()`, so a path the test process can open is the path a local browser opens. A remote browser needs a path on the machine that runs the browser. This command needs a BiDi session. On a classic session, [`setValue`](/docs/api/element/setValue.md) still types a path the local browser can already see. Passing more than one path to an input without `multiple`, a disabled input, or an element that is not a file input fails with the BiDi error `unable to set file input`. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).setFiles(files) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------- | ------------------ | ------------------------------------------ | | `files` | `string, string[]` | path or paths the browser machine can read | ## Example[​](#example "Direct link to Example") setFiles.js ``` it('sets a file input', async () => { await $('#file-upload').setFiles('/path/to/file.png') await $('#file-upload').setFiles(['/path/to/a.png', '/path/to/b.png']) }); ``` --- Source: https://webdriver.io/docs/api/element/setValue.md # setValue Input types whose value can't be typed: a range input ignores key strokes, and date and time inputs split their value into segments that typing fills in the browser's locale order, so "2026-10-04" ends up as "61004-02-02". `setValue` sets their value like the browser's own picker does instead. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).setValue() ``` --- Source: https://webdriver.io/docs/api/element/shadow$$.md # shadow$$ Access elements inside a given element's shadowRoot. The result is a [`WebdriverIO.ElementArray`](/docs/api/browser/$$.md), the same list as [`$$`](/docs/api/browser/$$.md). If you are working with lots of nested shadow roots, an alternative approach to `shadow$$` is to use the [deep selector](https://webdriver.io/docs/selectors#deep-selectors). info WebdriverIO automatically pierces through shadow roots when using `$` or `$$` commands. This command is only needed if you automate within an environment that doesn't support WebDriver Bidi yet, e.g. mobile web testing with Appium. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).shadow$$(selector) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------- | ------------------ | -------------------------------------------------- | | `selector` | `String, Function` | selector or JS Function to fetch a certain element | ## Example[​](#example "Direct link to Example") shadow$$.js ``` it('should return elements inside a shadowRoot', async () => { const innerEl = await $('.input').shadow$$('#innerEl'); console.log(await innerEl.getValue()); // outputs: 'test123' }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.ElementArray>** --- Source: https://webdriver.io/docs/api/element/shadow$.md # shadow$ Access an element inside a given element's shadowRoot. If you are working with lots of nested shadow roots, an alternative approach to `shadow$` is to use the [deep selector](https://webdriver.io/docs/selectors#deep-selectors). info WebdriverIO automatically pierces through shadow roots when using `$` or `$$` commands. This command is only needed if you automate within an environment that doesn't support WebDriver Bidi yet, e.g. mobile web testing with Appium. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).shadow$(selector) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------- | ------------------ | -------------------------------------------------- | | `selector` | `String, Function` | selector or JS Function to fetch a certain element | ## Example[​](#example "Direct link to Example") shadow$$.js ``` it('should return an element inside a shadowRoot', async () => { const innerEl = await $('custom-component').shadow$('#innerEl'); console.log(await innerEl.getValue()); // outputs: 'test123' }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<WebdriverIO.Element>** --- Source: https://webdriver.io/docs/api/element/waitForClickable.md # waitForClickable Wait for an element for the provided amount of milliseconds to be clickable or not clickable. info As opposed to other element commands WebdriverIO will not wait for the element to exist to execute this command. This command is only available for desktop and mobile browsers, not for native mobile apps. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).waitForClickable({ timeout, reverse, timeoutMsg, interval }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------------------ | ---------------- | -------------------------------------------------------------------------------------------------------- | | `options`<br />*optional* | `WaitForOptions` | waitForEnabled options (optional) | | `options.timeout`<br />*optional* | `Number` | time in ms (default set based on [`waitforTimeout`](/docs/configuration.md#waitfortimeout) config value) | | `options.reverse`<br />*optional* | `Boolean` | if true it waits for the opposite (default: false) | | `options.timeoutMsg`<br />*optional* | `String` | if exists it overrides the default error message | | `options.interval`<br />*optional* | `Number` | interval between checks (default: `waitforInterval`) | ## Example[​](#example "Direct link to Example") waitForClickable.js ``` it('should detect when element is clickable', async () => { const elem = await $('#elem') await elem.waitForClickable({ timeout: 3000 }); }); it('should detect when element is no longer clickable', async () => { const elem = await $('#elem') await elem.waitForClickable({ reverse: true }); }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<Boolean>** **`return`:** `true` if element is clickable (or doesn't if flag is set) --- Source: https://webdriver.io/docs/api/element/waitForDisplayed.md # waitForDisplayed `true` to check if the element is within the viewport. false by default. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).waitForDisplayed() ``` --- Source: https://webdriver.io/docs/api/element/waitForEnabled.md # waitForEnabled Wait for an element (selected by css selector) for the provided amount of milliseconds to be (dis/en)abled. If multiple elements get queried by given selector, it returns true if at least one element is (dis/en)abled. info As opposed to other element commands WebdriverIO will not wait for the element to exist to execute this command. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).waitForEnabled({ timeout, reverse, timeoutMsg, interval }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------------------ | ---------------- | -------------------------------------------------------------------------------------------------------- | | `options`<br />*optional* | `WaitForOptions` | waitForEnabled options (optional) | | `options.timeout`<br />*optional* | `Number` | time in ms (default set based on [`waitforTimeout`](/docs/configuration.md#waitfortimeout) config value) | | `options.reverse`<br />*optional* | `Boolean` | if true it waits for the opposite (default: false) | | `options.timeoutMsg`<br />*optional* | `String` | if exists it overrides the default error message | | `options.interval`<br />*optional* | `Number` | interval between checks (default: `waitforInterval`) | ## Examples[​](#examples "Direct link to Examples") index.html ``` <input type="text" id="username" value="foobar" disabled="disabled"></input> <script type="text/javascript"> setTimeout(() => { document.getElementById('username').disabled = false }, 2000); </script> ``` waitForEnabledExample.js ``` it('should detect when element is enabled', async () => { await $('#username').waitForEnabled({ timeout: 3000 }); }); it('should detect when element is disabled', async () => { elem = await $('#username'); await elem.waitForEnabled({ reverse: true }) }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<Boolean>** **`return`:** true if element is (dis/en)abled --- Source: https://webdriver.io/docs/api/element/waitForExist.md # waitForExist Wait for an element for the provided amount of milliseconds to be present within the DOM. Returns true if the selector matches at least one element that exists in the DOM, otherwise throws an error. If the reverse flag is true, the command will instead return true if the selector does not match any elements. info As opposed to other element commands WebdriverIO will not wait for the element to exist to execute this command. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).waitForExist({ timeout, reverse, timeoutMsg, interval }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------------------ | ---------------- | -------------------------------------------------------------------------------------------------------- | | `options`<br />*optional* | `WaitForOptions` | waitForEnabled options (optional) | | `options.timeout`<br />*optional* | `Number` | time in ms (default set based on [`waitforTimeout`](/docs/configuration.md#waitfortimeout) config value) | | `options.reverse`<br />*optional* | `Boolean` | if true it waits for the opposite (default: false) | | `options.timeoutMsg`<br />*optional* | `String` | if exists it overrides the default error message | | `options.interval`<br />*optional* | `Number` | interval between checks (default: `waitforInterval`) | ## Example[​](#example "Direct link to Example") waitForExistSyncExample.js ``` it('should display a notification message after successful form submit', async () => { const form = await $('form'); const notification = await $('.notification'); await form.$(".send").click(); await notification.waitForExist({ timeout: 5000 }); expect(await notification.getText()).to.be.equal('Data transmitted successfully!') }); it('should remove a message after successful form submit', async () => { const form = await $('form'); const message = await $('.message'); await form.$(".send").click(); await message.waitForExist({ reverse: true }); }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<Boolean>** **`return`:** true if element exists (or doesn't if flag is set) --- Source: https://webdriver.io/docs/api/element/waitForStable.md # waitForStable Wait for an element for the provided amount of milliseconds to be stable (not animating). Returns true if the selector matches at least one element that is stable in the DOM, otherwise throws an error. If the reverse flag is true, the command will instead return true if the selector does not match any stable elements. **Note 1:** it's best to disable animations instead of using this command **Note 2:** this command is only available for desktop and mobile browsers, not for native mobile apps. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).waitForStable({ timeout, reverse, timeoutMsg, interval }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------------------ | ---------------- | -------------------------------------------------------------------------------------------------------- | | `options`<br />*optional* | `WaitForOptions` | waitForStable options (optional) | | `options.timeout`<br />*optional* | `Number` | time in ms (default set based on [`waitforTimeout`](/docs/configuration.md#waitfortimeout) config value) | | `options.reverse`<br />*optional* | `Boolean` | if true it waits for the opposite (default: false) | | `options.timeoutMsg`<br />*optional* | `String` | if exists it overrides the default error message | | `options.interval`<br />*optional* | `Number` | interval between checks (default: `waitforInterval`) | ## Examples[​](#examples "Direct link to Examples") index.html ``` <head> <style> div { width: 200px; height: 200px; background-color: red; } #has-animation { animation: 3s 0s alternate slidein; } @keyframes slidein { from { margin-left: 100%; width: 300%; } to { margin-left: 0%; width: 100%; } } </style> </head> <body> <div #has-animation></div> <div #has-no-animation></div> </body> ``` waitForStable.js ``` it('should detect that element is instable and will wait for the element to become stable', async () => { const elem = await $('#has-animation') await elem.waitForStable({ timeout: 3000 }); }); it('should detect that element is stable and will not wait', async () => { const elem = await $('#has-no-animation') await elem.waitForStable(); }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<Boolean>** **`return`:** true if element is stable --- Source: https://webdriver.io/docs/api/element/waitUntil.md # waitUntil This wait command is your universal weapon if you want to wait on something. It expects a condition and waits until that condition is fulfilled with a truthy value. info As opposed to other element commands WebdriverIO will not wait for the element to exist to execute this command. A common example is to wait until a certain element contains a certain text (see example). ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).waitUntil(condition, { timeout, timeoutMsg, interval }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------------------ | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- | | `condition` | `Function` | condition to wait on | | `options`<br />*optional* | `WaitUntilOptions` | command options | | `options.timeout`<br />*optional* | `Number` | time in ms (default set based on [`waitforTimeout`](/docs/configuration.md#waitfortimeout) config value) | | `options.timeoutMsg`<br />*optional* | `String, Function` | error message to throw when waitUntil times out. A function is evaluated only after the timeout, so the message can include state from that moment. | | `options.interval`<br />*optional* | `Number` | interval between condition checks (default set based on [`waitforInterval`](/docs/configuration.md#waitforinterval) config value) | ## Examples[​](#examples "Direct link to Examples") index.html ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/0bfb2b8d212b627a2659b10f4449184b657e1d59/waitUntil/index.html#L3-L8 >) waitUntilExample.js ``` loading... ``` [View on GitHub](<https://github.com/webdriverio/example-recipes/blob/0bfb2b8d212b627a2659b10f4449184b657e1d59/waitUntil/waitUntilExample.js#L6-L14 >) ## Returns[​](#returns "Direct link to Returns") * **\<Boolean>** **`return`:** true if condition is fulfilled --- Source: https://webdriver.io/docs/api/mobile.md # Introduction to custom and enhanced Mobile Commands in WebdriverIO Testing mobile apps and mobile web applications comes with its own challenges, especially when dealing with platform-specific differences between Android and iOS. While Appium provides the flexibility to handle these differences, it often requires you to dive deep into complex, platform-dependent docs ([Android](https://appium.github.io/appium-uiautomator2-driver/latest/reference/execute-methods/#gestures), [iOS](https://appium.github.io/appium-xcuitest-driver/latest/reference/execute-methods/)) and commands. This can make writing test scripts more time-consuming, error-prone, and difficult to maintain. To simplify the process, WebdriverIO introduces **custom and enhanced mobile commands** tailored specifically for mobile web and native app testing. These commands abstract away the intricacies of underlying Appium APIs, enabling you to write concise, intuitive, and platform-agnostic test scripts. By focusing on ease of use, we aim to reduce the extra load while developing Appium scripts and empower you to automate mobile apps effortlessly. ## Why Custom Mobile Commands?[​](#why-custom-mobile-commands "Direct link to Why Custom Mobile Commands?") ### 1. **Simplifying Complex APIs**[​](#1-simplifying-complex-apis "Direct link to 1-simplifying-complex-apis") Some Appium commands, like gestures or element interactions, involve verbose and intricate syntax. For example, executing a long press action with the native Appium API requires constructing an `action` chain manually: ``` const element = $('~Contacts') await browser .action( 'pointer', { parameters: { pointerType: 'touch' } }) .move({ origin: element }) .down() .pause(1500) .up() .perform() ``` With WebdriverIO's custom commands, the same action can be performed with a single, expressive line of code: ``` await $('~Contacts').longPress(); ``` This drastically reduces boilerplate code, making your scripts cleaner and easier to understand. ### 2. **Cross-Platform Abstraction**[​](#2-cross-platform-abstraction "Direct link to 2-cross-platform-abstraction") Mobile apps often require platform-specific handling. For instance, scrolling in native apps differs significantly between [Android](https://appium.github.io/appium-uiautomator2-driver/latest/reference/execute-methods/#mobile-scrollgesture) and [iOS](https://appium.github.io/appium-xcuitest-driver/latest/reference/execute-methods/#mobile-scroll). WebdriverIO bridges this gap by providing unified commands like `scrollIntoView()` that work seamlessly across platforms, regardless of the underlying implementation. ``` await $('~element').scrollIntoView(); ``` This abstraction ensures your tests are portable and do not require constant branching or conditional logic to account for OS differences. ### 3. **Increased Productivity**[​](#3-increased-productivity "Direct link to 3-increased-productivity") By reducing the need to understand and implement low-level Appium commands, WebdriverIO's mobile commands enable you to focus on testing your app's functionality rather than wrestling with platform-specific nuances. This is especially beneficial for teams with limited experience in mobile automation or those seeking to accelerate their development cycle. ### 4. **Consistency and Maintainability**[​](#4-consistency-and-maintainability "Direct link to 4-consistency-and-maintainability") Custom commands bring uniformity to your test scripts. Instead of having varying implementations for similar actions, your team can rely on standardized, reusable commands. This not only makes the codebase more maintainable but also lowers the barrier for onboarding new team members. ## Why enhance certain mobile commands?[​](#why-enhance-certain-mobile-commands "Direct link to Why enhance certain mobile commands?") ### 1. Adding Flexibility[​](#1-adding-flexibility "Direct link to 1. Adding Flexibility") Certain mobile commands are enhanced to provide additional options and parameters that aren't available in the default Appium APIs. For example, WebdriverIO adds retry logic, timeouts, and the ability to filter webviews by specific criteria, enabling more control over complex scenarios. ``` // Example: Customizing retry intervals and timeouts for webview detection await driver.getContexts({ returnDetailedContexts: true, androidWebviewConnectionRetryTime: 1000, // Retry every 1 second androidWebviewConnectTimeout: 10000, // Timeout after 10 seconds }); ``` These options help adapt automation scripts to dynamic app behavior without additional boilerplate code. ### 2. Improving Usability[​](#2-improving-usability "Direct link to 2. Improving Usability") Enhanced commands abstract away complexities and repetitive patterns found in the native APIs. They allow you to perform more actions with fewer lines of code, reducing the learning curve for new users and making scripts easier to read and maintain. ``` // Example: Enhanced command for switching context by title await driver.switchContext({ title: 'My Webview Title', }); ``` Compared to the default Appium methods, enhanced commands eliminate the need for additional steps like manually retrieving available contexts and filtering through them. ### 3. Standardizing Behavior[​](#3-standardizing-behavior "Direct link to 3. Standardizing Behavior") WebdriverIO ensures that enhanced commands behave consistently across platforms like Android and iOS. This cross-platform abstraction minimizes the need for conditionally branching logic based on the operating system, leading to more maintainable test scripts. ``` // Example: Unified scroll command for both platforms await $('~element').scrollIntoView(); ``` This standardization simplifies codebases, especially for teams automating tests on multiple platforms. ### 4. Increasing Reliability[​](#4-increasing-reliability "Direct link to 4. Increasing Reliability") By incorporating retry mechanisms, smart defaults, and detailed error messages, enhanced commands reduce the likelihood of flaky tests. These improvements ensure your tests are resilient to issues like delays in webview initialization or transient app states. ``` // Example: Enhanced webview switching with robust matching logic await driver.switchContext({ url: /.*my-app\/dashboard/, androidWebviewConnectionRetryTime: 500, androidWebviewConnectTimeout: 7000, }); ``` This makes test execution more predictable and less prone to failures caused by environmental factors. ### 5. Enhancing Debugging Capabilities[​](#5-enhancing-debugging-capabilities "Direct link to 5. Enhancing Debugging Capabilities") Enhanced commands often return richer metadata, enabling easier debugging of complex scenarios, particularly in hybrid apps. For instance, commands like getContext and getContexts can return detailed information about webviews, including title, url, and visibility status. ``` // Example: Retrieving detailed metadata for debugging const contexts = await driver.getContexts({ returnDetailedContexts: true }); console.log(contexts); ``` This metadata helps identify and resolve issues faster, improving the overall debugging experience. By enhancing mobile commands, WebdriverIO not only makes automation easier but also aligns with its mission to provide developers with tools that are powerful, reliable, and intuitive to use. ## Hybrid Apps[​](#hybrid-apps "Direct link to Hybrid Apps") Hybrid apps combine web content with native functionality and require specialized handling during automation. These apps use webviews to render web content within a native application. WebdriverIO provides enhanced methods for working with hybrid apps effectively. ### Understanding Webviews[​](#understanding-webviews "Direct link to Understanding Webviews") A webview is a browser-like component embedded in a native app: * **Android:** Webviews are based on Chrome/System Webview and may contain multiple pages (similar to browser tabs). These webviews require ChromeDriver to automate interactions. Appium can automatically determine the required ChromeDriver version based on the version of the System WebView or Chrome installed on the device and download it automatically if not already available. This approach ensures seamless compatibility and minimizes manual setup. Refer to the [Appium UIAutomator2-documentation](https://appium.github.io/appium-uiautomator2-driver/latest/guides/hybrid/#automatic-discovery) to learn how Appium automatically downloads the correct ChromeDriver version. * **iOS:** Webviews are powered by Safari (WebKit) and identified by generic IDs like `WEBVIEW_{id}`. ### Challenges with Hybrid Apps[​](#challenges-with-hybrid-apps "Direct link to Challenges with Hybrid Apps") 1. Identifying the correct webview among multiple options. 2. Retrieving additional metadata such as the title, URL, or package name for better context. 3. Handling platform-specific differences between Android and iOS. 4. Switching to the correct context in a hybrid app reliably. ### Key Commands for Hybrid Apps[​](#key-commands-for-hybrid-apps "Direct link to Key Commands for Hybrid Apps") #### 1. `getContext`[​](#1-getcontext "Direct link to 1-getcontext") Retrieves the current context of the session. By default, it behaves like Appium's getContext method but can provide detailed context information when `returnDetailedContext` is enabled. For more information see [`getContext`](/docs/api/mobile/getContext.md) #### 2. `getContexts`[​](#2-getcontexts "Direct link to 2-getcontexts") Returns a detailed list of available contexts, improving upon Appium's contexts method. This makes it easier to identify the correct webview for interaction without calling extra commands to determine title, url or active `bundleId|packageName`. For more information see [`getContexts`](/docs/api/mobile/getContexts.md) #### 3. `switchContext`[​](#3-switchcontext "Direct link to 3-switchcontext") Switches to a specific webview based on name, title, or url. Provides additional flexibility, such as using regular expressions for matching. For more information see [`switchContext`](/docs/api/mobile/switchContext.md) ### Key Features for Hybrid Apps[​](#key-features-for-hybrid-apps "Direct link to Key Features for Hybrid Apps") 1. Detailed Metadata: Retrieve comprehensive details for debugging and reliable context switching. 2. Cross-Platform Consistency: Unified behavior for Android and iOS, handling platform-specific quirks seamlessly. 3. Custom Retry Logic (Android): Adjust retry intervals and timeouts for webview detection. Notes and Limitations * Android provides additional metadata, such as `packageName` and `webviewPageId`, while iOS focuses on `bundleId`. * Retry logic is customizable for Android but not applicable to iOS. * There are several cases that iOS can't find the Webview. Appium provides different extra capabilities for the `appium-xcuitest-driver` to find the Webview. If you believe that the Webview is not found, you can try to set one of the following capabilities: <!-- --> * `appium:includeSafariInWebviews`: Add Safari web contexts to the list of contexts available during a native/webview app test. This is useful if the test opens Safari and needs to be able to interact with it. Defaults to `false`. * `appium:webviewConnectRetries`: The maximum number of retries before giving up on web view pages detection. The delay between each retry is 500ms, default is `10` retries. * `appium:webviewConnectTimeout`: The maximum amount of time in milliseconds to wait for a web view page to be detected. Default is `5000` ms. For advanced examples and details, see the WebdriverIO Mobile API documentation. *** Our growing set of commands reflects our commitment to making mobile automation accessible and elegant. Whether you’re performing intricate gestures or working with native app elements, these commands align with WebdriverIO’s philosophy of creating a seamless automation experience. And we’re not stopping here—if there’s a feature you’d like to see, we welcome your feedback. Feel free to submit your requests via [this link](https://github.com/webdriverio/webdriverio/issues/new/choose). --- Source: https://webdriver.io/docs/api/mobile/acceptDialog.md # acceptDialog Accept a native mobile alert or permission dialog. Unlike browser dialogs which emit a `dialog` event, mobile permission dialogs and system alerts are already on screen when the test reaches them. Call this command to accept the dialog in place. info This command only works with the following up-to-date components: * Appium server (version 2.0.0 or higher) * `appium-uiautomator2-driver` (for Android) * `appium-xcuitest-driver` (for iOS) Make sure your local or cloud-based Appium environment is regularly updated to avoid compatibility issues. ## Usage[​](#usage "Direct link to Usage") ``` await browser.acceptDialog(buttonText) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------------------------- | -------- | --------------------------------------------------------------------------------------------------------- | | `buttonText`<br />*optional* | `string` | The text of the button to tap (e.g. `Allow`, `OK`, `Yes`). If omitted, the default accept action is used. | ## Example[​](#example "Direct link to Example") acceptDialog.js ``` it('should accept a permission dialog', async () => { // Accept an iOS permission dialog by button label await browser.acceptDialog('Allow') // Accept an Android alert await browser.acceptDialog('OK') // Accept whatever the default/first button is await browser.acceptDialog() }) ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/background.md # background Send the currently running app for this session to the background. Pass `-1` to keep the app in the background indefinitely, or `null` to send the app to the background without restoring it. ## Usage[​](#usage "Direct link to Usage") ``` await browser.background(seconds) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `seconds` | `number, null` | Number of seconds to background the app. Pass `-1` to keep it<br />in the background indefinitely, or `null` to not restore it. | ## Example[​](#example "Direct link to Example") background.js ``` it('should background the app', async () => { // Background the app for 5 seconds await browser.background(5) // Background the app indefinitely await browser.background(-1) }) ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/closeApp.md # closeApp Close a specific app or the currently active app on the device. If no `bundleId` (iOS) or `appId` (Android) is provided, the command will automatically detect and close the currently active app. ## Usage[​](#usage "Direct link to Usage") ``` await browser.closeApp({ bundleId, appId }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------ | | `options`<br />*optional* | `object` | Options for closing the app (optional) | | `options.bundleId`<br />*optional* | `string` | The bundle ID of the iOS app to close. If not provided, the currently active app is closed.<br />**iOS-ONLY** | | `options.appId`<br />*optional* | `string` | The package name of the Android app to close. If not provided, the currently active app is closed.<br />**ANDROID-ONLY** | ## Example[​](#example "Direct link to Example") closeApp.js ``` it('should close the currently active app', async () => { // Automatically close the currently active app await browser.closeApp() }) it('should close a specific iOS app by bundleId', async () => { // iOS: close a specific app using its bundle ID await browser.closeApp({ bundleId: 'com.example.myapp' }) }) it('should close a specific Android app by appId', async () => { // Android: close a specific app using its package name await browser.closeApp({ appId: 'com.example.myapp' }) }) ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/deepLink.md # deepLink Open a deep link URL in the mobile app based on the url and the app's package name (Android) or bundle ID (iOS). ## Usage[​](#usage "Direct link to Usage") ``` await browser.deepLink(link, appIdentifier, waitForLaunch) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `link` | `string` | The deep link URL that should be opened in the mobile app. It should be a valid deep link URL (e.g. `myapp://path`). If it's a universal deep link, which can be used for iOS, use the `browser.url("your-url")`-method. | | `appIdentifier` | `string` | The value of the `package` (Android) or `bundleId` (iOS) of the app that the deep link should open. | | `waitForLaunch`<br />*optional* | `boolean` | Whether to wait for the app to launch after opening the deep link. Default is `true`.<br />**ANDROID-ONLY** | ## Example[​](#example "Direct link to Example") deeplink.js ``` it('should open a deep link for the WDIO native demo app', async () => { // open the Drag tab with a deep link (this the bundleId for the iOS Demo App) await browser.deepLink('wdio://drag', 'org.reactjs.native.example.wdiodemoapp'); // Or open the Drag tab with a deep link (this the package name for the Android Demo App) await browser.deepLink('wdio://drag', 'com.wdiodemoapp'); // Or if you want to have it "cross-platform" you can use it like this await browser.deepLink('wdio://drag', browser.isIOS ? 'org.reactjs.native.example.wdiodemoapp' : 'com.wdiodemoapp'); }) it('should open a deep link without waiting for the app to launch (Android)', async () => { // Android-only: do not wait for the app to launch after opening the deep link await browser.deepLink('wdio://drag', 'com.wdiodemoapp', false) }) ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/dismissDialog.md # dismissDialog Dismiss a native mobile alert or permission dialog. Unlike browser dialogs which emit a `dialog` event, mobile permission dialogs and system alerts are already on screen when the test reaches them. Call this command to dismiss the dialog in place. info This command only works with the following up-to-date components: * Appium server (version 2.0.0 or higher) * `appium-uiautomator2-driver` (for Android) * `appium-xcuitest-driver` (for iOS) Make sure your local or cloud-based Appium environment is regularly updated to avoid compatibility issues. ## Usage[​](#usage "Direct link to Usage") ``` await browser.dismissDialog(buttonText) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------- | | `buttonText`<br />*optional* | `string` | The text of the button to tap (e.g. `Cancel`, `Don't Allow`, `No`). If omitted, the default dismiss action is used. | ## Example[​](#example "Direct link to Example") dismissDialog.js ``` it('should dismiss a permission dialog', async () => { // Dismiss an iOS permission dialog by button label await browser.dismissDialog("Don't Allow") // Dismiss an Android alert await browser.dismissDialog('Cancel') // Dismiss whatever the default/cancel button is await browser.dismissDialog() }) ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/dragAndDrop.md # dragAndDrop Drag an item to a destination element or position. info The functionality of this command highly depends on the way drag and drop is implemented in your app. If you experience issues please post your example in [#4134](https://github.com/webdriverio/webdriverio/issues/4134). Also make sure that the element you are dragging and the target where you are dropping are both visible on the screen. This command only works with the following up-to-date components: * Appium server (version 2.0.0 or higher) * `appium-uiautomator2-driver` (for Android) * `appium-xcuitest-driver` (for iOS) Make sure your local or cloud-based Appium environment is regularly updated to avoid compatibility issues. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).dragAndDrop(target, { duration }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------------------------------- | -------------------------------- | ----------------------------------------------------- | | `target` | `Element, DragAndDropCoordinate` | destination element or object with x and y properties | | `options`<br />*optional* | `DragAndDropOptions` | dragAndDrop command options | | `options.duration`<br />*optional* | `Number` | how long the drag should take place | ## Example[​](#example "Direct link to Example") example.test.js ``` it('should demonstrate the dragAndDrop command', async () => { const elem = $('#someElem') const target = $('#someTarget') // drag and drop to other element await elem.dragAndDrop(target) // drag and drop relative from current position await elem.dragAndDrop({ x: 100, y: 200 }) }) ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/fingerPrint.md # fingerPrint Authenticate users by using their fingerprint scan on supported Android emulators. The fingerprintId must be between 1 and 10. ## Usage[​](#usage "Direct link to Usage") ``` await browser.fingerPrint(fingerprintId) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------------- | -------- | -------------------------------------------- | | `fingerprintId` | `number` | The fingerprint sensor ID to simulate (1–10) | ## Example[​](#example "Direct link to Example") fingerPrint.js ``` it('should authenticate with fingerprint', async () => { await browser.fingerPrint(1) }) ``` ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/getClipboard.md # getClipboard Get the content of the system clipboard as a base64-encoded string. Android only supports the `plaintext` content type. ## Usage[​](#usage "Direct link to Usage") ``` await browser.getClipboard(contentType) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ----------------------------- | -------- | ------------------------------------------------------------------------------------------------------- | | `contentType`<br />*optional* | `string` | Content type to retrieve (e.g. `'plaintext'`, `'image'`, `'url'`). Android only supports `'plaintext'`. | ## Example[​](#example "Direct link to Example") getClipboard.js ``` it('should get the clipboard content', async () => { const content = await browser.getClipboard() const decoded = Buffer.from(content, 'base64').toString('utf8') }) ``` ## Returns[​](#returns "Direct link to Returns") * **<`Promise<string>`>** **`returns`:** Base64-encoded clipboard content. ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/getContext.md # getContext Retrieve the context of the current session. This method enhances the default Appium `context`/WebdriverIO `getContext` command by providing an option to return detailed context information, making it easier to work with hybrid apps that use webviews. ### How Contexts Work[​](#how-contexts-work "Direct link to How Contexts Work") Refer to [Hybrid Apps documentation](/docs/api/mobile.md#hybrid-apps) for more information. Below is an explanation of the challenges associated with the `getContext` command: #### For Android:[​](#for-android "Direct link to For Android:") * Webviews can contain multiple pages (like browser tabs), and identifying the correct page requires additional metadata such as `title` or `url`. * The default Appium methods only provide basic context names (e.g., `WEBVIEW_{packageName}`) without detailed information about the pages inside the webview. #### For iOS:[​](#for-ios "Direct link to For iOS:") * Each webview is identified by a generic `WEBVIEW_{id}` string, which doesn’t indicate its contents or the app screen it belongs to. ### Why Use This Method?[​](#why-use-this-method "Direct link to Why Use This Method?") * **Default Behavior**: <!-- --> * Returns the current context as a string (e.g., `NATIVE_APP` or `WEBVIEW_{id}`). * **Detailed Context**: <!-- --> * When `returnDetailedContext` is enabled, retrieves metadata such as: <!-- --> * **Android**: `packageName`, `title`, `url`, and `webviewPageId`. * **iOS**: `bundleId`, `title`, and `url`. * **Android-Specific Options**: <!-- --> * Retry intervals and timeouts can be customized to handle delays in webview initialization. Notes and Limitations * If `returnDetailedContext` is not enabled, the method behaves like the default Appium `getContext` method. * If you want to use the "default" Appium `context` method, you can use the `driver.getAppiumContext()` method, see also the [Appium Contexts](/docs/api/appium.md#getappiumcontext) command. * **Android:** Android-specific options (`androidWebviewConnectionRetryTime` and `androidWebviewConnectTimeout`) have no effect on iOS. * Logs warnings if multiple or no detailed contexts are found: <!-- --> * `We found more than 1 detailed context for the current context '{context}'. We will return the first context.` * `We did not get back any detailed context for the current context '{context}'. We will return the current context as a string.` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ----------------------------------------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `options`<br />*optional* | `GetContextsOptions` | The `getContext` options (optional) | | `options.returnDetailedContext`<br />*optional* | `boolean` | By default, we only return the context name based on the default Appium `context` API, which is only a string. If you want to get back detailed context information, set this to `true`. Default is `false` (optional). | | `options.androidWebviewConnectionRetryTime`<br />*optional* | `number` | The time in milliseconds to wait between each retry to connect to the webview. Default is `500` ms (optional).<br />**ANDROID-ONLY** | | `options.androidWebviewConnectTimeout`<br />*optional* | `number` | The maximum amount of time in milliseconds to wait for a web view page to be detected. Default is `5000` ms (optional).<br />**ANDROID-ONLY** | | `options.waitForWebviewMs`<br />*optional* | `number` | The time in milliseconds to wait for webviews to become available before returning contexts. This parameter is passed directly to the Appium `mobile: getContexts` command. Default is `0` ms (optional).<br />**ANDROID-ONLY**<br />This is useful when you know that a webview is loading but needs additional time to become available. This option works at the Appium level, before WebdriverIO's retry logic (`androidWebviewConnectionRetryTime` and `androidWebviewConnectTimeout`) is applied. | ## Examples[​](#examples "Direct link to Examples") default.test.js ``` it('should return the current context with the default Appium `context` method', async () => { // For Android await driver.getContext() // Returns 'WEBVIEW_com.wdiodemoapp' or 'NATIVE_APP' // // For iOS, the context will be 'WEBVIEW_{number}' await driver.getContext() // Returns 'WEBVIEW_94703.19' or 'NATIVE_APP' }) ``` detailed.test.js ``` it('should return the context of the current session with more detailed information', async () => { // For Android await driver.getContext({ returnDetailedContext: true}) // Returns or `NATIVE_APP`, or // { // id: 'WEBVIEW_com.wdiodemoapp', // title: 'WebdriverIO · Next-gen browser and mobile automation test framework for Node.js | WebdriverIO', // url: 'https://webdriver.io/', // packageName: 'com.wdiodemoapp', // webviewPageId: '5C0425CF67E9B169245F48FF21172912' // } // // For iOS, the context will be 'WEBVIEW_{number}' await driver.getContext({ returnDetailedContext: true}) // Returns or `NATIVE_APP`, or // { // id: 'WEBVIEW_64981.1', // title: 'WebdriverIO · Next-gen browser and mobile automation test framework for Node.js | WebdriverIO', // url: 'https://webdriver.io/', // bundleId: 'org.reactjs.native.example.wdiodemoapp' // } }) ``` customize.retry.test.js ``` it('should be able to cusomize the retry intervals and timeouts to handle delayed webview initialization', async () => { // For Android await driver.getContext({ returnDetailedContext: true, // NOTE: The following options are Android-specific // For Android we might need to wait a bit longer to connect to the webview, so we can provide some additional options androidWebviewConnectionRetryTime: 1*1000, // Retry every 1 second androidWebviewConnectTimeout: 10*1000, // Timeout after 10 seconds }) }) wait.for.webview.test.js t('should wait for webview to become available before retrieving context', async () => { // For Android await driver.getContext({ returnDetailedContext: true, // Wait for webview to become available at the Appium level before WebdriverIO's retry logic waitForWebviewMs: 3000, // Wait 3 seconds for webview to become available }) ) ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/getContexts.md # getContexts The WebdriverIO `getContexts` method is an improved version of the default Appium `contexts` (and the previous WebdriverIO `getContexts`) command. It provides detailed and actionable information about available contexts in a mobile app session, addressing the limitations of the default Appium methods. ### How Webviews Work and Why This Method Helps[​](#how-webviews-work-and-why-this-method-helps "Direct link to How Webviews Work and Why This Method Helps") For more details, refer to the [Hybrid Apps documentation](/docs/api/mobile.md#hybrid-apps). Below is a summary of the challenges addressed by the `getContexts` command: #### Android Challenges[​](#android-challenges "Direct link to Android Challenges") * A single webview (e.g., `WEBVIEW_{packageName}`) may contain multiple pages (similar to browser tabs). * The default Appium methods do not include details about these pages, such as their `title`, `url`, or visibility, making it hard to identify the correct page and leading to potential flakiness. #### iOS Challenges[​](#ios-challenges "Direct link to iOS Challenges") * The default Appium method only returns generic webview IDs (e.g., `WEBVIEW_{id}`) without any additional metadata. * This makes it difficult to determine which webview corresponds to the target app screen. The enhanced `getContexts` method solves these issues by returning detailed context objects, which include: * **For Android:** `title`, `url`, `packageName`, `webviewPageId`, and layout details (`screenX`, `screenY`, `width`, and `height`). * **For iOS:** `bundleId`, `title`, and `url`. These enhancements make debugging and interacting with hybrid apps more reliable. ### Why Use This Method?[​](#why-use-this-method "Direct link to Why Use This Method?") By default, the Appium `contexts` method returns only an array of strings representing available contexts: * **For Android:** `['NATIVE_APP', 'WEBVIEW_com.wdiodemoapp', ...]` * **For iOS:** `['NATIVE_APP', 'WEBVIEW_84392.1', ...]` While sufficient for simple scenarios, these default responses lack critical metadata for hybrid app testing: * **For Android:** The lack of page-specific metadata makes it challenging to interact with the correct webview. * **For iOS:** Generic webview IDs provide no insight into the content or app screen they represent. The enhanced `getContexts` method provides: * Detailed metadata for both Android and iOS. * Options to filter and customize the returned contexts for better targeting and interaction. Notes and Limitations * The enhanced `getContexts` method works on both Android and iOS platforms. However, the returned data may vary depending on the platform and app under test. * If you do not specify the `returnDetailedContexts` option, the method behaves like the default Appium `contexts` method, returning a simple context array. * To use the "default" Appium `contexts` method, use `driver.getAppiumContexts()`. For more information, see the [Appium Contexts documentation](/docs/api/appium.md#getappiumcontexts). #### Android Webviews:[​](#android-webviews "Direct link to Android Webviews:") * Metadata such as `androidWebviewData` is available only when `returnAndroidDescriptionData` is `true`. * Using the `getContexts` method on a Chrome browser may occasionally return incomplete data due to mismatched browser/Webview/ChromeDriver versions. In such cases, default values or an incorrect `webviewPageId` (e.g., `0`) may be returned. ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ----------------------------------------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `options`<br />*optional* | `GetContextsOptions` | The `getContexts` options (optional) | | `options.returnDetailedContexts`<br />*optional* | `boolean` | By default, we only return the context names based on the default Appium `contexts` API. If you want to get all data, you can set this to `true`. Default is `false` (optional). | | `options.androidWebviewConnectionRetryTime`<br />*optional* | `number` | The time in milliseconds to wait between each retry to connect to the webview. Default is `500` ms (optional).<br />**ANDROID-ONLY** | | `options.androidWebviewConnectTimeout`<br />*optional* | `number` | The maximum amount of time in milliseconds to wait for a web view page to be detected. Default is `5000` ms (optional).<br />**ANDROID-ONLY** | | `options.filterByCurrentAndroidApp`<br />*optional* | `boolean` | By default, we return all webviews. If you want to filter the webviews by the current Android app that is opened, you can set this to `true`. Default is `false` (optional).<br />**NOTE:** Be aware that you can also NOT find any Webview based on this "restriction".<br />**ANDROID-ONLY** | | `options.isAndroidWebviewVisible`<br />*optional* | `boolean` | By default, we only return the webviews that are attached and visible. If you want to get all webviews, you can set this to `false` (optional). Default is `true`.<br />**ANDROID-ONLY** | | `options.returnAndroidDescriptionData`<br />*optional* | `boolean` | By default, no Android Webview (Chrome) description description data. If you want to get all data, you can set this to `true`. Default is `false` (optional).<br />By enabling this option you will get extra data in the response, see the `description.data.test.js` for more information.<br />**ANDROID-ONLY** | | `options.waitForWebviewMs`<br />*optional* | `number` | The time in milliseconds to wait for webviews to become available before returning contexts. This parameter is passed directly to the Appium `mobile: getContexts` command. Default is `0` ms (optional).<br />**ANDROID-ONLY**<br />This is useful when you know that a webview is loading but needs additional time to become available. This option works at the Appium level, before WebdriverIO's retry logic (`androidWebviewConnectionRetryTime` and `androidWebviewConnectTimeout`) is applied. | ## Examples[​](#examples "Direct link to Examples") example.test.js ``` it('should return all contexts in the current session with the default Appium `contexts`-method.', async () => { // For Android await driver.getContexts() // Returns ['NATIVE_APP', 'WEBVIEW_com.wdiodemoapp', ...] // // For iOS, the context will be 'WEBVIEW_{number}' await driver.getContexts() // Returns [ 'NATIVE_APP', 'WEBVIEW_84392.1', ... ] }) ``` detailed.test.js ``` it('should return all contexts in the current session with detailed info.', async () => { // For Android await driver.getContexts({returnDetailedContexts: true}) // Returns [ // { id: 'NATIVE_APP' }, // { // id: 'WEBVIEW_com.wdiodemoapp', // title: 'WebdriverIO · Next-gen browser and mobile automation test framework for Node.js | WebdriverIO', // url: 'https://webdriver.io/', // packageName: 'com.wdiodemoapp', // webviewPageId: '58B0AA2DBBBBBE9008C35AE42385BB0D' // }, // { // id: 'WEBVIEW_chrome', // title: 'Android | Get more done with Google on Android-phones and devices', // url: 'https://www.android.com/', // packageName: 'com.android.chrome', // webviewPageId: '0' // } // ] // // For iOS, the context will be 'WEBVIEW_{number}' await driver.getContexts({returnDetailedContexts: true}) // Returns: [ // { id: 'NATIVE_APP' }, // { // id: 'WEBVIEW_86150.1', // title: 'WebdriverIO · Next-gen browser and mobile automation test framework for Node.js | WebdriverIO', // url: 'https://webdriver.io/', // bundleId: 'org.reactjs.native.example.wdiodemoapp' // }, // { // id: 'WEBVIEW_86152.1', // title: 'Apple', // url: 'https://www.apple.com/', // bundleId: 'com.apple.mobilesafari' // } // ] }) ``` description.data.test.js ``` it('should return Android description data for the webview', async () => { // For Android await driver.getContexts({returnDetailedContexts: true, returnAndroidDescriptionData: true}) // Returns [ // { id: 'NATIVE_APP' }, // { // androidWebviewData: { // // Indicates whether the web page is currently attached to a web view. // // `true` means the page is attached and likely active, `false` indicates it is not. // attached: true, // // Indicates whether the web page is empty or not. An empty page typically means that // // there is no significant content loaded in it. `true` indicates the page is empty, // // `false` indicates it has content. // empty: false, // // Indicates whether the page has never been attached to a web view. If `true`, the // // page has never been attached, which could indicate a new or unused page. If `false`, // // the page has been attached at some point. // neverAttached: false, // // Indicates whether the web page is visible on the screen. `true` means the page is // // visible to the user, `false` means it is not. // visible: true, // // This data can be super useful to determine where on the screen the webview is located // // and can come in handy when you want to interact with elements on the screen based on // // coordinates based on the top-left corner of the screen // screenX: 0, // screenY: 151, // height: 2589, // width: 1344 // }, // id: 'WEBVIEW_com.wdiodemoapp', // title: 'WebdriverIO · Next-gen browser and mobile automation test framework for Node.js | WebdriverIO', // url: 'https://webdriver.io/', // packageName: 'com.wdiodemoapp', // webviewPageId: '58B0AA2DBBBBBE9008C35AE42385BB0D' // } // ] }) wait.for.webview.test.js t('should wait for webview to become available before retrieving contexts', async () => { // For Android await driver.getContexts({ returnDetailedContexts: true, // Wait for webview to become available at the Appium level before WebdriverIO's retry logic waitForWebviewMs: 3000, // Wait 3 seconds for webview to become available }) ) ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/getCurrentActivity.md # getCurrentActivity Get the name of the current Android activity. ## Usage[​](#usage "Direct link to Usage") ``` await browser.getCurrentActivity() ``` ## Example[​](#example "Direct link to Example") getCurrentActivity.js ``` it('should get the current Android activity', async () => { const activity = await browser.getCurrentActivity() console.log('Current activity:', activity) }) ``` ## Returns[​](#returns "Direct link to Returns") * **<`Promise<string>`>** **`returns`:** The name of the current Android activity ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/getCurrentPackage.md # getCurrentPackage Get the name of the current Android package. ## Usage[​](#usage "Direct link to Usage") ``` await browser.getCurrentPackage() ``` ## Example[​](#example "Direct link to Example") getCurrentPackage.js ``` it('should get the current Android package', async () => { const pkg = await browser.getCurrentPackage() console.log('Current package:', pkg) }) ``` ## Returns[​](#returns "Direct link to Returns") * **<`Promise<string>`>** **`returns`:** The name of the current Android package ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/getDisplayDensity.md # getDisplayDensity Get the display density from the device. ## Usage[​](#usage "Direct link to Usage") ``` await browser.getDisplayDensity() ``` ## Example[​](#example "Direct link to Example") getDisplayDensity.js ``` it('should get the display density', async () => { const density = await browser.getDisplayDensity() console.log('Display density:', density) }) ``` ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/getPerformanceData.md # getPerformanceData Get performance data for a specific application. Returns system state information like cpu, memory, network traffic, and battery. Use `getPerformanceDataTypes()` to find available data types. ## Usage[​](#usage "Direct link to Usage") ``` await browser.getPerformanceData(packageName, dataType, dataReadTimeout) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------------------------------- | -------- | ------------------------------------------------------------------- | | `packageName` | `string` | The package name of the application to get performance data for | | `dataType` | `string` | The type of performance data to retrieve (e.g. cpuinfo, memoryinfo) | | `dataReadTimeout`<br />*optional* | `number` | Timeout in seconds to wait for the data to be read | ## Example[​](#example "Direct link to Example") getPerformanceData.js ``` it('should get performance data for an app', async () => { // Get available data types first const types = await browser.getPerformanceDataTypes() // Get CPU info for an app const cpuData = await browser.getPerformanceData('com.example.app', 'cpuinfo', 5) }) ``` ## Returns[​](#returns "Direct link to Returns") * **<`Promise<string[]>`>** **`returns`:** Performance data for the requested type ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/getPerformanceDataTypes.md # getPerformanceDataTypes Returns the information types of the system state which is supported to read as part of performance data (e.g. cpu, memory, network traffic, battery). ## Usage[​](#usage "Direct link to Usage") ``` await browser.getPerformanceDataTypes() ``` ## Example[​](#example "Direct link to Example") getPerformanceDataTypes.js ``` it('should get the supported performance data types', async () => { const types = await browser.getPerformanceDataTypes() console.log('Supported types:', types) }) ``` ## Returns[​](#returns "Direct link to Returns") * **<`Promise<string[]>`>** **`returns`:** A list of supported performance data type names ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/getStrings.md # getStrings Get app strings for a specific language. Returns a key-value object of all string resources defined in the application for the given language. ## Usage[​](#usage "Direct link to Usage") ``` await browser.getStrings(language, stringFile) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------------------------- | -------- | --------------------------------------------------------------------- | | `language`<br />*optional* | `string` | Language code (e.g. `'fr'`, `'de'`). Defaults to the device language. | | `stringFile`<br />*optional* | `string` | Path to the strings file (Android only). | ## Example[​](#example "Direct link to Example") getStrings.js ``` it('should get app strings', async () => { // Get strings for default language const strings = await browser.getStrings() // Get strings for a specific language const frStrings = await browser.getStrings('fr') }) ``` ## Returns[​](#returns "Direct link to Returns") * **<`Promise<Record<string, string>>`>** **`returns`:** Key-value map of all string resources. ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/getSystemBars.md # getSystemBars Retrieve visibility and bounds information of the status and navigation bars. ## Usage[​](#usage "Direct link to Usage") ``` await browser.getSystemBars() ``` ## Example[​](#example "Direct link to Example") getSystemBars.js ``` it('should get system bars info', async () => { const bars = await browser.getSystemBars() console.log('Status bar:', bars.statusBar) console.log('Navigation bar:', bars.navigationBar) }) ``` ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/gsmCall.md # gsmCall Make a GSM call on the Android emulator. Valid actions: 'call', 'accept', 'cancel', 'hold'. ## Usage[​](#usage "Direct link to Usage") ``` await browser.gsmCall(phoneNumber, action) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------- | -------- | ---------------------------------------------------------- | | `phoneNumber` | `string` | The phone number to use for the GSM call simulation | | `action` | `string` | The action to perform ('call', 'accept', 'cancel', 'hold') | ## Example[​](#example "Direct link to Example") gsmCall.js ``` it('should simulate a GSM call', async () => { // Simulate an incoming call await browser.gsmCall('+15551234567', 'call') // Accept the call await browser.gsmCall('+15551234567', 'accept') }) ``` ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/gsmSignal.md # gsmSignal Set the GSM signal strength on the Android emulator. ## Usage[​](#usage "Direct link to Usage") ``` await browser.gsmSignal(signalStrength) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------------- | -------- | -------------------------------------------------------------------------------------------------------------------------- | | `signalStrength` | `number` | The signal strength to set. Accepted values: `0` (no signal), `1` (very poor), `2` (poor), `3` (moderate), `4` (good/full) | ## Example[​](#example "Direct link to Example") gsmSignal.js ``` it('should set GSM signal to full strength', async () => { await browser.gsmSignal(4) }) it('should set GSM signal to no signal', async () => { await browser.gsmSignal(0) }) ``` ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/gsmVoice.md # gsmVoice Set the GSM voice state on the Android emulator. Valid values: 'unregistered', 'home', 'roaming', 'searching', 'denied', 'off', 'on'. ## Usage[​](#usage "Direct link to Usage") ``` await browser.gsmVoice(state) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------- | -------- | -------------------------------------------------------------------------------------------------- | | `state` | `string` | The GSM voice state to set ('unregistered', 'home', 'roaming', 'searching', 'denied', 'off', 'on') | ## Example[​](#example "Direct link to Example") gsmVoice.js ``` it('should set GSM voice state to home', async () => { await browser.gsmVoice('home') }) ``` ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/isLocked.md # isLocked Check whether the device screen is locked. ## Usage[​](#usage "Direct link to Usage") ``` await browser.isLocked() ``` ## Example[​](#example "Direct link to Example") isLocked.js ``` it('should check if the device is locked', async () => { const locked = await browser.isLocked() console.log('Device is locked:', locked) }) ``` ## Returns[​](#returns "Direct link to Returns") * **<`Promise<boolean>`>** **`returns`:** `true` if the device is locked, `false` otherwise ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/launchApp.md # launchApp Launch or activate an app on the device. If no `bundleId` (iOS) or `appId` (Android) is provided, the command will automatically detect and activate the currently active app. ## Usage[​](#usage "Direct link to Usage") ``` await browser.launchApp({ bundleId, arguments, environment, appId }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------- | | `options`<br />*optional* | `object` | Options for launching the app (optional) | | `options.bundleId`<br />*optional* | `string` | The bundle ID of the iOS app to launch. If not provided, the currently active app is used.<br />**iOS-ONLY** | | `options.arguments`<br />*optional* | `string, string[]` | Command line arguments to pass to the app on launch.<br />**iOS-ONLY** | | `options.environment`<br />*optional* | `object` | Environment variables to set when launching the app (key-value pairs).<br />**iOS-ONLY** | | `options.appId`<br />*optional* | `string` | The package name of the Android app to activate. If not provided, the currently active app is used.<br />**ANDROID-ONLY** | ## Example[​](#example "Direct link to Example") launchApp.js ``` it('should launch a specific iOS app', async () => { // iOS: launch a specific app by bundle ID await browser.launchApp({ bundleId: 'com.example.myapp' }) }) it('should launch an iOS app with arguments and environment', async () => { // iOS: launch an app and pass arguments and environment variables await browser.launchApp({ bundleId: 'com.example.myapp', arguments: ['-AppleLanguages', '(en)'], environment: { MY_ENV_VAR: 'value' } }) }) it('should launch a specific Android app', async () => { // Android: activate/launch a specific app by package name await browser.launchApp({ appId: 'com.example.myapp' }) }) it('should activate the currently active app', async () => { // Automatically detect and activate the current app await browser.launchApp() }) ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/lock.md # lock Lock the device screen. ## Usage[​](#usage "Direct link to Usage") ``` await browser.lock(seconds) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------- | -------- | ------------------------------------------------- | | `seconds`<br />*optional* | `number` | How long to lock the screen in seconds (iOS only) | ## Examples[​](#examples "Direct link to Examples") lock.js ``` it('should lock the screen', async () => { // Lock the screen indefinitely await browser.lock() }) ``` lock.timeout.js ``` it('should lock the screen for 5 seconds (iOS only)', async () => { // Lock the screen for 5 seconds, then auto-unlock (iOS only) await browser.lock(5) }) ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/longPress.md # longPress Performs a long press gesture on the given element on the screen. This issues a WebDriver `action` command for the selected element. It is based on the `click` command, except for iOS web context, there we use a script to simulate the long press due to the lack of support for long press gestures in webview. info This command only works with the following up-to-date components: * Appium server (version 2.0.0 or higher) * `appium-uiautomator2-driver` (for Android) * `appium-xcuitest-driver` (for iOS) Make sure your local or cloud-based Appium environment is regularly updated to avoid compatibility issues. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).longPress({ x, y, duration }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------------------------------- | ------------------ | -------------------------------------------------------------------- | | `options`<br />*optional* | `LongPressOptions` | Long press options (optional) | | `options.x`<br />*optional* | `number` | Number (optional) | | `options.y`<br />*optional* | `number` | Number (optional) | | `options.duration`<br />*optional* | `number` | Duration of the press in ms, default is 1500 ms<br />**MOBILE-ONLY** | ## Examples[​](#examples "Direct link to Examples") longpress.offset.js ``` it('should demonstrate a longPress using an offset on the iOS Contacts icon', async () => { const contacts = $('~Contacts') // opens the Contacts menu on iOS where you can quickly create // a new contact, edit your home screen, or remove the app // clicks 30 horizontal and 10 vertical pixels away from location of the icon (from center point of element) await contacts.longPress({ x: 30, y: 10 }) }) ``` longpress.example.js ``` it('should be able to open the contacts menu on iOS by executing a longPress of 5 seconds', async () => { const contacts = $('~Contacts') // opens the Contacts menu on iOS where you can quickly create // a new contact, edit your home screen, or remove the app await contacts.longPress({ duration: 5 * 1000 }) }) ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/longPressKeyCode.md # longPressKeyCode Press and hold a particular key code on the device. ## Usage[​](#usage "Direct link to Usage") ``` await browser.longPressKeyCode(keycode, metastate, flags) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------------------------- | -------- | ----------------------------------------------------------- | | `keycode` | `number` | The keycode to long-press (Android KeyEvent constant) | | `metastate`<br />*optional* | `number` | Meta state to apply during the key press (e.g. shift, ctrl) | | `flags`<br />*optional* | `number` | Integer flags for the key event | ## Example[​](#example "Direct link to Example") longPressKeyCode.js ``` it('should long press the Home button', async () => { await browser.longPressKeyCode(3) }) ``` ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/openNotifications.md # openNotifications Open Android notifications. ## Usage[​](#usage "Direct link to Usage") ``` await browser.openNotifications() ``` ## Example[​](#example "Direct link to Example") openNotifications.js ``` it('should open the Android notification shade', async () => { await browser.openNotifications() }) ``` ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/pinch.md # pinch Performs a pinch gesture on the given element on the screen. info Pinching is done based on native mobile gestures. It is only supported for the following drivers: * [appium-uiautomator2-driver](https://appium.github.io/appium-uiautomator2-driver/latest/reference/execute-methods/#mobile-pinchclosegesture) for Android * [appium-xcuitest-driver](https://appium.github.io/appium-xcuitest-driver/latest/reference/execute-methods/#mobile-pinch) for iOS This command only works with the following up-to-date components: * Appium server (version 2.0.0 or higher) * `appium-uiautomator2-driver` (for Android) * `appium-xcuitest-driver` (for iOS) Make sure your local or cloud-based Appium environment is regularly updated to avoid compatibility issues. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).pinch({ duration, scale }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `options`<br />*optional* | `PinchOptions` | pinch options (optional) | | `options.duration`<br />*optional* | `number` | The duration in millisecond of how fast the pinch should be executed, minimal is 500 ms and max is 10000 ms. The default is 1500 ms (1.5 seconds) (optional) | | `options.scale`<br />*optional* | `number` | The scale of how big the pinch should be according to the screen. Valid values must be float numbers in range 0..1, where 1.0 is 100% (optional) | ## Example[​](#example "Direct link to Example") pinch.js ``` it('should demonstrate a pinch on Google maps', async () => { const mapsElement = $('//*[@resource-id="com.google.android.apps.maps:id/map_frame"]') // Pinch with the default duration scale await mapsElement.pinch() // Pinch with a custom duration and scale await mapsElement.pinch({ duration: 4000, scale: 0.9 }) }) ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/powerAC.md # powerAC Set the state of the battery charger on the Android emulator. Valid values: 'on', 'off'. ## Usage[​](#usage "Direct link to Usage") ``` await browser.powerAC(state) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------- | -------- | ---------------------------------------- | | `state` | `string` | The charger state to set ('on' or 'off') | ## Example[​](#example "Direct link to Example") powerAC.js ``` it('should enable the AC charger', async () => { await browser.powerAC('on') }) ``` ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/powerCapacity.md # powerCapacity Set the battery percentage on the Android emulator. Value must be in the range \[0, 100]. ## Usage[​](#usage "Direct link to Usage") ``` await browser.powerCapacity(percent) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------- | -------- | ------------------------------------- | | `percent` | `number` | The battery percentage to set (0–100) | ## Example[​](#example "Direct link to Example") powerCapacity.js ``` it('should set battery to 75%', async () => { await browser.powerCapacity(75) }) ``` ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/pressKeyCode.md # pressKeyCode Press a particular key on the device. The keycode values correspond to Android KeyEvent constants. ## Usage[​](#usage "Direct link to Usage") ``` await browser.pressKeyCode(keycode, metastate, flags) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------------------------- | -------- | ----------------------------------------------------------- | | `keycode` | `number` | The keycode to press (Android KeyEvent constant) | | `metastate`<br />*optional* | `number` | Meta state to apply during the key press (e.g. shift, ctrl) | | `flags`<br />*optional* | `number` | Integer flags for the key event | ## Example[​](#example "Direct link to Example") pressKeyCode.js ``` it('should press the Home button', async () => { // Press the Home button (keycode 3) await browser.pressKeyCode(3) // Press with meta state (e.g., Shift + A = keycode 29, metastate 1) await browser.pressKeyCode(29, 1) }) ``` ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/relaunchActiveApp.md # relaunchActiveApp Performs a restart of the active native app by: * terminating the active app * launching the previously active app important This command will restart (terminate/close and launch/start) the current active app and will NOT reset the app state. Appium can not perform a hard reset of the app unless: * you start a new session and the session handler removes the app state/cleans the device * you have a backdoor in your app to reset the app state and Appium can call this backdoor If you want to reset the app state for Android or iOS you need to create your own reset mechanism/command in your script. Options could be: * Android: Use the `adb` command to clear the app data: `adb shell pm clear <appPackage>` * iOS: reinstall the app using the `mobile: installApp` command * .... * not use this command The options you have depend on the platform, the app and the location (local with most of the times full access to the device, or in the cloud with less access) you are testing. ## Example[​](#example "Direct link to Example") restart.app.js ``` it('should restart the app with default options', async () => { await browser.relaunchActiveApp() }) ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/scrollIntoView.md # scrollIntoView Scroll element into viewport for Desktop/Mobile Web **AND** Mobile Native Apps. info Scrolling for Mobile Native Apps is done based on the mobile `swipe` command. This command only works with the following up-to-date components: * Appium server (version 2.0.0 or higher) * `appium-uiautomator2-driver` (for Android) * `appium-xcuitest-driver` (for iOS) Make sure your local or cloud-based Appium environment is regularly updated to avoid compatibility issues. ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------------------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `options`<br />*optional* | `object, boolean` | options for `Element.scrollIntoView()`. Default for desktop/mobile web:<br />`{ block: 'start', inline: 'nearest' }`<br />Default for Mobile Native App<br />`{ maxScrolls: 10, scrollDirection: 'down' }` | | **Desktop/Mobile Web Only** | | | | `options.behavior`<br />*optional* | `string` | See [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView).<br />**WEB-ONLY** (Desktop/Mobile) | | `options.block`<br />*optional* | `string` | See [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView).<br />**WEB-ONLY** (Desktop/Mobile) | | `options.inline`<br />*optional* | `string` | See [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView).<br />**WEB-ONLY** (Desktop/Mobile) | | **Mobile Native App Only** | | | | `options.direction`<br />*optional* | `string` | Can be one of `down`, `up`, `left` or `right`, default is `up`.<br />**MOBILE-NATIVE-APP-ONLY** | | `options.maxScrolls`<br />*optional* | `number` | The max amount of scrolls until it will stop searching for the element, default is `10`.<br />**MOBILE-NATIVE-APP-ONLY** | | `options.duration`<br />*optional* | `number` | The duration in milliseconds for the swipe. Default is `1500` ms. The lower the value, the faster the swipe.<br />**MOBILE-NATIVE-APP-ONLY** | | `options.scrollableElement`<br />*optional* | `Element` | Element that is used to scroll within. If no element is provided it will use the following selector for iOS `-ios predicate string:type == "XCUIElementTypeApplication"` and the following for Android `//android.widget.ScrollView'`. If more elements match the default selector, then by default it will pick the first matching element.<br />**MOBILE-NATIVE-APP-ONLY** | | `options.percent`<br />*optional* | `number` | The percentage of the (default) scrollable element to swipe. This is a value between 0 and 1. Default is `0.95`.<br />**NEVER** swipe from the exact top\|bottom\|left\|right of the screen, you might trigger for example the notification bar or other OS/App features which can lead to unexpected results.<br />**MOBILE-NATIVE-APP-ONLY** | ## Examples[​](#examples "Direct link to Examples") desktop.mobile.web.scrollIntoView\.js ``` it('should demonstrate the desktop/mobile web scrollIntoView command', async () => { const elem = await $('#myElement'); // scroll to specific element await elem.scrollIntoView(); // center element within the viewport await elem.scrollIntoView({ block: 'center', inline: 'center' }); }); ``` mobile.native.app.scrollIntoView\.js ``` it('should demonstrate the mobile native app scrollIntoView command', async () => { const elem = await $('#myElement'); // scroll to a specific element in the default scrollable element for Android or iOS for a maximum of 10 scrolls await elem.scrollIntoView(); // Scroll to the left in the scrollable element called '#scrollable' for a maximum of 5 scrolls await elem.scrollIntoView({ direction: 'left', maxScrolls: 5, scrollableElement: $('#scrollable') }); }); ``` --- Source: https://webdriver.io/docs/api/mobile/sendKeyEvent.md # sendKeyEvent Send a key event to the Android device. This command is the legacy Android key event API. For new tests, prefer using `pressKeyCode()` with numeric keycodes from the Android `KeyEvent` constants. ## Usage[​](#usage "Direct link to Usage") ``` await browser.sendKeyEvent(keycode, metastate) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `keycode` | `string` | The keycode to send (as a string, e.g. `'3'` for Home). See [Android KeyEvent](https://developer.android.com/reference/android/view/KeyEvent) for all available keycodes. | | `metastate`<br />*optional* | `string` | The meta state to apply during the key press as a string (e.g. `'1'` for Shift). See [Android KeyEvent](https://developer.android.com/reference/android/view/KeyEvent) for all meta state values. | ## Example[​](#example "Direct link to Example") sendKeyEvent.js ``` it('should send a key event', async () => { // Send the Home key event (keycode '3') await browser.sendKeyEvent('3') // Send Shift+A (keycode '29', metastate '1') await browser.sendKeyEvent('29', '1') }) ``` ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/sendSms.md # sendSms Simulate an SMS message being received on the Android emulator. ## Usage[​](#usage "Direct link to Usage") ``` await browser.sendSms(phoneNumber, message) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------- | -------- | ----------------------------------------------- | | `phoneNumber` | `string` | The phone number the simulated SMS is sent from | | `message` | `string` | The text content of the simulated SMS | ## Example[​](#example "Direct link to Example") sendSms.js ``` it('should simulate receiving an SMS', async () => { await browser.sendSms('+15551234567', 'Hello from the test!') }) ``` ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/setClipboard.md # setClipboard Set the content of the system clipboard. The `content` must be provided as a base64-encoded string. Android only supports the `plaintext` content type. ## Usage[​](#usage "Direct link to Usage") ``` await browser.setClipboard(content, contentType, label) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ----------------------------- | -------- | ------------------------------------------------------------------------------------------- | | `content` | `string` | Base64-encoded string to set as clipboard content. | | `contentType`<br />*optional* | `string` | Content type (e.g. `'plaintext'`, `'image'`, `'url'`). Android only supports `'plaintext'`. | | `label`<br />*optional* | `string` | Clipboard label (Android only). | ## Example[​](#example "Direct link to Example") setClipboard.js ``` it('should set the clipboard content', async () => { // Set plaintext clipboard content const base64Content = Buffer.from('Hello World').toString('base64') await browser.setClipboard(base64Content, 'plaintext') }) ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/shake.md # shake Perform a shake action on the device. Supports iOS Simulator and real devices. ## Usage[​](#usage "Direct link to Usage") ``` await browser.shake() ``` ## Example[​](#example "Direct link to Example") shake.js ``` it('should shake the device', async () => { await browser.shake() }) ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) **Supported platforms:** iOS note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/startActivity.md # startActivity The package name of the app to start. ## Usage[​](#usage "Direct link to Usage") ``` await browser.startActivity() ``` --- Source: https://webdriver.io/docs/api/mobile/swipe.md # swipe Swipe in a specific direction within viewport or element for Desktop/Mobile Web **AND** Mobile Native Apps. info Swiping for Mobile Native Apps is based on the W3C-actions protocol, simulating a finger press and movement. This is different from the [`mobile: scrollGesture`](https://appium.github.io/appium-uiautomator2-driver/latest/reference/execute-methods/#mobile-scrollgesture) for Android or [`mobile: scroll`](https://appium.github.io/appium-xcuitest-driver/latest/reference/execute-methods/#mobile-scroll) for iOS command which is based on the Appium Driver protocol and is only available for mobile platforms in the NATIVE context. This command only works with the following up-to-date components: * Appium server (version 2.0.0 or higher) * `appium-uiautomator2-driver` (for Android) * `appium-xcuitest-driver` (for iOS) Make sure your local or cloud-based Appium environment is regularly updated to avoid compatibility issues. Swiping based on coordinates Avoid using `from` and `to` options unless absolutely necessary. These are device-specific and may not work consistently across devices. Use the `scrollableElement` option for reliable swipes within an element. ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------------------------------------------------------------------------------------------------------ | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `options`<br />*optional* | `object, boolean` | options for `browser.swipe()`. Default for desktop/mobile web:<br />`{ direction: 'up', duration: 1500, percent: 0.95, scrollableElement: WebdriverIO.Element }` | | `options.direction`<br />*optional* | `string` | Can be one of `down`, `up`, `left` or `right`, default is `up`.<br />**MOBILE-NATIVE-APP-ONLY** | | **Down** | | **Starting Point:**<br />You place your finger towards the top of the screen.<br />**Movement:**<br />You slide your finger downwards towards the bottom of the screen.<br />**Action:**<br />This also varies by context:<br />- On the home screen or in applications, it typically scrolls the content upwards.<br />- From the top edge, it often opens the notifications panel or quick settings.<br />- In browsers or reading apps, it can be used to scroll through content. | | **Left** | | **Starting Point:**<br />You place your finger on the right side of the screen.<br />**Movement:**<br />You slide your finger horizontally to the left.><br />**Action:**<br />The response to this gesture depends on the application:<br />- It can move to the next item in a carousel or a set of images.<br />- In a navigation context, it might go back to the previous page or close the current view.<br />- On the home screen, it usually switches to the next virtual desktop or screen. | | **Right** | | **Starting Point:**<br />You place your finger on the left side of the screen.<br />**Movement:**<br />You slide your finger horizontally to the right.<br />**Action:**<br />Similar to swiping left, but in the opposite direction:<br />-- It often moves to the previous item in a carousel or gallery.<br />- Can be used to open side menus or navigation drawers in apps.<br />- On the home screen, it typically switches to the previous virtual desktop. | | **Up** | | **Starting Point:**<br />You place your finger towards the bottom of the screen.<br />**Movement:**<br />You slide your finger upwards towards the top of the screen.><br />**Action:**<br />Depending on the context, different actions can occur:<br />- On the home screen or in a list, this usually scrolls the content downwards.<br />- In a full-screen app, it might open additional options or the app drawer.<br />- On certain interfaces, it could trigger a 'refresh' action or open a search bar. | | `options.duration`<br />*optional* | `number` | The duration in milliseconds for the swipe. Default is `1500` ms. The lower the value, the faster the swipe. | | `options.scrollableElement`<br />*optional* | `Element` | Element that is used to swipe within. If no element is provided it will use the following selector for iOS `-ios predicate string:type == "XCUIElementTypeApplication"` and the following for Android `//android.widget.ScrollView'`. If more elements match the default selector, then by default it will pick the first matching element.<br />**MOBILE-NATIVE-APP-ONLY** | | `options.percent`<br />*optional* | `number` | The percentage of the (default) scrollable element to swipe. This is a value between 0 and 1. Default is `0.95`.<br />**NEVER** swipe from the exact top\|bottom\|left\|right of the screen, you might trigger for example the notification bar or other OS/App features which can lead to unexpected results.<br />This has no effect if `from` and `to` are provided. | | **The below values **ONLY** have an effect if the `scrollableElement` is **NOT** provided, otherwise they are ignored.** | | | | `options.from`<br />*optional* | `object` | The x and y coordinates of the start of the swipe. If a `scrollableElement` is provided, then these coordinates have no effect. | | `options.from.x`<br />*optional* | `number` | The x-coordinate of the start of the swipe. | | `options.from.y`<br />*optional* | `number` | The y-coordinate of the start of the swipe. | | `options.to`<br />*optional* | `object` | The x and y coordinates of the end of the swipe. If a `scrollableElement` is provided, then these coordinates have no effect. | | `options.to.x`<br />*optional* | `number` | The x-coordinate of the end of the swipe. | | `options.to.y`<br />*optional* | `number` | The y-coordinate of the end of the swipe. | ## Examples[​](#examples "Direct link to Examples") swipe.js ``` it('should execute a default swipe', async () => { // Default will be a swipe from the bottom to the top, meaning it will swipe UP await browser.swipe(); }); ``` swipe.with.options.js ``` it('should execute a swipe with options', async () => { await browser.swipe({ direction: 'left', // Swipe from right to left duration: 5000, // Last for 5 seconds percent: 0.5, // Swipe 50% of the scrollableElement scrollableElement: $('~carousel'), // The element to swipe within }) }); ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/switchContext.md # switchContext Switch to a specific context using a given Webview `name`, `title`, or `url`. This method enhances the default Appium `context` command by offering more flexibility and precision for switching between native and webview contexts in hybrid mobile applications. ### How Contexts Work[​](#how-contexts-work "Direct link to How Contexts Work") For an overview of Hybrid Apps and webviews, refer to the [Hybrid Apps documentation](/docs/api/mobile.md#hybrid-apps). Below is a summary of how the `switchContext` command addresses common challenges: #### Android Challenges[​](#android-challenges "Direct link to Android Challenges") * Webviews often contain multiple pages (similar to browser tabs). Identifying the correct page requires additional metadata such as `title` or `url`, which is not provided by default Appium methods. * Default Appium methods return only basic context names (e.g., `WEBVIEW_{packageName}`) without details about the content or pages within the webview. * Switching contexts on Android involves two steps, which are handled automatically by this method: <!-- --> 1. Switch to the Webview context using `WEBVIEW_{packageName}`. 2. Select the appropriate page within the Webview using the `switchToWindow` method. #### iOS Challenges[​](#ios-challenges "Direct link to iOS Challenges") * Webviews are identified by generic IDs (e.g., `WEBVIEW_{id}`), which do not provide information about the content or the app screen they correspond to. * Determining the correct webview for interaction often requires trial and error. The `switchContext` method simplifies this process by retrieving detailed metadata (e.g., `title`, `url`, and visibility) to ensure accurate and reliable context switching. ### Why Use This Method?[​](#why-use-this-method "Direct link to Why Use This Method?") * **Simplified Switching**: If you know the `title` or `url` of the desired webview, this method eliminates the need for additional calls to `getContexts` or combining multiple methods like `switchContext({id})` and `getTitle()`. * **Automatic Context Matching**: Finds the best match for a context based on: <!-- --> * Platform-specific identifiers (`bundleId` for iOS, `packageName` for Android). By default, uses the active app identifier, but you can provide a custom `appIdentifier` to search in a specific app (useful for overlays or non-active apps). * Exact or partial matches for `title` or `url` (supports both strings and regular expressions). * Android-specific checks to ensure webviews are attached and visible. * **Fine-Grained Control**: Custom retry intervals and timeouts (Android-only) allow you to handle delays in webview initialization. * **Default Appium Method Access**: If needed, you can use the default Appium `switchContext` command via `driver.switchAppiumContext()`. Notes and Limitations * If the `title` or `url` of the desired webview is known, this method can automatically locate and switch to the matching context without additional `getContexts` calls. * Android-specific options like `androidWebviewConnectionRetryTime` and `androidWebviewConnectTimeout` are not applicable to iOS. * Logs reasons for context-matching failures to assist with debugging. * When using an object as input, either `title` or `url` is required. ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ----------------------------------------------------------- | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `context` | `string, SwitchContextOptions` | The name of the context to switch to. An object with more context options can be provided. | | `options` | `SwitchContextOptions` | switchContext command options | | `options.appIdentifier`<br />*optional* | `string` | The app identifier to search in. For iOS, this should be the `bundleId`. For Android, this should be the `packageName`. If not provided, the method will use the active app identifier. This is useful when you need to search for webviews in overlays or non-active apps that are not recognized as the "active" app. | | `options.title`<br />*optional* | `string, RegExp` | The title of the page to switch to. This will be the content of the title-tag of a webviewpage. You can use a string that needs to fully match or or a regular expression.<br />**IMPORTANT:** When you use options then or the `title` or the `url` property is required. | | `options.url`<br />*optional* | `string, RegExp` | The url of the page to switch to. This will be the `url` of a webviewpage. You can use a string that needs to fully match or or a regular expression.<br />**IMPORTANT:** When you use options then or the `title` or the `url` property is required. | | `options.androidWebviewConnectionRetryTime`<br />*optional* | `number` | The time in milliseconds to wait between each retry to connect to the webview. Default is `500` ms (optional).<br />**ANDROID-ONLY** and will only be used when a `title` or `url` is provided. | | `options.androidWebviewConnectTimeout`<br />*optional* | `number` | The maximum amount of time in milliseconds to wait for a web view page to be detected. Default is `5000` ms (optional).<br />**ANDROID-ONLY** and will only be used when a `title` or `url` is provided. | ## Examples[​](#examples "Direct link to Examples") example.test.js ``` it('should switch to a webview by name and uses the default Appium `context`-method', async () => { // For Android, the context will be '`WEBVIEW_{packageName}`' await driver.switchContext('WEBVIEW_com.wdiodemoapp') // For iOS, the context will be 'WEBVIEW_{number}' await driver.switchContext('WEBVIEW_94703.19') }) ``` exact.title.test.js ``` it('should switch to a webview and match a webview based on an EXACT match of the `title` of the webview', async () => { await driver.switchContext({ // In this case the title needs to be an exact match title: 'Webview Title', }) }) ``` exact.url.test.js ``` it('should switch to a webview and match a webview based on an EXACT match of the `title` of the webview', async () => { await driver.switchContext({ // In this case the url needs to be an exact match url: 'https://webdriver.io', }) }) ``` regex.title.url.test.js ``` it('should switch to a webview and match a webview based on regex match of the `title` and `url` of the webview', async () => { await driver.switchContext({ // The title should NOT end with 'foo' title: /^(?!.*foo$)/, // Matches any string that contains the substring `docs/api/mobile/switchContext` url: /.*docs\/api\/mobile\/switchContext/, }) }) ``` android.context.waits.test.js ``` it('should switch to a webview for Android but wait longer to connect and find a webview based on provided options', async () => { await driver.switchContext({ // In this case the title need to be an exact match title: 'Webview Title', // For Android we might need to wait a bit longer to connect to the webview, so we can provide some additional options androidWebviewConnectionRetryTime: 1*1000, // Retry every 1 second androidWebviewConnectTimeout: 10*1000, // Timeout after 10 seconds }) }) app.identifier.test.js t('should switch to a webview by providing a specific app identifier (bundleId for iOS or packageName for Android)', async () => { // For Android, provide the packageName to search in a specific app (useful for overlays or non-active apps) await driver.switchContext({ appIdentifier: 'com.otherApp', title: 'Other Apps', }) // For iOS, provide the bundleId to search in a specific app await driver.switchContext({ appIdentifier: 'com.apple.mobilesafari', url: /.*apple.com/, }) ) ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/tap.md # tap Performs a tap gesture on: * or the given element. It will **automatically scroll** if it can't be found. * or the screen on a mobile device by providing `x` and `y` coordinates Internally it uses: * Element tap: <!-- --> * the `click` command for Web environments (Chrome/Safari browsers, or hybrid apps) * the Android [`mobile: clickGesture`](https://appium.github.io/appium-uiautomator2-driver/latest/reference/execute-methods/#mobile-clickgesture) or iOS [`mobile: tap`](https://appium.github.io/appium-xcuitest-driver/latest/reference/execute-methods/#mobile-tap) for Natives apps, including the `scrollIntoView` command for automatic scrolling * Screen tap: <!-- --> * the `action` command for Web environments (Chrome/Safari browsers, or hybrid apps) * the Android [`mobile: clickGesture`](https://appium.github.io/appium-uiautomator2-driver/latest/reference/execute-methods/#mobile-clickgesture) or iOS [`mobile: tap`](https://appium.github.io/appium-xcuitest-driver/latest/reference/execute-methods/#mobile-tap) for Natives apps This difference makes the `tap` command a more reliable alternative to the `click` command for mobile apps. For Native Apps, this command differs from the `click` command as it will **automatically swipe** to the element using the `scrollIntoView command`, which is not supported for native apps with the `click` command. In hybrid apps or web environments, automatic scrolling is supported for both `click` and `tap` commands. info This command only works with the following up-to-date components: * Appium server (version 2.0.0 or higher) * `appium-uiautomator2-driver` (for Android) * `appium-xcuitest-driver` (for iOS) Make sure your local or cloud-based Appium environment is regularly updated to avoid compatibility issues. For Screen taps If you want to tap on a specific coordinate on the screen and you use a screenshot to determine the coordinates, remember that the the coordinates for iOS are based on the device's screen size, and not the screenshot size. The screenshot size is larger due to the device pixel ratio. The average device pixel ratio until the iPhone 8 and the current iPads is 2, for iPhones from the iPhone X the ratio is 3. This means that the screenshot size is 2 or 3 times larger than the device's screen size which means that ff you find the coordinates on the screenshot, divide them by the device pixel ratio to get the correct screen coordinates. For example: ``` const screenshotCoordinates = { x: 600, y: 900 }; const dpr = 3; // Example for iPhone 16 const screenCoordinates = { x: screenshotCoordinates.x / dpr, y: screenshotCoordinates.y / dpr }; await browser.tap(screenCoordinates); ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `options`<br />*optional* | `TapOptions` | Tap options (optional) | | **Element tap options** | | | | `options.x`<br />*optional* | `number` | Number (optional, mandatory if y is set)<br />**Only for SCREEN tap, not for ELEMENT tap** | | `options.y`<br />*optional* | `number` | Number (optional, mandatory if x is set)<br />**Only for SCREEN tap, not for ELEMENT tap** | | **Screen tap options** | | | | `options.direction`<br />*optional* | `string` | Can be one of `down`, `up`, `left` or `right`, default is `down`.<br />**Only for ELEMENT tap, not for SCREEN tap**<br />**MOBILE-NATIVE-APP-ONLY** | | `options.maxScrolls`<br />*optional* | `number` | The max amount of scrolls until it will stop searching for the element, default is `10`.<br />**Only for ELEMENT tap, not for SCREEN tap**<br />**MOBILE-NATIVE-APP-ONLY** | | `options.scrollableElement`<br />*optional* | `Element` | Element that is used to scroll within. If no element is provided it will use the following selector for iOS `-ios predicate string:type == "XCUIElementTypeApplication"` and the following for Android `//android.widget.ScrollView'`. If more elements match the default selector, then by default it will pick the first matching element.<br />**Only for ELEMENT tap, not for SCREEN tap**<br />**MOBILE-NATIVE-APP-ONLY** | ## Examples[​](#examples "Direct link to Examples") element.tap.example.js ``` it('should be able to tap an on element', async () => { const elem = $('~myElement') // It will automatically scroll to the element if it's not already in the viewport await elem.tap() }) ``` element.tap.scroll.options.example.js ``` it('should be able to swipe right 3 times in a custom scroll areas to an element and tap on the element', async () => { const elem = $('~myElement') // Swipe right 3 times in the custom scrollable element to find the element await elem.tap({ direction: 'right', maxScrolls: 3, scrollableElement: $('#scrollable') }) }) ``` screen.tap.example.js ``` it('should be able to tap on screen coordinates', async () => { await browser.tap({ x: 200, y: 400 }) }) ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/toggleAirplaneMode.md # toggleAirplaneMode Set the airplane mode state on the device. note Unlike the deprecated API which toggled the airplane mode state, this command requires an explicit `enabled` parameter to set the desired state directly. This command is only supported on Android. ## Usage[​](#usage "Direct link to Usage") ``` await browser.toggleAirplaneMode(enabled) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------- | --------- | ------------------------------------------------------------- | | `enabled` | `boolean` | Set to `true` to enable airplane mode, `false` to disable it. | ## Example[​](#example "Direct link to Example") toggleAirplaneMode.js ``` it('should set airplane mode', async () => { // Enable airplane mode await browser.toggleAirplaneMode(true) // Disable airplane mode await browser.toggleAirplaneMode(false) }) ``` ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/toggleData.md # toggleData Set the mobile data state on the device. note Unlike the deprecated API which toggled the data state, this command requires an explicit `enabled` parameter to set the desired state directly. This command is only supported on Android. ## Usage[​](#usage "Direct link to Usage") ``` await browser.toggleData(enabled) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------- | --------- | ----------------------------------------------------------- | | `enabled` | `boolean` | Set to `true` to enable mobile data, `false` to disable it. | ## Example[​](#example "Direct link to Example") toggleData.js ``` it('should set mobile data state', async () => { await browser.toggleData(true) // enable data await browser.toggleData(false) // disable data }) ``` ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/toggleEnrollTouchId.md # toggleEnrollTouchId Toggle Touch ID enrollment on iOS Simulator. note This command requires the `allowTouchIdEnroll` capability to be set to `true` in the session. It is only supported on iOS Simulator. When `enabled` is not provided, it defaults to `true`. ## Usage[​](#usage "Direct link to Usage") ``` await browser.toggleEnrollTouchId(enabled) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------- | --------- | ---------------------------------------------------------------------------------------- | | `enabled`<br />*optional* | `boolean` | Whether to enable (`true`) or disable (`false`) Touch ID enrollment. Defaults to `true`. | ## Example[​](#example "Direct link to Example") toggleEnrollTouchId.js ``` it('should toggle Touch ID enrollment', async () => { // Enable Touch ID enrollment await browser.toggleEnrollTouchId(true) // Disable Touch ID enrollment await browser.toggleEnrollTouchId(false) }) ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) **Supported platforms:** iOS note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/toggleLocationServices.md # toggleLocationServices Toggle the state of the location service. ## Usage[​](#usage "Direct link to Usage") ``` await browser.toggleLocationServices() ``` ## Example[​](#example "Direct link to Example") toggleLocationServices.js ``` it('should toggle location services', async () => { await browser.toggleLocationServices() }) ``` ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/toggleNetworkSpeed.md # toggleNetworkSpeed Set the network speed for the Android emulator. Valid values: 'full', 'gsm', 'edge', 'hscsd', 'gprs', 'umts', 'hsdpa', 'lte', 'evdo'. ## Usage[​](#usage "Direct link to Usage") ``` await browser.toggleNetworkSpeed(netspeed) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------- | -------- | ---------------------------------------------------------------------------------------------------------- | | `netspeed` | `string` | The network speed preset to apply ('full', 'gsm', 'edge', 'hscsd', 'gprs', 'umts', 'hsdpa', 'lte', 'evdo') | ## Example[​](#example "Direct link to Example") toggleNetworkSpeed.js ``` it('should set network speed to LTE', async () => { await browser.toggleNetworkSpeed('lte') }) ``` ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/toggleWiFi.md # toggleWiFi Set the WiFi state on the device. note Unlike the deprecated API which toggled the WiFi state, this command requires an explicit `enabled` parameter to set the desired state directly. This command is only supported on Android. ## Usage[​](#usage "Direct link to Usage") ``` await browser.toggleWiFi(enabled) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | --------- | --------- | ---------------------------------------------------- | | `enabled` | `boolean` | Set to `true` to enable WiFi, `false` to disable it. | ## Example[​](#example "Direct link to Example") toggleWiFi.js ``` it('should set WiFi state', async () => { await browser.toggleWiFi(true) // enable WiFi await browser.toggleWiFi(false) // disable WiFi }) ``` ## Support[​](#support "Direct link to Support") ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/touchId.md # touchId Simulate a Touch ID or Face ID biometric match event on iOS Simulator. note This command requires the `allowTouchIdEnroll` capability to be set to `true` in the session. It is only supported on iOS Simulator. ## Usage[​](#usage "Direct link to Usage") ``` await browser.touchId(match, type) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------------------- | --------- | ------------------------------------------------------------------------------------------------------------------- | | `match` | `boolean` | Whether the biometric match should succeed (`true`) or fail (`false`) | | `type`<br />*optional* | `string` | The biometric type to simulate. Use `'touchId'` for Touch ID (default) or `'faceId'` for Face ID.<br />**iOS-ONLY** | ## Example[​](#example "Direct link to Example") touchId.js ``` it('should simulate a Touch ID fingerprint match', async () => { // Simulate a successful Touch ID match await browser.touchId(true) // Simulate a failed Touch ID match await browser.touchId(false) }) it('should simulate a Face ID match', async () => { // Simulate a successful Face ID match await browser.touchId(true, 'faceId') // Simulate a failed Face ID match await browser.touchId(false, 'faceId') }) ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) **Supported platforms:** iOS note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/unlock.md # unlock Unlock the device screen. ## Usage[​](#usage "Direct link to Usage") ``` await browser.unlock({ strategy, timeoutMs, unlockKey, unlockType }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------------------ | -------- | --------------------------------------------------------------------------------------------------------------------------- | | `options`<br />*optional* | `object` | Unlock options (Android only) | | `options.strategy`<br />*optional* | `string` | The unlock strategy to use. Accepted values: `'locksettings'` (default) or `'uiautomator'`.<br />**ANDROID-ONLY** | | `options.timeoutMs`<br />*optional* | `number` | The timeout in milliseconds to wait for the unlock to complete. Default is `2000`.<br />**ANDROID-ONLY** | | `options.unlockKey`<br />*optional* | `string` | The PIN, password, or pattern to use for unlocking. Required when the device has a PIN/password lock.<br />**ANDROID-ONLY** | | `options.unlockType`<br />*optional* | `string` | The type of lock mechanism on the device (e.g. `'pin'`, `'password'`, `'pattern'`).<br />**ANDROID-ONLY** | ## Example[​](#example "Direct link to Example") unlock.js ``` it('should unlock the device screen', async () => { // Unlock with no arguments (iOS or Android with default settings) await browser.unlock() }) it('should unlock Android with a PIN', async () => { // Android-only: unlock using locksettings strategy with a PIN await browser.unlock({ strategy: 'locksettings', unlockType: 'pin', unlockKey: '1234' }) }) it('should unlock Android with a custom timeout', async () => { // Android-only: unlock with a custom timeout await browser.unlock({ timeoutMs: 5000 }) }) ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mobile/zoom.md # zoom Performs a zoom gesture on the given element on the screen. info Zooming is done based on native mobile gestures. It is only supported for the following drivers: * [appium-uiautomator2-driver](https://appium.github.io/appium-uiautomator2-driver/latest/reference/execute-methods/#mobile-pinchopengesture) for Android * [appium-xcuitest-driver](https://appium.github.io/appium-xcuitest-driver/latest/reference/execute-methods/#mobile-pinch) for iOS This command only works with the following up-to-date components: * Appium server (version 2.0.0 or higher) * `appium-uiautomator2-driver` (for Android) * `appium-xcuitest-driver` (for iOS) Make sure your local or cloud-based Appium environment is regularly updated to avoid compatibility issues. ## Usage[​](#usage "Direct link to Usage") ``` await $(selector).zoom({ duration, scale }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------------------------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | `options`<br />*optional* | `PinchAndZoomOptions` | Zoom options (optional) | | `options.duration`<br />*optional* | `number` | The duration in millisecond of how fast the zoom should be executed, minimal is 500 ms and max is 10000 ms. The default is 1500 ms (1.5 seconds) (optional) | | `options.scale`<br />*optional* | `number` | The scale of how big the zoom should be according to the screen. Valid values must be float numbers in range 0..1, where 1.0 is 100% (optional) | ## Example[​](#example "Direct link to Example") zoom.js ``` it('should demonstrate a zoom on Google maps', async () => { const mapsElement = $('//*[@resource-id="com.google.android.apps.maps:id/map_frame"]') // Zoom with the default duration scale await mapsElement.zoom() // Zoom with a custom duration and scale await mapsElement.zoom({ duration: 4000, scale: 0.9 }) }) ``` ## Support[​](#support "Direct link to Support") ![Support for ios](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iRWJlbmVfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgd2lkdGg9IjQ5Ni4yNTVweCIgaGVpZ2h0PSI2MDguNzI4cHgiIHZpZXdCb3g9IjAgMCA0OTYuMjU1IDYwOC43MjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ5Ni4yNTUgNjA4LjcyODsiCgkgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxwYXRoIHN0eWxlPSJmaWxsOiM5OTk5OTk7IiBkPSJNMjczLjgxLDUyLjk3M0MzMTMuODA2LDAuMjU3LDM2OS40MSwwLDM2OS40MSwwczguMjcxLDQ5LjU2Mi0zMS40NjMsOTcuMzA2CgljLTQyLjQyNiw1MC45OC05MC42NDksNDIuNjM4LTkwLjY0OSw0Mi42MzhTMjM4LjI0Myw5OS44NSwyNzMuODEsNTIuOTczeiIvPgo8cGF0aCBzdHlsZT0iZmlsbDojOTk5OTk5OyIgZD0iTTI1Mi4zODUsMTc0LjY2MmMyMC41NzYsMCw1OC43NjQtMjguMjg0LDEwOC40NzEtMjguMjg0Yzg1LjU2MiwwLDExOS4yMjIsNjAuODgzLDExOS4yMjIsNjAuODgzCglzLTY1LjgzMywzMy42NTktNjUuODMzLDExNS4zMzFjMCw5Mi4xMzMsODIuMDEsMTIzLjg4NSw4Mi4wMSwxMjMuODg1cy01Ny4zMjgsMTYxLjM1Ny0xMzQuNzYyLDE2MS4zNTcKCWMtMzUuNTY1LDAtNjMuMjE1LTIzLjk2Ny0xMDAuNjg4LTIzLjk2N2MtMzguMTg4LDAtNzYuMDg0LDI0Ljg2MS0xMDAuNzY2LDI0Ljg2MUM4OS4zMyw2MDguNzMsMCw0NTUuNjY2LDAsMzMyLjYyOAoJYzAtMTIxLjA1Miw3NS42MTItMTg0LjU1NCwxNDYuNTMzLTE4NC41NTRDMTkyLjYzOCwxNDguMDc0LDIyOC40MTYsMTc0LjY2MiwyNTIuMzg1LDE3NC42NjJ6Ii8+Cjwvc3ZnPgo=) ![Support for android](/assets/images/android-d941e94d5839760141de31c8446b67ce.svg) **Supported platforms:** iOS, Android note Refer to the official [Appium driver documentation](https://appium.io/docs/en/latest/ecosystem/) to see which driver versions support this command. --- Source: https://webdriver.io/docs/api/mock.md # The Mock Object The mock object is an object that represents a network mock and contains information about requests that were matching given `url` and `filterOptions`. It can be received using the [`mock`](/docs/api/browser/mock.md) command. info Note that using the `mock` command requires support for Chrome DevTools protocol. That support is given if you run tests locally in Chromium based browser or if you use a Selenium Grid v4 or higher. This command can **not** be used when running automated tests in the cloud. Find out more in the [Automation Protocols](/docs/automationProtocols.md) section. You can read more about mocking requests and responses in WebdriverIO in our [Mocks and Spies](/docs/mocksandspies.md) guide. ## Multi-remote[​](#multi-remote "Direct link to Multi-remote") On a [multi-remote](/docs/multiremote.md) browser, [`browser.mock()`](/docs/api/browser/mock.md) returns a `MultiRemoteMock` instead of this object. `instances` lists the browser names, and `getInstance(name)` returns the `Mock` for that browser. `respond()`, `restore()`, and the other methods below run on every instance. `calls` stays on each instance's mock: `mock.getInstance('myChromeBrowser').calls`. `getInstance` throws `Multi-remote object has no instance named "<name>"` when `name` is not one of `instances`. ## Properties[​](#properties "Direct link to Properties") A mock object contains the following properties: | Name | Type | Details | | --------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `url` | `String` | The url passed into the mock command | | `filterOptions` | `Object` | The resource filter options passed into the mock command | | `browser` | `Object` | The [Browser Object](/docs/api/browser.md) used to get the mock object. | | `calls` | `Object[]` | Information about matching browser requests, containing properties such as `url`, `method`, `headers`, `initialPriority`, `referrerPolic`, `statusCode`, `responseHeaders` and `body` | ## Methods[​](#methods "Direct link to Methods") Mock objects provide various commands, listed in the `mock` section, that allow users to modify the behavior of the request or response. * [`abort`](/docs/api/mock/abort.md) * [`abortOnce`](/docs/api/mock/abortOnce.md) * [`clear`](/docs/api/mock/clear.md) * [`request`](/docs/api/mock/request.md) * [`requestOnce`](/docs/api/mock/requestOnce.md) * [`respond`](/docs/api/mock/respond.md) * [`respondOnce`](/docs/api/mock/respondOnce.md) * [`restore`](/docs/api/mock/restore.md) * [`waitForResponse`](/docs/api/mock/waitForResponse.md) ## Events[​](#events "Direct link to Events") The mock object is an EventEmitter and a couple of events are emitted for your use cases. Here is a list of events. ### `request`[​](#request "Direct link to request") This event is being emitted when launching a network request that matches mock patterns. Request is passed in event callback. Request interface: ``` interface RequestEvent { requestId: number request: Matches responseStatusCode: number responseHeaders: Record<string, string> } ``` ### `overwrite`[​](#overwrite "Direct link to overwrite") This event is being emitted when network response is overwrited with [`respond`](/docs/api/mock/respond.md) or [`respondOnce`](/docs/api/mock/respondOnce.md). Response is passed in event callback. Response interface: ``` interface OverwriteEvent { requestId: number responseCode: number responseHeaders: Record<string, string> body?: string | Record<string, any> } ``` ### `fail`[​](#fail "Direct link to fail") This event is being emitted when network request is aborted with [`abort`](/docs/api/mock/abort.md) or [`abortOnce`](/docs/api/mock/abortOnce.md). Fail is passed in event callback. Fail interface: ``` interface FailEvent { requestId: number errorReason: Protocol.Network.ErrorReason } ``` ### `match`[​](#match "Direct link to match") This event is being emitted when new match is added, before `continue` or `overwrite`. Match is passed in event callback. Match interface: ``` interface MatchEvent { url: string // Request URL (without fragment). urlFragment?: string // Fragment of the requested URL starting with hash, if present. method: string // HTTP request method. headers: Record<string, string> // HTTP request headers. postData?: string // HTTP POST request data. hasPostData?: boolean // True when the request has POST data. mixedContentType?: MixedContentType // The mixed content export type of the request. initialPriority: ResourcePriority // Priority of the resource request at the time request is sent. referrerPolicy: ReferrerPolicy // The referrer policy of the request, as defined in https://www.w3.org/TR/referrer-policy/ isLinkPreload?: boolean // Whether is loaded via link preload. body: string | Buffer | JsonCompatible // Body response of actual resource. responseHeaders: Record<string, string> // HTTP response headers. statusCode: number // HTTP response status code. mockedResponse?: string | Buffer // If mock, emitting the event, also modified it's response. } ``` ### `continue`[​](#continue "Direct link to continue") This event is being emitted when the network response has neither been overwritten nor interrupted, or if response was already sent by another mock. `requestId` is passed in event callback. ## Which mock answers a request[​](#which-mock-answers-a-request "Direct link to Which mock answers a request") Several mocks can match one request. In each phase of the request (before the request is sent, and when the response starts), one mock acts on it, in this order: 1. A mock that acts (`respond`, `abort`, `request`) beats a mock that only lets the request through, such as a spy or a mock that used up its `once` calls. 2. A mock of a tab or of a parallel test beats a session-wide mock from `browser.mock()`. 3. The mock that was created first wins. The other mocks emit `continue` for this request. An `abort()` that gives way and fails the request when the response starts emits `fail` instead. Each phase has its own winner, so two mocks can act on one request. For example, a `request()` overwrite of a tab can change the request, and then a session-wide `respond()` can replace the response. `browser.mock()` replaces an existing mock only when the URL definition and the scope (session-wide, tab or parallel test) are the same. If a mock waits for the response (for example with a `statusCode` filter) and the response does not match, the next mock in this order answers in Chrome. In Firefox, a mock that waits for the response cannot send a body after the request left. It gives way to a mock that answers early, and WebdriverIO logs one warning for each such mock. A mock that gives way before the request is sent lets the request reach the server. Its `request()` or `redirect()` overwrite does not apply to this request. This is also true for an `abort()` and for a `respond()` with `fetchResponse: false`. When such a `respond()` answers at the response, it sends the status 200, or its `statusCode` option. In Firefox, it cannot send a body at the response, so the real response goes through. In Chrome, a session-wide `abort()` that gives way to a mock that waits for the response fails the request only after the server answered, and only when the response does not match the filter of that mock. The same hand-over applies between two `browser.mock()` mocks when the older one waits for the response. In Firefox, the `abort()` wins before the request is sent. If a filter function or a `request` event handler of a matching mock throws, WebdriverIO logs the error and fails the request. This order applies to the mocks of one browser object. Two `attach()` clients of one session do not share it: a mock of one client does not give way to a mock of the other client. But a `browser.mock()` with the same URL definition on one client replaces the mock of the other client, because both clients use the same session. ## Examples[​](#examples "Direct link to Examples") Getting a number of pending requests: ``` let pendingRequests = 0 const mock = await browser.mock('**') // it is important to match all requests otherwise, the resulting value can be very confusing. mock.on('request', ({request}) => { pendingRequests++ console.log(`matched request to ${request.url}, pending ${pendingRequests} requests`) }) mock.on('match', ({url}) => { pendingRequests-- console.log(`resolved request to ${url}, pending ${pendingRequests} requests`) }) ``` Throwing an error on 404 network fail: ``` browser.addCommand('loadPageWithout404', (url, {selector, predicate}) => new Promise(async (resolve, reject) => { const mock = await this.mock('**') mock.on('match', ({url, statusCode}) => { if (statusCode === 404) { reject(new Error(`request to ${url} failed with "Not Found"`)) } }) await this.url(url).catch(reject) // waiting here, because some requests can still be pending if (selector) { await this.$(selector).waitForExist().catch(reject) } if (predicate) { await this.waitUntil(predicate).catch(reject) } resolve() })) await browser.loadPageWithout404(browser, 'some/url', { selector: 'main' }) ``` Determining if mock respond value was used: ``` const firstMock = await browser.mock('**/foo/**') const secondMock = await browser.mock('**/foo/bar/**') firstMock.respondOnce({id: 3, title: 'three'}) secondMock.respond({id: 4, title: 'four'}) firstMock.on('overwrite', () => { // triggers for first request to '**/foo/**' }).on('continue', () => { // triggers for rest requests to '**/foo/**' }) secondMock.on('continue', () => { // triggers for first request to '**/foo/bar/**' }).on('overwrite', () => { // triggers for rest requests to '**/foo/bar/**' }) ``` In this example, `firstMock` was defined first and has one `respondOnce` call, so the `secondMock` response value will not be used for the first request. After `firstMock` used its response, it only lets requests through, so the `secondMock` response value is used for the rest of them. --- Source: https://webdriver.io/docs/api/mock/abort.md # abort Abort the request with one of the following error codes: `Failed`, `Aborted`, `TimedOut`, `AccessDenied`, `ConnectionClosed`, `ConnectionReset`, `ConnectionRefused`, `ConnectionAborted`, `ConnectionFailed`, `NameNotResolved`, `InternetDisconnected`, `AddressUnreachable`, `BlockedByClient`, `BlockedByResponse`. ## Usage[​](#usage "Direct link to Usage") ``` mock.abort(errorCode) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ----------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `errorCode` | `ErrorCode` | error code of the response, can be one of: `Failed`, `Aborted`, `TimedOut`, `AccessDenied`, `ConnectionClosed`, `ConnectionReset`, `ConnectionRefused`, `ConnectionAborted`, `ConnectionFailed`, `NameNotResolved`, `InternetDisconnected`, `AddressUnreachable`, `BlockedByClient`, `BlockedByResponse` | ## Example[​](#example "Direct link to Example") abort.js ``` it('should block Google Analytics from page', async () => { const mock = await browser.mock('https://www.google-analytics.com/**') mock.abort('Failed') }) ``` --- Source: https://webdriver.io/docs/api/mock/abortOnce.md # abortOnce Abort the request once with one of the following error codes: `Failed`, `Aborted`, `TimedOut`, `AccessDenied`, `ConnectionClosed`, `ConnectionReset`, `ConnectionRefused`, `ConnectionAborted`, `ConnectionFailed`, `NameNotResolved`, `InternetDisconnected`, `AddressUnreachable`, `BlockedByClient`, `BlockedByResponse`. ## Usage[​](#usage "Direct link to Usage") ``` mock.abortOnce(errorCode) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ----------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `errorCode` | `ErrorCode` | error code of the response, can be one of: `Failed`, `Aborted`, `TimedOut`, `AccessDenied`, `ConnectionClosed`, `ConnectionReset`, `ConnectionRefused`, `ConnectionAborted`, `ConnectionFailed`, `NameNotResolved`, `InternetDisconnected`, `AddressUnreachable`, `BlockedByClient`, `BlockedByResponse` | ## Example[​](#example "Direct link to Example") abortOnce.js ``` it('should block mock only once', async () => { const mock = await browser.mock('https://webdriver.io') mock.abortOnce('Failed') await browser.url('https://webdriver.io') // catch failing command as page can't be loaded .catch(() => {}) console.log(await browser.getTitle()) // outputs: "" await browser.url('https://webdriver.io') console.log(await browser.getTitle()) // outputs: "WebdriverIO · Next-gen browser and mobile automation test framework for Node.js" }) ``` --- Source: https://webdriver.io/docs/api/mock/clear.md # clear Resets all information stored in the `mock.calls` array. ## Usage[​](#usage "Direct link to Usage") ``` mock.clear() ``` ## Example[​](#example "Direct link to Example") clear.js ``` it('should clear mock', async () => { const mock = await browser.mock('https://google.com/') await browser.url('https://google.com') console.log(mock.calls.length) // returns 1 mock.clear() console.log(mock.calls.length) // returns 0 }) ``` --- Source: https://webdriver.io/docs/api/mock/redirect.md # redirect Sets up a redirect for a given mock. This allows you to redirect a request to another URL. Note: these redirects only apply to requests made by a script in the browser, not when calling the `url` command. ## Usage[​](#usage "Direct link to Usage") ``` mock.redirect(url) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ----- | -------- | --------------------------------------- | | `url` | `string` | target resource to redirect requests to | ## Example[​](#example "Direct link to Example") respond.js ``` it('redirects all my API request to my staging server', async () => { const mock = await browser.mock('https://application.com/api/*') mock.redirect('https://staging.application.com/api/*') // is the same as mock.request({ url: 'https://staging.application.com/api/*' }) // ... }) ``` --- Source: https://webdriver.io/docs/api/mock/request.md # request Allows you do modify requests the browser makes during the session. This can be useful for the following use cases: * validating if your application sends correct request payloads * passing through authorization headers to test protected resources * setting session cookies to test user authentication * modifying requests to test edge cases ## Usage[​](#usage "Direct link to Usage") ``` mock.request({ header, cookies, method, url, header, statusCode, fetchResponse }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | -------------------------------------- | ----------------------- | ------------------------------------------------------ | | `overwrites` | `MockOverwrite` | payload to overwrite the response | | `overwrites.header` | `Record<string,string>` | overwrite specific headers | | `overwrites.cookies` | `Record<string,string>` | overwrite request cookies | | `overwrites.method` | `string` | overwrite request method | | `overwrites.url` | `string` | overwrite request url to initiate a redirect | | `params`<br />*optional* | `MockResponseParams` | additional respond parameters to overwrite | | `params.header`<br />*optional* | `Object` | overwrite specific headers | | `params.statusCode`<br />*optional* | `Number` | overwrite response status code | | `params.fetchResponse`<br />*optional* | `Boolean` | fetch real response before responding with mocked data | ## Example[​](#example "Direct link to Example") respond.js ``` it('adds an auth header to my API requests', async () => { const mock = await browser.mock('https://application.com/api', { method: 'get' }) mock.request({ headers: { 'Authorization': 'Bearer token' } }) await browser.url('https://application.com') // ... }) ``` --- Source: https://webdriver.io/docs/api/mock/requestOnce.md # requestOnce Only change request parameter once with given overwrite for the next request. You can call `requestOnce` multiple consecutive times and it will apply the overwrites in order. If you only use `requestOnce` and the resource is called more times a mock has been defined than it defaults back to the original resource. ## Usage[​](#usage "Direct link to Usage") ``` mock.requestOnce({ header, cookies, method, url, header, statusCode, fetchResponse }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | -------------------------------------- | ------------------------ | ------------------------------------------------------ | | `overwrites` | `MockOverwrite` | payload to overwrite the response | | `overwrites.header` | `Record<string, string>` | overwrite specific headers | | `overwrites.cookies` | `Record<string, string>` | overwrite request cookies | | `overwrites.method` | `string` | overwrite request method | | `overwrites.url` | `string` | overwrite request url to initiate a redirect | | `params`<br />*optional* | `MockResponseParams` | additional respond parameters to overwrite | | `params.header`<br />*optional* | `Object` | overwrite specific headers | | `params.statusCode`<br />*optional* | `Number` | overwrite response status code | | `params.fetchResponse`<br />*optional* | `Boolean` | fetch real response before responding with mocked data | ## Example[​](#example "Direct link to Example") respond.js ``` it('adds different auth headers to my API requests', async () => { const mock = await browser.mock('https://application.com/api', { method: 'get' }) mock.requestOnce({ headers: { 'Authorization': 'Bearer token' } }) mock.requestOnce({ headers: { 'Authorization': 'Another bearer token' } }) await browser.url('https://application.com') // ... }) ``` --- Source: https://webdriver.io/docs/api/mock/respond.md # respond Always respond with same overwrite. ## Usage[​](#usage "Direct link to Usage") ``` mock.respond(overwrites, { header, statusCode, fetchResponse }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | -------------------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `overwrites` | `MockOverwrite` | payload to overwrite the response | | `params`<br />*optional* | `MockResponseParams` | additional respond parameters to overwrite | | `params.header`<br />*optional* | `Object` | overwrite specific headers | | `params.statusCode`<br />*optional* | `Number` | overwrite response status code | | `params.fetchResponse`<br />*optional* | `Boolean` | fetch the real response before responding. `false` skips the backend (unless this mock gives way to another mock before the request is sent) and throws when the mock filters on `statusCode` or `responseHeaders` | ## Example[​](#example "Direct link to Example") respond.js ``` it('should demonstrate response overwrite with static data', async () => { const mock = await browser.mock('https://todo-backend-express-knex.herokuapp.com/', { method: 'get' }) mock.respond([{ title: 'Injected (non) completed Todo', order: null, completed: false }, { title: 'Injected completed Todo', order: null, completed: true }], { statusCode: 200, fetchResponse: true // default }) await browser.url('https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/') await $('#todo-list li').waitForExist() console.log(await $$('#todo-list li').map(el => el.getText())) // outputs: "[ 'Injected (non) completed Todo', 'Injected completed Todo' ]" }) it('should demonstrate response overwrite with dynamic data', async () => { const mock = await browser.mock('https://todo-backend-express-knex.herokuapp.com/') mock.respond((request) => { if (request.body.username === 'test') { return { ...request.body, foo: 'bar' } } return request.body }, { statusCode: () => 200, headers: () => ({ foo: 'bar' }), fetchResponse: false // do not fetch real response }) }) ``` --- Source: https://webdriver.io/docs/api/mock/respondOnce.md # respondOnce Only respond once with given overwrite. You can call `respondOnce` multiple consecutive times and it will start with the respond you defined last. If you only use `respondOnce` and the resource is called more times a mock has been defined than it defaults back to the original resource. ## Usage[​](#usage "Direct link to Usage") ``` mock.respondOnce(overwrites, { header, statusCode, fetchResponse }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | -------------------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | `overwrites` | `MockOverwrite` | payload to overwrite the response | | `params`<br />*optional* | `MockResponseParams` | additional respond parameters to overwrite | | `params.header`<br />*optional* | `Object` | overwrite specific headers | | `params.statusCode`<br />*optional* | `Number` | overwrite response status code | | `params.fetchResponse`<br />*optional* | `Boolean` | fetch the real response before responding. `false` skips the backend and throws when the mock filters on `statusCode` or `responseHeaders` | ## Example[​](#example "Direct link to Example") respondOnce.js ``` async function getToDos () { await $('#todo-list li').waitForExist() return $$('#todo-list li').map(el => el.getText()) } it('should demonstrate the respondOnce command', async () => { const mock = await browser.mock('https://todo-backend-express-knex.herokuapp.com/', { method: 'get' }) mock.respondOnce([{ title: '3' }, { title: '2' }, { title: '1' }]) mock.respondOnce([{ title: '2' }, { title: '1' }]) mock.respondOnce([{ title: '1' }]) await browser.url('https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/') console.log(await getToDos()) // outputs [ '3', '2', '1' ] await browser.url('https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/') console.log(await getToDos()) // outputs [ '2', '1' ] await browser.url('https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/') console.log(await getToDos()) // outputs [ '1' ] await browser.url('https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/') console.log(await getToDos()) // outputs actual resource response }) ``` --- Source: https://webdriver.io/docs/api/mock/restore.md # restore Does everything that `mock.clear()` does, and also removes any mocked return values or implementations. Restored mock does not emit events and could not mock responses. ## Usage[​](#usage "Direct link to Usage") ``` mock.restore() ``` ## Example[​](#example "Direct link to Example") addValue.js ``` it('should demonstrate the addValue command', async () => { const mock = await browser.mock('*' + '/googlelogo_color_272x92dp.png') mock.respond('https://webdriver.io/img/webdriverio.png') await browser.url('https://google.com') // shows WebdriverIO logo instead of Google await mock.restore() await browser.url('https://google.com') // shows normal Google logo again }) ``` --- Source: https://webdriver.io/docs/api/mock/waitForResponse.md # waitForResponse Wait until at least one matching request has received a response. ## Usage[​](#usage "Direct link to Usage") ``` mock.waitForResponse({ timeout, interval, timeoutMsg }) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------------------------------------ | ---------------- | ------------------------------------------------------------------- | | `options`<br />*optional* | `WaitForOptions` | wait options | | `options.timeout`<br />*optional* | `Number` | max wait time in ms (defaults to `browser.options.waitforTimeout`) | | `options.interval`<br />*optional* | `Number` | poll interval in ms (defaults to `browser.options.waitforInterval`) | | `options.timeoutMsg`<br />*optional* | `String` | custom timeout error message | ## Example[​](#example "Direct link to Example") waitForResponse.js ``` it('should wait for a matching response', async () => { const mock = await browser.mock('*' + '/users/list') // trigger action that issues the request await $('#load').click() await mock.waitForResponse({ timeout: 5000 }) expect(mock.calls.length).toBeGreaterThan(0) }) ``` --- Source: https://webdriver.io/docs/api/dialog.md # The Dialog Object Dialog objects are dispatched by [`browser`](/docs/api/browser.md) via the `browser.on('dialog')` event. An example of using the Dialog object: ``` import { browser } from '@wdio/globals' await browser.url('https://webdriver.io') browser.on('dialog', async (dialog) => { console.log(dialog.message()) // outputs: "Hello Dialog" await dialog.dismiss() }) await browser.execute(() => alert('Hello Dialog')) ``` note Dialogs are dismissed automatically, unless there is at least one `browser.on('dialog')` or `browser.once('dialog')` listener. When a listener is present, it must either [`dialog.accept()`](/docs/api/dialog/accept.md) or [`dialog.dismiss()`](/docs/api/dialog/dismiss.md) the dialog - otherwise the page will freeze waiting for the dialog, and actions like click will never finish. Mobile native dialogs Browser dialog events are not emitted for native iOS/Android permission dialogs. Handle those with [`browser.acceptDialog`](/docs/api/mobile/acceptDialog.md) and [`browser.dismissDialog`](/docs/api/mobile/dismissDialog.md) instead. --- Source: https://webdriver.io/docs/api/dialog/accept.md # accept Accepts the dialog and returns when the dialog has been handled. info Only works with browser dialogs (via BiDi protocol). For mobile native dialogs, use [`browser.acceptDialog`](/docs/api/mobile/acceptDialog.md) instead. ## Usage[​](#usage "Direct link to Usage") ``` await dialog.accept(promptText) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---------------------------- | -------- | ------------------------------------------------------------------------------------------- | | `promptText`<br />*optional* | `string` | A text to enter into prompt. Does not cause any effects if the dialog's type is not prompt. | ## Example[​](#example "Direct link to Example") dialogAccept.js ``` // Listen for the dialog event to get the dialog object browser.on('dialog', async (dialog) => { console.log(dialog.message()); // prints: 'Hello, world!' await dialog.accept(); }); // Or accept a prompt dialog with text browser.on('dialog', async (dialog) => { if (dialog.type() === 'prompt') { await dialog.accept('my input'); } }); ``` --- Source: https://webdriver.io/docs/api/dialog/defaultValue.md # defaultValue If dialog is prompt, returns default prompt value. Otherwise, returns empty string. info Only works with browser dialogs (via BiDi protocol). Native mobile dialogs do not expose a default value through WebDriver. Use [`browser.acceptDialog`](/docs/api/mobile/acceptDialog.md) or [`browser.dismissDialog`](/docs/api/mobile/dismissDialog.md) to handle them. ## Usage[​](#usage "Direct link to Usage") ``` await dialog.defaultValue() ``` ## Example[​](#example "Direct link to Example") dialogDefaultValue.js ``` // Listen for the dialog event to get the dialog object browser.on('dialog', async (dialog) => { if (dialog.type() === 'prompt') { const value = await dialog.defaultValue(); console.log(value); // prints the default prompt value } }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<string>** **`returns`:** The default prompt value, or empty string if not a prompt. --- Source: https://webdriver.io/docs/api/dialog/dismiss.md # dismiss Dismisses the dialog and returns when the dialog has been handled. info Only works with browser dialogs (via BiDi protocol). For mobile native dialogs, use [`browser.dismissDialog`](/docs/api/mobile/dismissDialog.md) instead. ## Usage[​](#usage "Direct link to Usage") ``` await dialog.dismiss() ``` ## Example[​](#example "Direct link to Example") dialogDismiss.js ``` // Listen for the dialog event to get the dialog object browser.on('dialog', async (dialog) => { console.log(dialog.message()); // prints: 'Are you sure?' await dialog.dismiss(); }); ``` --- Source: https://webdriver.io/docs/api/dialog/message.md # message A message displayed in the dialog. info Only works with browser dialogs (via BiDi protocol). Native mobile dialogs do not expose their message through WebDriver. Use [`browser.acceptDialog`](/docs/api/mobile/acceptDialog.md) or [`browser.dismissDialog`](/docs/api/mobile/dismissDialog.md) to handle them. ## Usage[​](#usage "Direct link to Usage") ``` await dialog.message() ``` ## Example[​](#example "Direct link to Example") dialogMessage.js ``` // Listen for the dialog event to get the dialog object browser.on('dialog', async (dialog) => { const message = await dialog.message(); console.log(message); // prints: 'Hello, world!' }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<string>** **`returns`:** The message displayed in the dialog. --- Source: https://webdriver.io/docs/api/dialog/type.md # type Returns dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`. info Only works with browser dialogs (via BiDi protocol). Native mobile dialogs do not expose a dialog type through WebDriver. Use [`browser.acceptDialog`](/docs/api/mobile/acceptDialog.md) or [`browser.dismissDialog`](/docs/api/mobile/dismissDialog.md) to handle them. ## Usage[​](#usage "Direct link to Usage") ``` await dialog.type() ``` ## Example[​](#example "Direct link to Example") dialogType.js ``` // Listen for the dialog event to get the dialog object browser.on('dialog', async (dialog) => { const type = await dialog.type(); console.log(type); // prints: 'alert', 'confirm', 'prompt', or 'beforeunload' }); ``` ## Returns[​](#returns "Direct link to Returns") * **\<string>** **`returns`:** The type of the dialog --- Source: https://webdriver.io/docs/api/clock.md # The Clock Object You can modify the browser system clock using the [`emulate`](/docs/emulation.md) command. It overrides native global functions related to time allowing them to be controlled synchronously via `clock.tick()` or the yielded clock object. This includes controlling: * `setTimeout` * `clearTimeout` * `setInterval` * `clearInterval` * `Date Objects` The clock starts at the unix epoch (timestamp of 0). This means that when you instantiate new Date in your application, it will have a time of January 1st, 1970 if you don't pass any other options to the `emulate` command. ## Example[​](#example "Direct link to Example") When calling `browser.emulate('clock', { ... })` it will immediately overwrite the global functions for the current page as well as all following pages, e.g.: ``` const clock = await browser.emulate('clock', { now: new Date(1989, 7, 4) }) console.log(await browser.execute(() => (new Date()).toString())) // returns "Fri Aug 04 1989 00:00:00 GMT-0700 (Pacific Daylight Time)" await browser.url('https://webdriverio') console.log(await browser.execute(() => (new Date()).toString())) // returns "Fri Aug 04 1989 00:00:00 GMT-0700 (Pacific Daylight Time)" await clock.restore() console.log(await browser.execute(() => (new Date()).toString())) // returns "Thu Aug 01 2024 17:59:59 GMT-0700 (Pacific Daylight Time)" await browser.url('http://guinea-pig.webdriver.io/pointer.html') console.log(await browser.execute(() => (new Date()).toString())) // returns "Thu Aug 01 2024 17:59:59 GMT-0700 (Pacific Daylight Time)" ``` You can modify the system time by calling [`setSystemTime`](/docs/api/clock/setSystemTime.md) or [`tick`](/docs/api/clock/tick.md). --- Source: https://webdriver.io/docs/api/clock/restore.md # restore Restore all overridden native functions. This is automatically called between tests, so should not generally be needed. ## Usage[​](#usage "Direct link to Usage") ``` const clock = await browser.emulate('clock', { ... }) await clock.restore() ``` ## Example[​](#example "Direct link to Example") restore.js ``` console.log(new Date()) // returns e.g. 1722560447102 const clock = await browser.emulate('clock', { now: new Date(2021, 3, 14) }) console.log(await browser.execute(() => new Date().getTime())) // returns 1618383600000 await clock.restore() console.log(await browser.execute(() => new Date().getTime())) // returns 1722560447102 ``` ## Returns[​](#returns "Direct link to Returns") * **< `Promise<void>` >** --- Source: https://webdriver.io/docs/api/clock/setSystemTime.md # setSystemTime Change the system time to the new now. Now can be a timestamp, date object, or not passed in which defaults to 0. No timers will be called, nor will the time left before they trigger change. ## Usage[​](#usage "Direct link to Usage") ``` const clock = await browser.emulate('clock', { ... }) await clock.setSystemTime(date) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ------ | -------------- | --------------------------------------- | | `date` | `Date, number` | The new date to set the system time to. | ## Example[​](#example "Direct link to Example") setSystemTime.js ``` const clock = await browser.emulate('clock', { now: new Date(2021, 3, 14) }) console.log(await browser.execute(() => new Date().getTime())) // returns 1618383600000 await clock.setSystemTime(new Date(2011, 3, 15)) console.log(await browser.execute(() => new Date().getTime())) // returns 1302850800000 ``` ## Returns[​](#returns "Direct link to Returns") * **< `Promise<void>` >** --- Source: https://webdriver.io/docs/api/clock/tick.md # tick Move the clock the specified number of `milliseconds`. Any timers within the affected range of time will be called. ## Usage[​](#usage "Direct link to Usage") ``` const clock = await browser.emulate('clock', { ... }) await clock.tick(ms) ``` ## Parameters[​](#parameters "Direct link to Parameters") | Name | Type | Details | | ---- | -------- | --------------------------------------------- | | `ms` | `number` | The number of milliseconds to move the clock. | ## Example[​](#example "Direct link to Example") tick.js ``` const clock = await browser.emulate('clock', { now: new Date(2021, 3, 14) }) console.log(await browser.execute(() => new Date().getTime())) // returns 1618383600000 await clock.tick(1000) console.log(await browser.execute(() => new Date().getTime())) // returns 1618383601000 ``` ## Returns[​](#returns "Direct link to Returns") * **< `Promise<void>` >**