Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
docs(android): extract android docs into docs/src/mobile-api (#40644)
Pavel Feldmana57d8cd20215
diff --git a/docs/src/api/class-android.md b/docs/src/mobile-api/class-android.mdsimilarity index 100%rename from docs/src/api/class-android.mdrename to docs/src/mobile-api/class-android.mddiff --git a/docs/src/api/class-androiddevice.md b/docs/src/mobile-api/class-androiddevice.mdsimilarity index 100%rename from docs/src/api/class-androiddevice.mdrename to docs/src/mobile-api/class-androiddevice.mddiff --git a/docs/src/api/class-androidinput.md b/docs/src/mobile-api/class-androidinput.mdsimilarity index 100%rename from docs/src/api/class-androidinput.mdrename to docs/src/mobile-api/class-androidinput.mddiff --git a/docs/src/api/class-androidsocket.md b/docs/src/mobile-api/class-androidsocket.mdsimilarity index 100%rename from docs/src/api/class-androidsocket.mdrename to docs/src/mobile-api/class-androidsocket.mddiff --git a/docs/src/api/class-androidwebview.md b/docs/src/mobile-api/class-androidwebview.mdsimilarity index 100%rename from docs/src/api/class-androidwebview.mdrename to docs/src/mobile-api/class-androidwebview.mddiff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.tsindex bf34b0dabd..4a33756068 100644--- a/packages/playwright-client/types/types.d.ts+++ b/packages/playwright-client/types/types.d.ts@@ -17140,1180 +17140,1101 @@ export {};/**- * Playwright has **experimental** support for Android automation. This includes Chrome for Android and Android- * WebView.- *- * *Requirements*- * - Android device or AVD Emulator.- * - [ADB daemon](https://developer.android.com/studio/command-line/adb) running and authenticated with your device.- * Typically running `adb devices` is all you need to do.- * - [`Chrome 87`](https://play.google.com/store/apps/details?id=com.android.chrome) or newer installed on the- * device- * - "Enable command line on non-rooted devices" enabled in `chrome://flags`.- *- * *Known limitations*- * - Raw USB operation is not yet supported, so you need ADB.- * - Device needs to be awake to produce screenshots. Enabling "Stay awake" developer mode will help.- * - We didn't run all the tests against the device, so not everything works.- *- * *How to run*- *- * An example of the Android automation script would be:- *- * ```js- * const { _android: android } = require('playwright');- *- * (async () => {- * // Connect to the device.- * const [device] = await android.devices();- * console.log(`Model: ${device.model()}`);- * console.log(`Serial: ${device.serial()}`);- * // Take screenshot of the whole device.- * await device.screenshot({ path: 'device.png' });- *- * {- * // --------------------- WebView ------------------------ *- * // Launch an application with WebView.- * await device.shell('am force-stop org.chromium.webview_shell');- * await device.shell('am start org.chromium.webview_shell/.WebViewBrowserActivity');- * // Get the WebView.- * const webview = await device.webView({ pkg: 'org.chromium.webview_shell' });- *- * // Fill the input box.- * await device.fill({- * res: 'org.chromium.webview_shell:id/url_field',- * }, 'github.com/microsoft/playwright');- * await device.press({- * res: 'org.chromium.webview_shell:id/url_field',- * }, 'Enter');- *- * // Work with WebView's page as usual.- * const page = await webview.page();- * await page.waitForNavigation({ url: /.*microsoft\/playwright.*\/ });- * console.log(await page.title());- * }- *- * {- * // --------------------- Browser ------------------------ *- * // Launch Chrome browser.- * await device.shell('am force-stop com.android.chrome');- * const context = await device.launchBrowser();- *- * // Use BrowserContext as usual.- * const page = await context.newPage();- * await page.goto('https://webkit.org/');- * console.log(await page.evaluate(() => window.location.href));- * await page.screenshot({ path: 'page.png' });- *- * await context.close();- * }- *- * // Close the device.- * await device.close();- * })();- * ```- *+ * Exposes API that can be used for the Web API testing. This class is used for creating+ * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) instance which in turn can be used for+ * sending web requests. An instance of this class can be obtained via+ * [playwright.request](https://playwright.dev/docs/api/class-playwright#playwright-request). For more information see+ * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext).*/-export interface Android {+export interface APIRequest {/**- * This methods attaches Playwright to an existing Android device. Use- * [android.launchServer([options])](https://playwright.dev/docs/api/class-android#android-launch-server) to launch a- * new Android server instance.- * @param endpoint A browser websocket endpoint to connect to.+ * Creates new instances of [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext).* @param options*/- connect(endpoint: string, options?: {+ newContext(options?: {/**- * Additional HTTP headers to be sent with web socket connect request. Optional.+ * Methods like+ * [apiRequestContext.get(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-get)+ * take the base URL into consideration by using the+ * [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL.+ * Examples:+ * - baseURL: `http://localhost:3000` and sending request to `/bar.html` results in `http://localhost:3000/bar.html`+ * - baseURL: `http://localhost:3000/foo/` and sending request to `./bar.html` results in+ * `http://localhost:3000/foo/bar.html`+ * - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in+ * `http://localhost:3000/bar.html`*/- headers?: { [key: string]: string; };+ baseURL?: string;/**- * Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going- * on. Defaults to `0`.+ * TLS Client Authentication allows the server to request a client certificate and verify it.+ *+ * **Details**+ *+ * An array of client certificates to be used. Each certificate object must have either both `certPath` and `keyPath`,+ * a single `pfxPath`, or their corresponding direct value equivalents (`cert` and `key`, or `pfx`). Optionally,+ * `passphrase` property should be provided if the certificate is encrypted. The `origin` property should be provided+ * with an exact match to the request origin that the certificate is valid for.+ *+ * Client certificate authentication is only active when at least one client certificate is provided. If you want to+ * reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that+ * does not match any of the domains you plan to visit.+ *+ * **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it+ * work by replacing `localhost` with `local.playwright`.+ **/- slowMo?: number;+ clientCertificates?: Array<{+ /**+ * Exact origin that the certificate is valid for. Origin includes `https` protocol, a hostname and optionally a port.+ */+ origin: string;- /**- * Maximum time in milliseconds to wait for the connection to be established. Defaults to `30000` (30 seconds). Pass- * `0` to disable timeout.- */- timeout?: number;- }): Promise<AndroidDevice>;+ /**+ * Path to the file with the certificate in PEM format.+ */+ certPath?: string;- /**- * Returns the list of detected Android devices.- * @param options- */- devices(options?: {- /**- * Optional host to establish ADB server connection. Default to `127.0.0.1`.- */- host?: string;+ /**+ * Direct value of the certificate in PEM format.+ */+ cert?: Buffer;- /**- * Prevents automatic playwright driver installation on attach. Assumes that the drivers have been installed already.- */- omitDriverInstall?: boolean;+ /**+ * Path to the file with the private key in PEM format.+ */+ keyPath?: string;- /**- * Optional port to establish ADB server connection. Default to `5037`.- */- port?: number;- }): Promise<Array<AndroidDevice>>;+ /**+ * Direct value of the private key in PEM format.+ */+ key?: Buffer;- /**- * Launches Playwright Android server that clients can connect to. See the following example:- *- * **Usage**- *- * Server Side:- *- * ```js- * const { _android } = require('playwright');- *- * (async () => {- * const browserServer = await _android.launchServer({- * // If you have multiple devices connected and want to use a specific one.- * // deviceSerialNumber: '<deviceSerialNumber>',- * });- * const wsEndpoint = browserServer.wsEndpoint();- * console.log(wsEndpoint);- * })();- * ```- *- * Client Side:- *- * ```js- * const { _android } = require('playwright');- *- * (async () => {- * const device = await _android.connect('<wsEndpoint>');- *- * console.log(device.model());- * console.log(device.serial());- * await device.shell('am force-stop com.android.chrome');- * const context = await device.launchBrowser();- *- * const page = await context.newPage();- * await page.goto('https://webkit.org/');- * console.log(await page.evaluate(() => window.location.href));- * await page.screenshot({ path: 'page-chrome-1.png' });- *- * await context.close();- * })();- * ```- *- * @param options- */- launchServer(options?: {- /**- * Optional host to establish ADB server connection. Default to `127.0.0.1`.- */- adbHost?: string;+ /**+ * Path to the PFX or PKCS12 encoded private key and certificate chain.+ */+ pfxPath?: string;- /**- * Optional port to establish ADB server connection. Default to `5037`.- */- adbPort?: number;+ /**+ * Direct value of the PFX or PKCS12 encoded private key and certificate chain.+ */+ pfx?: Buffer;- /**- * Optional device serial number to launch the browser on. If not specified, it will throw if multiple devices are- * connected.- */- deviceSerialNumber?: string;+ /**+ * Passphrase for the private key (PEM or PFX).+ */+ passphrase?: string;+ }>;/**- * Host to use for the web socket. It is optional and defaults to `localhost`, accepting connections only from the- * loopback interface. Pass an explicit address (e.g. `0.0.0.0`) to accept connections from the network — be aware- * this exposes the device RPC to anything that can reach the listening port.+ * An object containing additional HTTP headers to be sent with every request. Defaults to none.*/- host?: string;+ extraHTTPHeaders?: { [key: string]: string; };/**- * Prevents automatic playwright driver installation on attach. Assumes that the drivers have been installed already.+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status+ * codes.*/- omitDriverInstall?: boolean;+ failOnStatusCode?: boolean;/**- * Port to use for the web socket. Defaults to 0 that picks any available port.+ * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no+ * origin is specified, the username and password are sent to any servers upon unauthorized responses.*/- port?: number;+ httpCredentials?: {+ username: string;- /**- * Path at which to serve the Android Server. For security, this defaults to an unguessable string.- *- * **NOTE** Any process or web page (including those running in Playwright) with knowledge of the `wsPath` can take- * control of the OS user. For this reason, you should use an unguessable token when using this option.- *+ password: string;++ /**+ * Restrain sending http credentials on specific origin (scheme://host:port).+ */+ origin?: string;++ /**+ * This option only applies to the requests sent from corresponding+ * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) and does not affect requests sent from+ * the browser. `'always'` - `Authorization` header with basic authentication credentials will be sent with the each+ * API request. `'unauthorized` - the credentials are only sent when 401 (Unauthorized) response with+ * `WWW-Authenticate` header is received. Defaults to `'unauthorized'`.+ */+ send?: "unauthorized"|"always";+ };++ /**+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.*/- wsPath?: string;- }): Promise<BrowserServer>;+ ignoreHTTPSErrors?: boolean;- /**- * This setting will change the default maximum time for all the methods accepting- * [`timeout`](https://playwright.dev/docs/api/class-android#android-set-default-timeout-option-timeout) option.- * @param timeout Maximum time in milliseconds- */- setDefaultTimeout(timeout: number): void;-}+ /**+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects. This can be overwritten for each request+ * individually.+ */+ maxRedirects?: number;-/**- * [AndroidDevice](https://playwright.dev/docs/api/class-androiddevice) represents a connected device, either real- * hardware or emulated. Devices can be obtained using- * [android.devices([options])](https://playwright.dev/docs/api/class-android#android-devices).- */-export interface AndroidDevice {- /**- * Emitted when the device connection gets closed.- */- on(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;+ /**+ * Network proxy settings.+ */+ proxy?: {+ /**+ * Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example `http://myproxy.com:3128` or+ * `socks5://myproxy.com:3128`. Short form `myproxy.com:3128` is considered an HTTP proxy.+ */+ server: string;- /**- * Emitted when a new WebView instance is detected.- */- on(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;+ /**+ * Optional comma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.+ */+ bypass?: string;- /**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.- */- once(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;+ /**+ * Optional username to use if HTTP proxy requires authentication.+ */+ username?: string;- /**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.- */- once(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;+ /**+ * Optional password to use if HTTP proxy requires authentication.+ */+ password?: string;+ };- /**- * Emitted when the device connection gets closed.- */- addListener(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;+ /**+ * Populates context with given storage state. This option can be used to initialize context with logged-in+ * information obtained via+ * [browserContext.storageState([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-storage-state)+ * or+ * [apiRequestContext.storageState([options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-storage-state).+ * Either a path to the file with saved storage, or the value returned by one of+ * [browserContext.storageState([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-storage-state)+ * or+ * [apiRequestContext.storageState([options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-storage-state)+ * methods.+ */+ storageState?: string|{+ cookies: Array<{+ name: string;- /**- * Emitted when a new WebView instance is detected.- */- addListener(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;+ value: string;- /**- * Removes an event listener added by `on` or `addListener`.- */- removeListener(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;+ domain: string;- /**- * Removes an event listener added by `on` or `addListener`.- */- removeListener(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;+ path: string;- /**- * Removes an event listener added by `on` or `addListener`.- */- off(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;+ /**+ * Unix time in seconds.+ */+ expires: number;- /**- * Removes an event listener added by `on` or `addListener`.- */- off(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;+ httpOnly: boolean;- /**- * Emitted when the device connection gets closed.- */- prependListener(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;+ secure: boolean;- /**- * Emitted when a new WebView instance is detected.- */- prependListener(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;+ sameSite: "Strict"|"Lax"|"None";+ }>;- /**- * Disconnects from the device.- */- close(): Promise<void>;+ origins: Array<{+ origin: string;- /**- * Drags the widget defined by- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-drag-option-selector) towards- * [`dest`](https://playwright.dev/docs/api/class-androiddevice#android-device-drag-option-dest) point.- * @param selector Selector to drag.- * @param dest Point to drag to.- * @param options- */- drag(selector: AndroidSelector, dest: {- x: number;+ localStorage: Array<{+ name: string;++ value: string;+ }>;+ }>;+ };- y: number;- }, options?: {/**- * Optional speed of the drag in pixels per second.+ * Maximum time in milliseconds to wait for the response. Defaults to `30000` (30 seconds). Pass `0` to disable+ * timeout.*/- speed?: number;+ timeout?: number;/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Specific user agent to use in this context.*/- timeout?: number;- }): Promise<void>;+ userAgent?: string;+ }): Promise<APIRequestContext>;+}+/**+ * This API is used for the Web API testing. You can use it to trigger API endpoints, configure micro-services,+ * prepare environment or the service to your e2e test.+ *+ * Each Playwright browser context has an associated+ * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext), accessible via+ * [browserContext.request](https://playwright.dev/docs/api/class-browsercontext#browser-context-request) or+ * [page.request](https://playwright.dev/docs/api/class-page#page-request) (these return the+ *+ * **same instance** — `page.request` is a shortcut for `page.context().request`). You can also create a standalone,+ * isolated instance with+ * [apiRequest.newContext([options])](https://playwright.dev/docs/api/class-apirequest#api-request-new-context).+ *+ * **Cookie management**+ *+ * The [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) returned by+ * [browserContext.request](https://playwright.dev/docs/api/class-browsercontext#browser-context-request) and+ *+ * [page.request](https://playwright.dev/docs/api/class-page#page-request) uses the same cookie jar as its+ * [BrowserContext](https://playwright.dev/docs/api/class-browsercontext):+ *+ * If you want API requests that do **not** share cookies with the browser, create an isolated context via+ * [apiRequest.newContext([options])](https://playwright.dev/docs/api/class-apirequest#api-request-new-context). Such+ * `APIRequestContext` object will have its own isolated cookie storage.+ */+export interface APIRequestContext {/**- * Fills the specific- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-fill-option-selector) input box- * with [`text`](https://playwright.dev/docs/api/class-androiddevice#android-device-fill-option-text).- * @param selector Selector to fill.- * @param text Text to be filled in the input box.+ * Sends HTTP(S) [DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE) request and returns its+ * response. The method will populate request cookies from the context and update context cookies from the response.+ * The method will automatically follow redirects.+ * @param url Target URL.* @param options*/- fill(selector: AndroidSelector, text: string, options?: {+ delete(url: string, options?: {/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string+ * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`+ * header will be set to `application/octet-stream` if not explicitly set.*/- timeout?: number;- }): Promise<void>;+ data?: string|Buffer|Serializable;- /**- * Flings the widget defined by- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-fling-option-selector) in the- * specified [`direction`](https://playwright.dev/docs/api/class-androiddevice#android-device-fling-option-direction).- * @param selector Selector to fling.- * @param direction Fling direction.- * @param options- */- fling(selector: AndroidSelector, direction: "down"|"up"|"left"|"right", options?: {/**- * Optional speed of the fling in pixels per second.+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status+ * codes.*/- speed?: number;+ failOnStatusCode?: boolean;/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent+ * as this request body. If this parameter is specified `content-type` header will be set to+ * `application/x-www-form-urlencoded` unless explicitly provided.*/- timeout?: number;- }): Promise<void>;-- /**- * Returns information about a widget defined by- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-info-option-selector).- * @param selector Selector to return information about.- */- info(selector: AndroidSelector): Promise<AndroidElementInfo>;-- /**- * Installs an apk on the device.- * @param file Either a path to the apk file, or apk file content.- * @param options- */- installApk(file: string|Buffer, options?: {- /**- * Optional arguments to pass to the `shell:cmd package install` call. Defaults to `-r -t -S`.- */- args?: Array<string>;- }): Promise<void>;-- /**- * Launches Chrome browser on the device, and returns its persistent context.- * @param options- */- launchBrowser(options?: {- /**- * Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.- */- acceptDownloads?: boolean;-- /**- * **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality.- *- * Additional arguments to pass to the browser instance. The list of Chromium flags can be found- * [here](https://peter.sh/experiments/chromium-command-line-switches/).- */- args?: Array<string>;-- /**- * When using [page.goto(url[, options])](https://playwright.dev/docs/api/class-page#page-goto),- * [page.route(url, handler[, options])](https://playwright.dev/docs/api/class-page#page-route),- * [page.waitForURL(url[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-url),- * [page.waitForRequest(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-request),- * or- * [page.waitForResponse(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-response)- * it takes the base URL in consideration by using the- * [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL.- * Unset by default. Examples:- * - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`- * - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in- * `http://localhost:3000/foo/bar.html`- * - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in- * `http://localhost:3000/bar.html`- */- baseURL?: string;-- /**- * Toggles bypassing page's Content-Security-Policy. Defaults to `false`.- */- bypassCSP?: boolean;+ form?: { [key: string]: string|number|boolean; }|FormData;/**- * Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)- * media feature, supported values are `'light'` and `'dark'`. See- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.- * Passing `null` resets emulation to system defaults. Defaults to `'light'`.+ * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by+ * it.*/- colorScheme?: null|"light"|"dark"|"no-preference";+ headers?: { [key: string]: string; };/**- * Emulates `'prefers-contrast'` media feature, supported values are `'no-preference'`, `'more'`. See- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.- * Passing `null` resets emulation to system defaults. Defaults to `'no-preference'`.+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.*/- contrast?: null|"no-preference"|"more";+ ignoreHTTPSErrors?: boolean;/**- * Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about- * [emulating devices with device scale factor](https://playwright.dev/docs/emulation#devices).+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.*/- deviceScaleFactor?: number;+ maxRedirects?: number;/**- * An object containing additional HTTP headers to be sent with every request. Defaults to none.+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.*/- extraHTTPHeaders?: { [key: string]: string; };+ maxRetries?: number;/**- * Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.- * Passing `null` resets emulation to system defaults. Defaults to `'none'`.+ * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this+ * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless+ * explicitly provided. File values can be passed either as+ * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file+ * name, mime-type and its content.*/- forcedColors?: null|"active"|"none";-- geolocation?: {+ multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{/**- * Latitude between -90 and 90.+ * File name*/- latitude: number;+ name: string;/**- * Longitude between -180 and 180.+ * File type*/- longitude: number;+ mimeType: string;/**- * Non-negative accuracy value. Defaults to `0`.+ * File content*/- accuracy?: number;- };+ buffer: Buffer;+ }; };/**- * Specifies if viewport supports touch events. Defaults to false. Learn more about- * [mobile emulation](https://playwright.dev/docs/emulation#devices).+ * Query parameters to be sent with the URL.*/- hasTouch?: boolean;+ params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;/**- * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no- * origin is specified, the username and password are sent to any servers upon unauthorized responses.+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.*/- httpCredentials?: {- username: string;-- password: string;-- /**- * Restrain sending http credentials on specific origin (scheme://host:port).- */- origin?: string;+ timeout?: number;+ }): Promise<APIResponse>;- /**- * This option only applies to the requests sent from corresponding- * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) and does not affect requests sent from- * the browser. `'always'` - `Authorization` header with basic authentication credentials will be sent with the each- * API request. `'unauthorized` - the credentials are only sent when 401 (Unauthorized) response with- * `WWW-Authenticate` header is received. Defaults to `'unauthorized'`.- */- send?: "unauthorized"|"always";- };+ /**+ * All responses returned by+ * [apiRequestContext.get(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-get)+ * and similar methods are stored in the memory, so that you can later call+ * [apiResponse.body()](https://playwright.dev/docs/api/class-apiresponse#api-response-body).This method discards all+ * its resources, calling any method on disposed+ * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) will throw an exception.+ * @param options+ */+ dispose(options?: {+ /**+ * The reason to be reported to the operations interrupted by the context disposal.+ */+ reason?: string;+ }): Promise<void>;+ /**+ * Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and+ * update context cookies from the response. The method will automatically follow redirects.+ *+ * **Usage**+ *+ * JSON objects can be passed directly to the request:+ *+ * ```js+ * await request.fetch('https://example.com/api/createBook', {+ * method: 'post',+ * data: {+ * title: 'Book Title',+ * author: 'John Doe',+ * }+ * });+ * ```+ *+ * The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data`+ * encoding, by specifiying the `multipart` parameter:+ *+ * ```js+ * const form = new FormData();+ * form.set('name', 'John');+ * form.append('name', 'Doe');+ * // Send two file fields with the same name.+ * form.append('file', new File(['console.log(2024);'], 'f1.js', { type: 'text/javascript' }));+ * form.append('file', new File(['hello'], 'f2.txt', { type: 'text/plain' }));+ * await request.fetch('https://example.com/api/uploadForm', {+ * multipart: form+ * });+ * ```+ *+ * @param urlOrRequest Target URL or Request to get all parameters from.+ * @param options+ */+ fetch(urlOrRequest: string|Request, options?: {/**- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.+ * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string+ * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`+ * header will be set to `application/octet-stream` if not explicitly set.*/- ignoreHTTPSErrors?: boolean;+ data?: string|Buffer|Serializable;/**- * Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,- * so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more- * about [mobile emulation](https://playwright.dev/docs/emulation#ismobile).+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status+ * codes.*/- isMobile?: boolean;+ failOnStatusCode?: boolean;/**- * Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about- * [disabling JavaScript](https://playwright.dev/docs/emulation#javascript-enabled).+ * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent+ * as this request body. If this parameter is specified `content-type` header will be set to+ * `application/x-www-form-urlencoded` unless explicitly provided.*/- javaScriptEnabled?: boolean;+ form?: { [key: string]: string|number|boolean; }|FormData;/**- * Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value,- * `Accept-Language` request header value as well as number and date formatting rules. Defaults to the system default- * locale. Learn more about emulation in our [emulation guide](https://playwright.dev/docs/emulation#locale--timezone).+ * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by+ * it.*/- locale?: string;+ headers?: { [key: string]: string; };/**- * Logger sink for Playwright logging.- * @deprecated The logs received by the logger are incomplete. Please use tracing instead.+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.*/- logger?: Logger;+ ignoreHTTPSErrors?: boolean;/**- * Whether to emulate network being offline. Defaults to `false`. Learn more about- * [network emulation](https://playwright.dev/docs/emulation#offline).+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.*/- offline?: boolean;+ maxRedirects?: number;/**- * A list of permissions to grant to all pages in this context. See- * [browserContext.grantPermissions(permissions[, options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-grant-permissions)- * for more details. Defaults to none.+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.*/- permissions?: Array<string>;+ maxRetries?: number;/**- * Optional package name to launch instead of default Chrome for Android.+ * If set changes the fetch method (e.g. [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) or+ * [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)). If not specified, GET method is used.*/- pkg?: string;+ method?: string;/**- * Network proxy settings.+ * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this+ * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless+ * explicitly provided. File values can be passed either as+ * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file+ * name, mime-type and its content.*/- proxy?: {+ multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{/**- * Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example `http://myproxy.com:3128` or- * `socks5://myproxy.com:3128`. Short form `myproxy.com:3128` is considered an HTTP proxy.+ * File name*/- server: string;+ name: string;/**- * Optional comma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.+ * File type*/- bypass?: string;+ mimeType: string;/**- * Optional username to use if HTTP proxy requires authentication.+ * File content*/- username?: string;+ buffer: Buffer;+ }; };- /**- * Optional password to use if HTTP proxy requires authentication.- */- password?: string;- };+ /**+ * Query parameters to be sent with the URL.+ */+ params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;/**- * Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into `recordHar.path` file.- * If not specified, the HAR is not recorded. Make sure to await- * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for- * the HAR to be saved.+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.*/- recordHar?: {- /**- * Optional setting to control whether to omit request content from the HAR. Defaults to `false`. Deprecated, use- * `content` policy instead.- */- omitContent?: boolean;+ timeout?: number;+ }): Promise<APIResponse>;- /**- * Optional setting to control resource content management. If `omit` is specified, content is not persisted. If- * `attach` is specified, resources are persisted as separate files or entries in the ZIP archive. If `embed` is- * specified, content is stored inline the HAR file as per HAR specification. Defaults to `attach` for `.zip` output- * files and to `embed` for all other file extensions.- */- content?: "omit"|"embed"|"attach";+ /**+ * Sends HTTP(S) [GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET) request and returns its+ * response. The method will populate request cookies from the context and update context cookies from the response.+ * The method will automatically follow redirects.+ *+ * **Usage**+ *+ * Request parameters can be configured with `params` option, they will be serialized into the URL search parameters:+ *+ * ```js+ * // Passing params as object+ * await request.get('https://example.com/api/getText', {+ * params: {+ * 'isbn': '1234',+ * 'page': 23,+ * }+ * });+ *+ * // Passing params as URLSearchParams+ * const searchParams = new URLSearchParams();+ * searchParams.set('isbn', '1234');+ * searchParams.append('page', 23);+ * searchParams.append('page', 24);+ * await request.get('https://example.com/api/getText', { params: searchParams });+ *+ * // Passing params as string+ * const queryString = 'isbn=1234&page=23&page=24';+ * await request.get('https://example.com/api/getText', { params: queryString });+ * ```+ *+ * @param url Target URL.+ * @param options+ */+ get(url: string, options?: {+ /**+ * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string+ * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`+ * header will be set to `application/octet-stream` if not explicitly set.+ */+ data?: string|Buffer|Serializable;- /**- * Path on the filesystem to write the HAR file to. If the file name ends with `.zip`, `content: 'attach'` is used by- * default.- */- path: string;+ /**+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status+ * codes.+ */+ failOnStatusCode?: boolean;- /**- * When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,- * cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.- */- mode?: "full"|"minimal";+ /**+ * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent+ * as this request body. If this parameter is specified `content-type` header will be set to+ * `application/x-www-form-urlencoded` unless explicitly provided.+ */+ form?: { [key: string]: string|number|boolean; }|FormData;- /**- * A glob or regex pattern to filter requests that are stored in the HAR. When a- * [`baseURL`](https://playwright.dev/docs/api/class-browser#browser-new-context-option-base-url) via the context- * options was provided and the passed URL is a path, it gets merged via the- * [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor. Defaults to none.- */- urlFilter?: string|RegExp;- };+ /**+ * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by+ * it.+ */+ headers?: { [key: string]: string; };/**- * Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded.- * Make sure to await- * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for- * videos to be saved.+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.*/- recordVideo?: {+ ignoreHTTPSErrors?: boolean;++ /**+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.+ */+ maxRedirects?: number;++ /**+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.+ */+ maxRetries?: number;++ /**+ * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this+ * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless+ * explicitly provided. File values can be passed either as+ * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file+ * name, mime-type and its content.+ */+ multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{/**- * Path to the directory to put videos into. If not specified, the videos will be stored in `artifactsDir` (see- * [browserType.launch([options])](https://playwright.dev/docs/api/class-browsertype#browser-type-launch) options).+ * File name*/- dir?: string;+ name: string;/**- * Optional dimensions of the recorded videos. If not specified the size will be equal to `viewport` scaled down to- * fit into 800x800. If `viewport` is not configured explicitly the video size defaults to 800x450. Actual picture of- * each page will be scaled down if necessary to fit the specified size.+ * File type*/- size?: {- /**- * Video frame width.- */- width: number;-- /**- * Video frame height.- */- height: number;- };+ mimeType: string;/**- * If specified, enables visual annotations on interacted elements during video recording.+ * File content*/- showActions?: {- /**- * How long each annotation is displayed in milliseconds. Defaults to `500`.- */- duration?: number;-- /**- * Position of the action title overlay. Defaults to `"top-right"`.- */- position?: "top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right";-- /**- * Font size of the action title in pixels. Defaults to `24`.- */- fontSize?: number;- };- };+ buffer: Buffer;+ }; };/**- * Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.- * Passing `null` resets emulation to system defaults. Defaults to `'no-preference'`.+ * Query parameters to be sent with the URL.*/- reducedMotion?: null|"reduce"|"no-preference";+ params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;/**- * Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the- * [`viewport`](https://playwright.dev/docs/api/class-androiddevice#android-device-launch-browser-option-viewport) is- * set.+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.*/- screen?: {- /**- * page width in pixels.- */- width: number;+ timeout?: number;+ }): Promise<APIResponse>;- /**- * page height in pixels.- */- height: number;- };+ /**+ * Sends HTTP(S) [HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD) request and returns its+ * response. The method will populate request cookies from the context and update context cookies from the response.+ * The method will automatically follow redirects.+ * @param url Target URL.+ * @param options+ */+ head(url: string, options?: {+ /**+ * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string+ * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`+ * header will be set to `application/octet-stream` if not explicitly set.+ */+ data?: string|Buffer|Serializable;/**- * Whether to allow sites to register Service workers. Defaults to `'allow'`.- * - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be- * registered.- * - `'block'`: Playwright will block all registration of Service Workers.+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status+ * codes.*/- serviceWorkers?: "allow"|"block";+ failOnStatusCode?: boolean;/**- * If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on- * selectors that imply single target DOM element will throw when more than one element matches the selector. This- * option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See- * [Locator](https://playwright.dev/docs/api/class-locator) to learn more about the strict mode.+ * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent+ * as this request body. If this parameter is specified `content-type` header will be set to+ * `application/x-www-form-urlencoded` unless explicitly provided.*/- strictSelectors?: boolean;+ form?: { [key: string]: string|number|boolean; }|FormData;/**- * Changes the timezone of the context. See- * [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)- * for a list of supported timezone IDs. Defaults to the system timezone.+ * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by+ * it.*/- timezoneId?: string;+ headers?: { [key: string]: string; };/**- * Specific user agent to use in this context.+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.*/- userAgent?: string;+ ignoreHTTPSErrors?: boolean;/**- * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use `null` to disable the consistent- * viewport emulation. Learn more about [viewport emulation](https://playwright.dev/docs/emulation#viewport).- *- * **NOTE** The `null` value opts out from the default presets, makes viewport depend on the host window size defined- * by the operating system. It makes the execution of the tests non-deterministic.- *+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.*/- viewport?: null|{- /**- * page width in pixels.- */- width: number;+ maxRedirects?: number;- /**- * page height in pixels.- */- height: number;- };- }): Promise<BrowserContext>;+ /**+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.+ */+ maxRetries?: number;- /**- * Performs a long tap on the widget defined by- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-long-tap-option-selector).- * @param selector Selector to tap on.- * @param options- */- longTap(selector: AndroidSelector, options?: {/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this+ * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless+ * explicitly provided. File values can be passed either as+ * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file+ * name, mime-type and its content.*/- timeout?: number;- }): Promise<void>;+ multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{+ /**+ * File name+ */+ name: string;- /**- * Device model.- */- model(): string;+ /**+ * File type+ */+ mimeType: string;- /**- * Launches a process in the shell on the device and returns a socket to communicate with the launched process.- * @param command Shell command to execute.- */- open(command: string): Promise<AndroidSocket>;+ /**+ * File content+ */+ buffer: Buffer;+ }; };- /**- * Pinches the widget defined by- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-pinch-close-option-selector) in the- * closing direction.- * @param selector Selector to pinch close.- * @param percent The size of the pinch as a percentage of the widget's size.- * @param options- */- pinchClose(selector: AndroidSelector, percent: number, options?: {/**- * Optional speed of the pinch in pixels per second.+ * Query parameters to be sent with the URL.*/- speed?: number;+ params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.*/timeout?: number;- }): Promise<void>;+ }): Promise<APIResponse>;/**- * Pinches the widget defined by- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-pinch-open-option-selector) in the- * open direction.- * @param selector Selector to pinch open.- * @param percent The size of the pinch as a percentage of the widget's size.+ * Sends HTTP(S) [PATCH](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) request and returns its+ * response. The method will populate request cookies from the context and update context cookies from the response.+ * The method will automatically follow redirects.+ * @param url Target URL.* @param options*/- pinchOpen(selector: AndroidSelector, percent: number, options?: {+ patch(url: string, options?: {/**- * Optional speed of the pinch in pixels per second.+ * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string+ * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`+ * header will be set to `application/octet-stream` if not explicitly set.*/- speed?: number;+ data?: string|Buffer|Serializable;/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status+ * codes.*/- timeout?: number;- }): Promise<void>;+ failOnStatusCode?: boolean;- /**- * Presses the specific [`key`](https://playwright.dev/docs/api/class-androiddevice#android-device-press-option-key)- * in the widget defined by- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-press-option-selector).- * @param selector Selector to press the key in.- * @param key The key to press.- * @param options- */- press(selector: AndroidSelector, key: AndroidKey, options?: {/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent+ * as this request body. If this parameter is specified `content-type` header will be set to+ * `application/x-www-form-urlencoded` unless explicitly provided.*/- timeout?: number;- }): Promise<void>;+ form?: { [key: string]: string|number|boolean; }|FormData;- /**- * Copies a file to the device.- * @param file Either a path to the file, or file content.- * @param path Path to the file on the device.- * @param options- */- push(file: string|Buffer, path: string, options?: {/**- * Optional file mode, defaults to `644` (`rw-r--r--`).+ * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by+ * it.*/- mode?: number;- }): Promise<void>;+ headers?: { [key: string]: string; };- /**- * Returns the buffer with the captured screenshot of the device.- * @param options- */- screenshot(options?: {/**- * The file path to save the image to. If- * [`path`](https://playwright.dev/docs/api/class-androiddevice#android-device-screenshot-option-path) is a relative- * path, then it is resolved relative to the current working directory. If no path is provided, the image won't be- * saved to the disk.+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.*/- path?: string;- }): Promise<Buffer>;+ ignoreHTTPSErrors?: boolean;- /**- * Scrolls the widget defined by- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-scroll-option-selector) in the- * specified- * [`direction`](https://playwright.dev/docs/api/class-androiddevice#android-device-scroll-option-direction).- * @param selector Selector to scroll.- * @param direction Scroll direction.- * @param percent Distance to scroll as a percentage of the widget's size.- * @param options- */- scroll(selector: AndroidSelector, direction: "down"|"up"|"left"|"right", percent: number, options?: {/**- * Optional speed of the scroll in pixels per second.+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.*/- speed?: number;+ maxRedirects?: number;/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.*/- timeout?: number;- }): Promise<void>;-- /**- * Device serial number.- */- serial(): string;-- /**- * This setting will change the default maximum time for all the methods accepting- * [`timeout`](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout-option-timeout)- * option.- * @param timeout Maximum time in milliseconds- */- setDefaultTimeout(timeout: number): void;-- /**- * Executes a shell command on the device and returns its output.- * @param command Shell command to execute.- */- shell(command: string): Promise<Buffer>;+ maxRetries?: number;- /**- * Swipes the widget defined by- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-swipe-option-selector) in the- * specified [`direction`](https://playwright.dev/docs/api/class-androiddevice#android-device-swipe-option-direction).- * @param selector Selector to swipe.- * @param direction Swipe direction.- * @param percent Distance to swipe as a percentage of the widget's size.- * @param options- */- swipe(selector: AndroidSelector, direction: "down"|"up"|"left"|"right", percent: number, options?: {/**- * Optional speed of the swipe in pixels per second.+ * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this+ * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless+ * explicitly provided. File values can be passed either as+ * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file+ * name, mime-type and its content.*/- speed?: number;+ multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{+ /**+ * File name+ */+ name: string;- /**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.- */- timeout?: number;- }): Promise<void>;+ /**+ * File type+ */+ mimeType: string;++ /**+ * File content+ */+ buffer: Buffer;+ }; };- /**- * Taps on the widget defined by- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-tap-option-selector).- * @param selector Selector to tap on.- * @param options- */- tap(selector: AndroidSelector, options?: {/**- * Optional duration of the tap in milliseconds.+ * Query parameters to be sent with the URL.*/- duration?: number;+ params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.*/timeout?: number;- }): Promise<void>;+ }): Promise<APIResponse>;/**- * Waits for the specific- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-wait-option-selector) to either- * appear or disappear, depending on the- * [`state`](https://playwright.dev/docs/api/class-androiddevice#android-device-wait-option-state).- * @param selector Selector to wait for.- * @param options- */- wait(selector: AndroidSelector, options?: {- /**- * Optional state. Can be either:- * - default - wait for element to be present.- * - `'gone'` - wait for element to not be present.- */- state?: "gone";+ * Sends HTTP(S) [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) request and returns its+ * response. The method will populate request cookies from the context and update context cookies from the response.+ * The method will automatically follow redirects.+ *+ * **Usage**+ *+ * JSON objects can be passed directly to the request:+ *+ * ```js+ * await request.post('https://example.com/api/createBook', {+ * data: {+ * title: 'Book Title',+ * author: 'John Doe',+ * }+ * });+ * ```+ *+ * To send form data to the server use `form` option. Its value will be encoded into the request body with+ * `application/x-www-form-urlencoded` encoding (see below how to use `multipart/form-data` form encoding to send+ * files):+ *+ * ```js+ * await request.post('https://example.com/api/findBook', {+ * form: {+ * title: 'Book Title',+ * author: 'John Doe',+ * }+ * });+ * ```+ *+ * The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data`+ * encoding. Use [FormData] to construct request body and pass it to the request as `multipart` parameter:+ *+ * ```js+ * const form = new FormData();+ * form.set('name', 'John');+ * form.append('name', 'Doe');+ * // Send two file fields with the same name.+ * form.append('file', new File(['console.log(2024);'], 'f1.js', { type: 'text/javascript' }));+ * form.append('file', new File(['hello'], 'f2.txt', { type: 'text/plain' }));+ * await request.post('https://example.com/api/uploadForm', {+ * multipart: form+ * });+ * ```+ *+ * @param url Target URL.+ * @param options+ */+ post(url: string, options?: {+ /**+ * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string+ * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`+ * header will be set to `application/octet-stream` if not explicitly set.+ */+ data?: string|Buffer|Serializable;/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status+ * codes.*/- timeout?: number;- }): Promise<void>;+ failOnStatusCode?: boolean;- /**- * Emitted when the device connection gets closed.- */- waitForEvent(event: 'close', optionsOrPredicate?: { predicate?: (androidDevice: AndroidDevice) => boolean | Promise<boolean>, timeout?: number } | ((androidDevice: AndroidDevice) => boolean | Promise<boolean>)): Promise<AndroidDevice>;+ /**+ * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent+ * as this request body. If this parameter is specified `content-type` header will be set to+ * `application/x-www-form-urlencoded` unless explicitly provided.+ */+ form?: { [key: string]: string|number|boolean; }|FormData;- /**- * Emitted when a new WebView instance is detected.- */- waitForEvent(event: 'webview', optionsOrPredicate?: { predicate?: (androidWebView: AndroidWebView) => boolean | Promise<boolean>, timeout?: number } | ((androidWebView: AndroidWebView) => boolean | Promise<boolean>)): Promise<AndroidWebView>;+ /**+ * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by+ * it.+ */+ headers?: { [key: string]: string; };+ /**+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.+ */+ ignoreHTTPSErrors?: boolean;- /**- * This method waits until [AndroidWebView](https://playwright.dev/docs/api/class-androidwebview) matching the- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-web-view-option-selector) is opened- * and returns it. If there is already an open [AndroidWebView](https://playwright.dev/docs/api/class-androidwebview)- * matching the- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-web-view-option-selector), returns- * immediately.- * @param selector- * @param options- */- webView(selector: {/**- * Optional Package identifier.+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.*/- pkg?: string;+ maxRedirects?: number;/**- * Optional webview socket name.+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.*/- socketName?: string;- }, options?: {+ maxRetries?: number;+/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this+ * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless+ * explicitly provided. File values can be passed either as+ * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file+ * name, mime-type and its content.*/- timeout?: number;- }): Promise<AndroidWebView>;+ multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{+ /**+ * File name+ */+ name: string;- /**- * Currently open WebViews.- */- webViews(): Array<AndroidWebView>;+ /**+ * File type+ */+ mimeType: string;- input: AndroidInput;+ /**+ * File content+ */+ buffer: Buffer;+ }; };- [Symbol.asyncDispose](): Promise<void>;-}+ /**+ * Query parameters to be sent with the URL.+ */+ params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;++ /**+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.+ */+ timeout?: number;+ }): Promise<APIResponse>;-export interface AndroidInput {/**- * Performs a drag between [`from`](https://playwright.dev/docs/api/class-androidinput#android-input-drag-option-from)- * and [`to`](https://playwright.dev/docs/api/class-androidinput#android-input-drag-option-to) points.- * @param from The start point of the drag.- * @param to The end point of the drag.- * @param steps The number of steps in the drag. Each step takes 5 milliseconds to complete.+ * Sends HTTP(S) [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) request and returns its+ * response. The method will populate request cookies from the context and update context cookies from the response.+ * The method will automatically follow redirects.+ * @param url Target URL.+ * @param options*/- drag(from: {- x: number;+ put(url: string, options?: {+ /**+ * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string+ * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`+ * header will be set to `application/octet-stream` if not explicitly set.+ */+ data?: string|Buffer|Serializable;- y: number;- }, to: {- x: number;+ /**+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status+ * codes.+ */+ failOnStatusCode?: boolean;- y: number;- }, steps: number): Promise<void>;+ /**+ * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent+ * as this request body. If this parameter is specified `content-type` header will be set to+ * `application/x-www-form-urlencoded` unless explicitly provided.+ */+ form?: { [key: string]: string|number|boolean; }|FormData;- /**- * Presses the [`key`](https://playwright.dev/docs/api/class-androidinput#android-input-press-option-key).- * @param key Key to press.- */- press(key: AndroidKey): Promise<void>;+ /**+ * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by+ * it.+ */+ headers?: { [key: string]: string; };- /**- * Swipes following the path defined by- * [`segments`](https://playwright.dev/docs/api/class-androidinput#android-input-swipe-option-segments).- * @param from The point to start swiping from.- * @param segments Points following the [`from`](https://playwright.dev/docs/api/class-androidinput#android-input-swipe-option-from)- * point in the swipe gesture.- * @param steps The number of steps for each segment. Each step takes 5 milliseconds to complete, so 100 steps means half a second- * per each segment.- */- swipe(from: {- x: number;+ /**+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.+ */+ ignoreHTTPSErrors?: boolean;- y: number;- }, segments: ReadonlyArray<{- x: number;+ /**+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.+ */+ maxRedirects?: number;- y: number;- }>, steps: number): Promise<void>;+ /**+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.+ */+ maxRetries?: number;- /**- * Taps at the specified [`point`](https://playwright.dev/docs/api/class-androidinput#android-input-tap-option-point).- * @param point The point to tap at.- */- tap(point: {- x: number;+ /**+ * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this+ * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless+ * explicitly provided. File values can be passed either as+ * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file+ * name, mime-type and its content.+ */+ multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{+ /**+ * File name+ */+ name: string;- y: number;- }): Promise<void>;+ /**+ * File type+ */+ mimeType: string;- /**- * Types [`text`](https://playwright.dev/docs/api/class-androidinput#android-input-type-option-text) into currently- * focused widget.- * @param text Text to type.- */- type(text: string): Promise<void>;-}+ /**+ * File content+ */+ buffer: Buffer;+ }; };-/**- * [AndroidSocket](https://playwright.dev/docs/api/class-androidsocket) is a way to communicate with a process- * launched on the [AndroidDevice](https://playwright.dev/docs/api/class-androiddevice). Use- * [androidDevice.open(command)](https://playwright.dev/docs/api/class-androiddevice#android-device-open) to open a- * socket.- */-export interface AndroidSocket {- /**- * Emitted when the socket is closed.- */- on(event: 'close', listener: () => any): this;+ /**+ * Query parameters to be sent with the URL.+ */+ params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;- /**- * Emitted when data is available to read from the socket.- */- on(event: 'data', listener: (buffer: Buffer) => any): this;+ /**+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.+ */+ timeout?: number;+ }): Promise<APIResponse>;/**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ * Returns storage state for this request context, contains current cookies and local storage snapshot if it was+ * passed to the constructor.+ * @param options*/- once(event: 'close', listener: () => any): this;+ storageState(options?: {+ /**+ * Set to `true` to include IndexedDB in the storage state snapshot.+ */+ indexedDB?: boolean;- /**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.- */- once(event: 'data', listener: (buffer: Buffer) => any): this;+ /**+ * The file path to save the storage state to. If+ * [`path`](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-storage-state-option-path) is+ * a relative path, then it is resolved relative to current working directory. If no path is provided, storage state+ * is still returned, but won't be saved to the disk.+ */+ path?: string;+ }): Promise<{+ cookies: Array<{+ name: string;++ value: string;++ domain: string;++ path: string;++ /**+ * Unix time in seconds.+ */+ expires: number;++ httpOnly: boolean;++ secure: boolean;++ sameSite: "Strict"|"Lax"|"None";+ }>;++ origins: Array<{+ origin: string;++ localStorage: Array<{+ name: string;++ value: string;+ }>;+ }>;+ }>;++ tracing: Tracing;+ [Symbol.asyncDispose](): Promise<void>;+}++/**+ * [APIResponse](https://playwright.dev/docs/api/class-apiresponse) class represents responses returned by+ * [apiRequestContext.get(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-get)+ * and similar methods.+ */+export interface APIResponse {/**- * Emitted when the socket is closed.+ * Returns the buffer with response body.*/- addListener(event: 'close', listener: () => any): this;+ body(): Promise<Buffer>;/**- * Emitted when data is available to read from the socket.+ * Disposes the body of this response. If not called then the body will stay in memory until the context closes.*/- addListener(event: 'data', listener: (buffer: Buffer) => any): this;+ dispose(): Promise<void>;/**- * Removes an event listener added by `on` or `addListener`.+ * An object with all the response HTTP headers associated with this response.*/- removeListener(event: 'close', listener: () => any): this;+ headers(): { [key: string]: string; };/**- * Removes an event listener added by `on` or `addListener`.+ * An array with all the response HTTP headers associated with this response. Header names are not lower-cased.+ * Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple times.*/- removeListener(event: 'data', listener: (buffer: Buffer) => any): this;+ headersArray(): Array<{+ /**+ * Name of the header.+ */+ name: string;++ /**+ * Value of the header.+ */+ value: string;+ }>;/**- * Removes an event listener added by `on` or `addListener`.+ * Returns the JSON representation of response body.+ *+ * This method will throw if the response body is not parsable via `JSON.parse`.*/- off(event: 'close', listener: () => any): this;+ json(): Promise<Serializable>;/**- * Removes an event listener added by `on` or `addListener`.+ * Contains a boolean stating whether the response was successful (status in the range 200-299) or not.*/- off(event: 'data', listener: (buffer: Buffer) => any): this;+ ok(): boolean;/**- * Emitted when the socket is closed.+ * Contains the status code of the response (e.g., 200 for a success).*/- prependListener(event: 'close', listener: () => any): this;+ status(): number;/**- * Emitted when data is available to read from the socket.+ * Contains the status text of the response (e.g. usually an "OK" for a success).*/- prependListener(event: 'data', listener: (buffer: Buffer) => any): this;+ statusText(): string;/**- * Closes the socket.+ * Returns the text representation of response body.*/- close(): Promise<void>;+ text(): Promise<string>;/**- * Writes some [`data`](https://playwright.dev/docs/api/class-androidsocket#android-socket-write-option-data) to the- * socket.- * @param data Data to write.+ * Contains the URL of the response.*/- write(data: Buffer): Promise<void>;+ url(): string;[Symbol.asyncDispose](): Promise<void>;}-/**- * [AndroidWebView](https://playwright.dev/docs/api/class-androidwebview) represents a WebView open on the- * [AndroidDevice](https://playwright.dev/docs/api/class-androiddevice). WebView is usually obtained using- * [androidDevice.webView(selector[, options])](https://playwright.dev/docs/api/class-androiddevice#android-device-web-view).- */-export interface AndroidWebView {+export interface BrowserServer {/**- * Emitted when the WebView is closed.+ * Emitted when the browser server closes.*/on(event: 'close', listener: () => any): this;@@ -18323,7 +18244,7 @@ export interface AndroidWebView {once(event: 'close', listener: () => any): this;/**- * Emitted when the WebView is closed.+ * Emitted when the browser server closes.*/addListener(event: 'close', listener: () => any): this;@@ -18338,4419 +18259,4498 @@ export interface AndroidWebView {off(event: 'close', listener: () => any): this;/**- * Emitted when the WebView is closed.+ * Emitted when the browser server closes.*/prependListener(event: 'close', listener: () => any): this;/**- * Connects to the WebView and returns a regular Playwright [Page](https://playwright.dev/docs/api/class-page) to- * interact with.+ * Closes the browser gracefully and makes sure the process is terminated.*/- page(): Promise<Page>;+ close(): Promise<void>;/**- * WebView process PID.+ * Kills the browser process and waits for the process to exit.*/- pid(): number;+ kill(): Promise<void>;/**- * WebView package identifier.+ * Spawned browser application process.*/- pkg(): string;+ process(): ChildProcess;++ /**+ * Browser websocket url.+ *+ * Browser websocket endpoint which can be used as an argument to+ * [browserType.connect(endpoint[, options])](https://playwright.dev/docs/api/class-browsertype#browser-type-connect)+ * to establish connection to the browser.+ */+ wsEndpoint(): string;++ [Symbol.asyncDispose](): Promise<void>;}/**- * Exposes API that can be used for the Web API testing. This class is used for creating- * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) instance which in turn can be used for- * sending web requests. An instance of this class can be obtained via- * [playwright.request](https://playwright.dev/docs/api/class-playwright#playwright-request). For more information see- * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext).+ * Accurately simulating time-dependent behavior is essential for verifying the correctness of applications. Learn+ * more about [clock emulation](https://playwright.dev/docs/clock).+ *+ * Note that clock is installed for the entire [BrowserContext](https://playwright.dev/docs/api/class-browsercontext),+ * so the time in all the pages and iframes is controlled by the same clock.*/-export interface APIRequest {+export interface Clock {/**- * Creates new instances of [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext).+ * Advance the clock by jumping forward in time. Only fires due timers at most once. This is equivalent to user+ * closing the laptop lid for a while and reopening it later, after given time.+ *+ * **Usage**+ *+ * ```js+ * await page.clock.fastForward(1000);+ * await page.clock.fastForward('30:00');+ * ```+ *+ * @param ticks Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are+ * "08" for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.+ */+ fastForward(ticks: number|string): Promise<void>;++ /**+ * Install fake implementations for the following time-related functions:+ * - `Date`+ * - `setTimeout`+ * - `clearTimeout`+ * - `setInterval`+ * - `clearInterval`+ * - `requestAnimationFrame`+ * - `cancelAnimationFrame`+ * - `requestIdleCallback`+ * - `cancelIdleCallback`+ * - `performance`+ *+ * Fake timers are used to manually control the flow of time in tests. They allow you to advance time, fire timers,+ * and control the behavior of time-dependent functions. See+ * [clock.runFor(ticks)](https://playwright.dev/docs/api/class-clock#clock-run-for) and+ * [clock.fastForward(ticks)](https://playwright.dev/docs/api/class-clock#clock-fast-forward) for more information.* @param options*/- newContext(options?: {+ install(options?: {/**- * Methods like- * [apiRequestContext.get(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-get)- * take the base URL into consideration by using the- * [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL.- * Examples:- * - baseURL: `http://localhost:3000` and sending request to `/bar.html` results in `http://localhost:3000/bar.html`- * - baseURL: `http://localhost:3000/foo/` and sending request to `./bar.html` results in- * `http://localhost:3000/foo/bar.html`- * - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in- * `http://localhost:3000/bar.html`+ * Time to initialize with, current system time by default.*/- baseURL?: string;+ time?: number|string|Date;+ }): Promise<void>;- /**- * TLS Client Authentication allows the server to request a client certificate and verify it.- *- * **Details**- *- * An array of client certificates to be used. Each certificate object must have either both `certPath` and `keyPath`,- * a single `pfxPath`, or their corresponding direct value equivalents (`cert` and `key`, or `pfx`). Optionally,- * `passphrase` property should be provided if the certificate is encrypted. The `origin` property should be provided- * with an exact match to the request origin that the certificate is valid for.- *- * Client certificate authentication is only active when at least one client certificate is provided. If you want to- * reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that- * does not match any of the domains you plan to visit.- *- * **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it- * work by replacing `localhost` with `local.playwright`.- *- */- clientCertificates?: Array<{- /**- * Exact origin that the certificate is valid for. Origin includes `https` protocol, a hostname and optionally a port.- */- origin: string;-- /**- * Path to the file with the certificate in PEM format.- */- certPath?: string;-- /**- * Direct value of the certificate in PEM format.- */- cert?: Buffer;+ /**+ * Advance the clock by jumping forward in time and pause the time. Once this method is called, no timers are fired+ * unless [clock.runFor(ticks)](https://playwright.dev/docs/api/class-clock#clock-run-for),+ * [clock.fastForward(ticks)](https://playwright.dev/docs/api/class-clock#clock-fast-forward),+ * [clock.pauseAt(time)](https://playwright.dev/docs/api/class-clock#clock-pause-at) or+ * [clock.resume()](https://playwright.dev/docs/api/class-clock#clock-resume) is called.+ *+ * Only fires due timers at most once. This is equivalent to user closing the laptop lid for a while and reopening it+ * at the specified time and pausing.+ *+ * **Usage**+ *+ * ```js+ * await page.clock.pauseAt(new Date('2020-02-02'));+ * await page.clock.pauseAt('2020-02-02');+ * ```+ *+ * For best results, install the clock before navigating the page and set it to a time slightly before the intended+ * test time. This ensures that all timers run normally during page loading, preventing the page from getting stuck.+ * Once the page has fully loaded, you can safely use+ * [clock.pauseAt(time)](https://playwright.dev/docs/api/class-clock#clock-pause-at) to pause the clock.+ *+ * ```js+ * // Initialize clock with some time before the test time and let the page load+ * // naturally. `Date.now` will progress as the timers fire.+ * await page.clock.install({ time: new Date('2024-12-10T08:00:00') });+ * await page.goto('http://localhost:3333');+ * await page.clock.pauseAt(new Date('2024-12-10T10:00:00'));+ * ```+ *+ * @param time Time to pause at.+ */+ pauseAt(time: number|string|Date): Promise<void>;- /**- * Path to the file with the private key in PEM format.- */- keyPath?: string;+ /**+ * Resumes timers. Once this method is called, time resumes flowing, timers are fired as usual.+ */+ resume(): Promise<void>;- /**- * Direct value of the private key in PEM format.- */- key?: Buffer;+ /**+ * Advance the clock, firing all the time-related callbacks.+ *+ * **Usage**+ *+ * ```js+ * await page.clock.runFor(1000);+ * await page.clock.runFor('30:00');+ * ```+ *+ * @param ticks Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are+ * "08" for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.+ */+ runFor(ticks: number|string): Promise<void>;- /**- * Path to the PFX or PKCS12 encoded private key and certificate chain.- */- pfxPath?: string;+ /**+ * Makes `Date.now` and `new Date()` return fixed fake time at all times, keeps all the timers running.+ *+ * Use this method for simple scenarios where you only need to test with a predefined time. For more advanced+ * scenarios, use [clock.install([options])](https://playwright.dev/docs/api/class-clock#clock-install) instead. Read+ * docs on [clock emulation](https://playwright.dev/docs/clock) to learn more.+ *+ * **Usage**+ *+ * ```js+ * await page.clock.setFixedTime(Date.now());+ * await page.clock.setFixedTime(new Date('2020-02-02'));+ * await page.clock.setFixedTime('2020-02-02');+ * ```+ *+ * @param time Time to be set in milliseconds.+ */+ setFixedTime(time: number|string|Date): Promise<void>;- /**- * Direct value of the PFX or PKCS12 encoded private key and certificate chain.- */- pfx?: Buffer;+ /**+ * Sets system time, but does not trigger any timers. Use this to test how the web page reacts to a time shift, for+ * example switching from summer to winter time, or changing time zones.+ *+ * **Usage**+ *+ * ```js+ * await page.clock.setSystemTime(Date.now());+ * await page.clock.setSystemTime(new Date('2020-02-02'));+ * await page.clock.setSystemTime('2020-02-02');+ * ```+ *+ * @param time Time to be set in milliseconds.+ */+ setSystemTime(time: number|string|Date): Promise<void>;+}- /**- * Passphrase for the private key (PEM or PFX).- */- passphrase?: string;- }>;+/**+ * [ConsoleMessage](https://playwright.dev/docs/api/class-consolemessage) objects are dispatched by page via the+ * [page.on('console')](https://playwright.dev/docs/api/class-page#page-event-console) event. For each console message+ * logged in the page there will be corresponding event in the Playwright context.+ *+ * ```js+ * // Listen for all console logs+ * page.on('console', msg => console.log(msg.text()));+ *+ * // Listen for all console events and handle errors+ * page.on('console', msg => {+ * if (msg.type() === 'error')+ * console.log(`Error text: "${msg.text()}"`);+ * });+ *+ * // Get the next console log+ * const msgPromise = page.waitForEvent('console');+ * await page.evaluate(() => {+ * console.log('hello', 42, { foo: 'bar' }); // Issue console.log inside the page+ * });+ * const msg = await msgPromise;+ *+ * // Deconstruct console log arguments+ * await msg.args()[0].jsonValue(); // hello+ * await msg.args()[1].jsonValue(); // 42+ * ```+ *+ */+export interface ConsoleMessage {+ /**+ * List of arguments passed to a `console` function call. See also+ * [page.on('console')](https://playwright.dev/docs/api/class-page#page-event-console).+ */+ args(): Array<JSHandle>;+ location(): {/**- * An object containing additional HTTP headers to be sent with every request. Defaults to none.+ * URL of the resource.*/- extraHTTPHeaders?: { [key: string]: string; };+ url: string;/**- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status- * codes.+ * 0-based line number in the resource.*/- failOnStatusCode?: boolean;+ line: number;/**- * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no- * origin is specified, the username and password are sent to any servers upon unauthorized responses.+ * 0-based column number in the resource.*/- httpCredentials?: {- username: string;-- password: string;-- /**- * Restrain sending http credentials on specific origin (scheme://host:port).- */- origin?: string;-- /**- * This option only applies to the requests sent from corresponding- * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) and does not affect requests sent from- * the browser. `'always'` - `Authorization` header with basic authentication credentials will be sent with the each- * API request. `'unauthorized` - the credentials are only sent when 401 (Unauthorized) response with- * `WWW-Authenticate` header is received. Defaults to `'unauthorized'`.- */- send?: "unauthorized"|"always";- };+ column: number;/**- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.+ * 0-based line number in the resource. Deprecated, use `line` instead.*/- ignoreHTTPSErrors?: boolean;+ lineNumber: number;/**- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is- * exceeded. Defaults to `20`. Pass `0` to not follow redirects. This can be overwritten for each request- * individually.+ * 0-based column number in the resource. Deprecated, use `column` instead.*/- maxRedirects?: number;+ columnNumber: number;+ };- /**- * Network proxy settings.- */- proxy?: {- /**- * Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example `http://myproxy.com:3128` or- * `socks5://myproxy.com:3128`. Short form `myproxy.com:3128` is considered an HTTP proxy.- */- server: string;+ /**+ * The page that produced this console message, if any.+ */+ page(): null|Page;- /**- * Optional comma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.- */- bypass?: string;+ /**+ * The text of the console message.+ */+ text(): string;- /**- * Optional username to use if HTTP proxy requires authentication.- */- username?: string;+ /**+ * The timestamp of the console message in milliseconds since the Unix epoch.+ */+ timestamp(): number;- /**- * Optional password to use if HTTP proxy requires authentication.- */- password?: string;- };+ type(): "log"|"debug"|"info"|"error"|"warning"|"dir"|"dirxml"|"table"|"trace"|"clear"|"startGroup"|"startGroupCollapsed"|"endGroup"|"assert"|"profile"|"profileEnd"|"count"|"time"|"timeEnd";- /**- * Populates context with given storage state. This option can be used to initialize context with logged-in- * information obtained via- * [browserContext.storageState([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-storage-state)- * or- * [apiRequestContext.storageState([options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-storage-state).- * Either a path to the file with saved storage, or the value returned by one of- * [browserContext.storageState([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-storage-state)- * or- * [apiRequestContext.storageState([options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-storage-state)- * methods.- */- storageState?: string|{- cookies: Array<{- name: string;-- value: string;-- domain: string;-- path: string;-- /**- * Unix time in seconds.- */- expires: number;-- httpOnly: boolean;-- secure: boolean;-- sameSite: "Strict"|"Lax"|"None";- }>;-- origins: Array<{- origin: string;-- localStorage: Array<{- name: string;-- value: string;- }>;- }>;- };-- /**- * Maximum time in milliseconds to wait for the response. Defaults to `30000` (30 seconds). Pass `0` to disable- * timeout.- */- timeout?: number;-- /**- * Specific user agent to use in this context.- */- userAgent?: string;- }): Promise<APIRequestContext>;+ /**+ * The web worker or service worker that produced this console message, if any. Note that console messages from web+ * workers also have non-null+ * [consoleMessage.page()](https://playwright.dev/docs/api/class-consolemessage#console-message-page).+ */+ worker(): null|Worker;}/**- * This API is used for the Web API testing. You can use it to trigger API endpoints, configure micro-services,- * prepare environment or the service to your e2e test.- *- * Each Playwright browser context has an associated- * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext), accessible via- * [browserContext.request](https://playwright.dev/docs/api/class-browsercontext#browser-context-request) or- * [page.request](https://playwright.dev/docs/api/class-page#page-request) (these return the+ * Coverage gathers information about parts of JavaScript and CSS that were used by the page.*- * **same instance** — `page.request` is a shortcut for `page.context().request`). You can also create a standalone,- * isolated instance with- * [apiRequest.newContext([options])](https://playwright.dev/docs/api/class-apirequest#api-request-new-context).+ * An example of using JavaScript coverage to produce Istanbul report for page load:*- * **Cookie management**+ * **NOTE** Coverage APIs are only supported on Chromium-based browsers.*- * The [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) returned by- * [browserContext.request](https://playwright.dev/docs/api/class-browsercontext#browser-context-request) and+ * ```js+ * const { chromium } = require('playwright');+ * const v8toIstanbul = require('v8-to-istanbul');*- * [page.request](https://playwright.dev/docs/api/class-page#page-request) uses the same cookie jar as its- * [BrowserContext](https://playwright.dev/docs/api/class-browsercontext):+ * (async () => {+ * const browser = await chromium.launch();+ * const page = await browser.newPage();+ * await page.coverage.startJSCoverage();+ * await page.goto('https://chromium.org');+ * const coverage = await page.coverage.stopJSCoverage();+ * for (const entry of coverage) {+ * const converter = v8toIstanbul('', 0, { source: entry.source });+ * await converter.load();+ * converter.applyCoverage(entry.functions);+ * console.log(JSON.stringify(converter.toIstanbul()));+ * }+ * await browser.close();+ * })();+ * ```*- * If you want API requests that do **not** share cookies with the browser, create an isolated context via- * [apiRequest.newContext([options])](https://playwright.dev/docs/api/class-apirequest#api-request-new-context). Such- * `APIRequestContext` object will have its own isolated cookie storage.*/-export interface APIRequestContext {+export interface Coverage {/**- * Sends HTTP(S) [DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE) request and returns its- * response. The method will populate request cookies from the context and update context cookies from the response.- * The method will automatically follow redirects.- * @param url Target URL.+ * Returns coverage is started* @param options*/- delete(url: string, options?: {- /**- * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string- * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`- * header will be set to `application/octet-stream` if not explicitly set.- */- data?: string|Buffer|Serializable;-- /**- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status- * codes.- */- failOnStatusCode?: boolean;-+ startCSSCoverage(options?: {/**- * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent- * as this request body. If this parameter is specified `content-type` header will be set to- * `application/x-www-form-urlencoded` unless explicitly provided.+ * Whether to reset coverage on every navigation. Defaults to `true`.*/- form?: { [key: string]: string|number|boolean; }|FormData;+ resetOnNavigation?: boolean;+ }): Promise<void>;+ /**+ * Returns coverage is started+ *+ * **NOTE** Anonymous scripts are ones that don't have an associated url. These are scripts that are dynamically+ * created on the page using `eval` or `new Function`. If+ * [`reportAnonymousScripts`](https://playwright.dev/docs/api/class-coverage#coverage-start-js-coverage-option-report-anonymous-scripts)+ * is set to `true`, anonymous scripts will have `__playwright_evaluation_script__` as their URL.+ *+ * @param options+ */+ startJSCoverage(options?: {/**- * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by- * it.+ * Whether anonymous scripts generated by the page should be reported. Defaults to `false`.*/- headers?: { [key: string]: string; };+ reportAnonymousScripts?: boolean;/**- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.+ * Whether to reset coverage on every navigation. Defaults to `true`.*/- ignoreHTTPSErrors?: boolean;+ resetOnNavigation?: boolean;+ }): Promise<void>;+ /**+ * Returns the array of coverage reports for all stylesheets+ *+ * **NOTE** CSS Coverage doesn't include dynamically injected style tags without sourceURLs.+ *+ */+ stopCSSCoverage(): Promise<Array<{/**- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.+ * StyleSheet URL*/- maxRedirects?: number;+ url: string;/**- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.+ * StyleSheet content, if available.*/- maxRetries?: number;+ text?: string;/**- * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this- * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless- * explicitly provided. File values can be passed either as- * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file- * name, mime-type and its content.+ * StyleSheet ranges that were used. Ranges are sorted and non-overlapping.*/- multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{- /**- * File name- */- name: string;-+ ranges: Array<{/**- * File type+ * A start offset in text, inclusive*/- mimeType: string;+ start: number;/**- * File content+ * An end offset in text, exclusive*/- buffer: Buffer;- }; };+ end: number;+ }>;+ }>>;+ /**+ * Returns the array of coverage reports for all scripts+ *+ * **NOTE** JavaScript Coverage doesn't include anonymous scripts by default. However, scripts with sourceURLs are+ * reported.+ *+ */+ stopJSCoverage(): Promise<Array<{/**- * Query parameters to be sent with the URL.+ * Script URL*/- params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;+ url: string;/**- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.+ * Script ID*/- timeout?: number;- }): Promise<APIResponse>;+ scriptId: string;- /**- * All responses returned by- * [apiRequestContext.get(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-get)- * and similar methods are stored in the memory, so that you can later call- * [apiResponse.body()](https://playwright.dev/docs/api/class-apiresponse#api-response-body).This method discards all- * its resources, calling any method on disposed- * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) will throw an exception.- * @param options- */- dispose(options?: {/**- * The reason to be reported to the operations interrupted by the context disposal.+ * Script content, if applicable.*/- reason?: string;- }): Promise<void>;+ source?: string;- /**- * Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and- * update context cookies from the response. The method will automatically follow redirects.- *- * **Usage**- *- * JSON objects can be passed directly to the request:- *- * ```js- * await request.fetch('https://example.com/api/createBook', {- * method: 'post',- * data: {- * title: 'Book Title',- * author: 'John Doe',- * }- * });- * ```- *- * The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data`- * encoding, by specifiying the `multipart` parameter:- *- * ```js- * const form = new FormData();- * form.set('name', 'John');- * form.append('name', 'Doe');- * // Send two file fields with the same name.- * form.append('file', new File(['console.log(2024);'], 'f1.js', { type: 'text/javascript' }));- * form.append('file', new File(['hello'], 'f2.txt', { type: 'text/plain' }));- * await request.fetch('https://example.com/api/uploadForm', {- * multipart: form- * });- * ```- *- * @param urlOrRequest Target URL or Request to get all parameters from.- * @param options- */- fetch(urlOrRequest: string|Request, options?: {/**- * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string- * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`- * header will be set to `application/octet-stream` if not explicitly set.+ * V8-specific coverage format.*/- data?: string|Buffer|Serializable;+ functions: Array<{+ functionName: string;- /**- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status- * codes.- */- failOnStatusCode?: boolean;+ isBlockCoverage: boolean;- /**- * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent- * as this request body. If this parameter is specified `content-type` header will be set to- * `application/x-www-form-urlencoded` unless explicitly provided.- */- form?: { [key: string]: string|number|boolean; }|FormData;+ ranges: Array<{+ count: number;- /**- * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by- * it.- */- headers?: { [key: string]: string; };+ startOffset: number;- /**- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.- */- ignoreHTTPSErrors?: boolean;+ endOffset: number;+ }>;+ }>;+ }>>;+}- /**- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.- */- maxRedirects?: number;+/**+ * API for controlling the Playwright debugger. The debugger allows pausing script execution and inspecting the page.+ * Obtain the debugger instance via+ * [browserContext.debugger](https://playwright.dev/docs/api/class-browsercontext#browser-context-debugger).+ */+export interface Debugger {+ /**+ * Emitted when the debugger pauses or resumes.+ */+ on(event: 'pausedstatechanged', listener: () => any): this;- /**- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.- */- maxRetries?: number;+ /**+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ */+ once(event: 'pausedstatechanged', listener: () => any): this;- /**- * If set changes the fetch method (e.g. [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) or- * [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)). If not specified, GET method is used.- */- method?: string;+ /**+ * Emitted when the debugger pauses or resumes.+ */+ addListener(event: 'pausedstatechanged', listener: () => any): this;- /**- * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this- * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless- * explicitly provided. File values can be passed either as- * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file- * name, mime-type and its content.- */- multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{- /**- * File name- */- name: string;+ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ removeListener(event: 'pausedstatechanged', listener: () => any): this;- /**- * File type- */- mimeType: string;+ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ off(event: 'pausedstatechanged', listener: () => any): this;- /**- * File content- */- buffer: Buffer;- }; };+ /**+ * Emitted when the debugger pauses or resumes.+ */+ prependListener(event: 'pausedstatechanged', listener: () => any): this;- /**- * Query parameters to be sent with the URL.- */- params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;+ /**+ * Resumes script execution and pauses again before the next action. Throws if the debugger is not paused.+ */+ next(): Promise<void>;- /**- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.- */- timeout?: number;- }): Promise<APIResponse>;+ /**+ * Returns details about the currently paused call. Returns `null` if the debugger is not paused.+ */+ pausedDetails(): null|{+ location: {+ file: string;++ line?: number;++ column?: number;+ };++ title: string;+ };/**- * Sends HTTP(S) [GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET) request and returns its- * response. The method will populate request cookies from the context and update context cookies from the response.- * The method will automatically follow redirects.- *- * **Usage**- *- * Request parameters can be configured with `params` option, they will be serialized into the URL search parameters:- *- * ```js- * // Passing params as object- * await request.get('https://example.com/api/getText', {- * params: {- * 'isbn': '1234',- * 'page': 23,- * }- * });- *- * // Passing params as URLSearchParams- * const searchParams = new URLSearchParams();- * searchParams.set('isbn', '1234');- * searchParams.append('page', 23);- * searchParams.append('page', 24);- * await request.get('https://example.com/api/getText', { params: searchParams });+ * Configures the debugger to pause before the next action is executed.*- * // Passing params as string- * const queryString = 'isbn=1234&page=23&page=24';- * await request.get('https://example.com/api/getText', { params: queryString });- * ```+ * Throws if the debugger is already paused. Use+ * [debugger.next()](https://playwright.dev/docs/api/class-debugger#debugger-next) or+ * [debugger.runTo(location)](https://playwright.dev/docs/api/class-debugger#debugger-run-to) to step while paused.*- * @param url Target URL.- * @param options+ * Note that [page.pause()](https://playwright.dev/docs/api/class-page#page-pause) is equivalent to a "debugger"+ * statement — it pauses execution at the call site immediately. On the contrary,+ * [debugger.requestPause()](https://playwright.dev/docs/api/class-debugger#debugger-request-pause) is equivalent to+ * "pause on next statement" — it configures the debugger to pause before the next action is executed.*/- get(url: string, options?: {- /**- * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string- * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`- * header will be set to `application/octet-stream` if not explicitly set.- */- data?: string|Buffer|Serializable;+ requestPause(): Promise<void>;- /**- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status- * codes.- */- failOnStatusCode?: boolean;+ /**+ * Resumes script execution. Throws if the debugger is not paused.+ */+ resume(): Promise<void>;- /**- * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent- * as this request body. If this parameter is specified `content-type` header will be set to- * `application/x-www-form-urlencoded` unless explicitly provided.- */- form?: { [key: string]: string|number|boolean; }|FormData;+ /**+ * Resumes script execution and pauses when an action originates from the given source location. Throws if the+ * debugger is not paused.+ * @param location The source location to pause at.+ */+ runTo(location: {+ file: string;- /**- * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by- * it.- */- headers?: { [key: string]: string; };+ line?: number;- /**- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.- */- ignoreHTTPSErrors?: boolean;+ column?: number;+ }): Promise<void>;+}- /**- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.- */- maxRedirects?: number;+/**+ * [Dialog](https://playwright.dev/docs/api/class-dialog) objects are dispatched by page via the+ * [page.on('dialog')](https://playwright.dev/docs/api/class-page#page-event-dialog) event.+ *+ * An example of using `Dialog` class:+ *+ * ```js+ * const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.+ *+ * (async () => {+ * const browser = await chromium.launch();+ * const page = await browser.newPage();+ * page.on('dialog', async dialog => {+ * console.log(dialog.message());+ * await dialog.dismiss();+ * });+ * await page.evaluate(() => alert('1'));+ * await browser.close();+ * })();+ * ```+ *+ * **NOTE** Dialogs are dismissed automatically, unless there is a+ * [page.on('dialog')](https://playwright.dev/docs/api/class-page#page-event-dialog) listener. When listener is+ * present, it **must** either+ * [dialog.accept([promptText])](https://playwright.dev/docs/api/class-dialog#dialog-accept) or+ * [dialog.dismiss()](https://playwright.dev/docs/api/class-dialog#dialog-dismiss) the dialog - otherwise the page+ * will [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the+ * dialog, and actions like click will never finish.+ *+ */+export interface Dialog {+ /**+ * Returns when the dialog has been accepted.+ * @param promptText A text to enter in prompt. Does not cause any effects if the dialog's `type` is not prompt. Optional.+ */+ accept(promptText?: string): Promise<void>;- /**- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.- */- maxRetries?: number;+ /**+ * If dialog is prompt, returns default prompt value. Otherwise, returns empty string.+ */+ defaultValue(): string;- /**- * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this- * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless- * explicitly provided. File values can be passed either as- * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file- * name, mime-type and its content.- */- multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{- /**- * File name- */- name: string;+ /**+ * Returns when the dialog has been dismissed.+ */+ dismiss(): Promise<void>;- /**- * File type- */- mimeType: string;+ /**+ * A message displayed in the dialog.+ */+ message(): string;- /**- * File content- */- buffer: Buffer;- }; };+ /**+ * The page that initiated this dialog, if available.+ */+ page(): null|Page;- /**- * Query parameters to be sent with the URL.- */- params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;+ /**+ * Returns dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`.+ */+ type(): string;+}- /**- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.- */- timeout?: number;- }): Promise<APIResponse>;+/**+ * [Disposable](https://playwright.dev/docs/api/class-disposable) is returned from various methods to allow undoing+ * the corresponding action. For example,+ * [page.addInitScript(script[, arg])](https://playwright.dev/docs/api/class-page#page-add-init-script) returns a+ * [Disposable](https://playwright.dev/docs/api/class-disposable) that can be used to remove the init script.+ */+export interface Disposable {+ /**+ * Removes the associated resource. For example, removes the init script installed via+ * [page.addInitScript(script[, arg])](https://playwright.dev/docs/api/class-page#page-add-init-script) or+ * [browserContext.addInitScript(script[, arg])](https://playwright.dev/docs/api/class-browsercontext#browser-context-add-init-script).+ */+ dispose(): Promise<void>;++ [Symbol.asyncDispose](): Promise<void>;+}++/**+ * [Download](https://playwright.dev/docs/api/class-download) objects are dispatched by page via the+ * [page.on('download')](https://playwright.dev/docs/api/class-page#page-event-download) event.+ *+ * All the downloaded files belonging to the browser context are deleted when the browser context is closed.+ *+ * Download event is emitted once the download starts. Download path becomes available once download completes.+ *+ * ```js+ * // Start waiting for download before clicking. Note no await.+ * const downloadPromise = page.waitForEvent('download');+ * await page.getByText('Download file').click();+ * const download = await downloadPromise;+ *+ * // Wait for the download process to complete and save the downloaded file somewhere.+ * await download.saveAs('/path/to/save/at/' + download.suggestedFilename());+ * ```+ *+ */+export interface Download {+ /**+ * Cancels a download. Will not fail if the download is already finished or canceled. Upon successful cancellations,+ * `download.failure()` would resolve to `'canceled'`.+ */+ cancel(): Promise<void>;/**- * Sends HTTP(S) [HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD) request and returns its- * response. The method will populate request cookies from the context and update context cookies from the response.- * The method will automatically follow redirects.- * @param url Target URL.+ * Returns a readable stream for a successful download, or throws for a failed/canceled download.+ *+ * **NOTE** If you don't need a readable stream, it's usually simpler to read the file from disk after the download+ * completed. See [download.path()](https://playwright.dev/docs/api/class-download#download-path).+ *+ */+ createReadStream(): Promise<Readable>;++ /**+ * Deletes the downloaded file. Will wait for the download to finish if necessary.+ */+ delete(): Promise<void>;++ /**+ * Returns download error if any. Will wait for the download to finish if necessary.+ */+ failure(): Promise<null|string>;++ /**+ * Get the page that the download belongs to.+ */+ page(): Page;++ /**+ * Returns path to the downloaded file for a successful download, or throws for a failed/canceled download. The method+ * will wait for the download to finish if necessary. The method throws when connected remotely.+ *+ * Note that the download's file name is a random GUID, use+ * [download.suggestedFilename()](https://playwright.dev/docs/api/class-download#download-suggested-filename) to get+ * suggested file name.+ */+ path(): Promise<string>;++ /**+ * Copy the download to a user-specified path. It is safe to call this method while the download is still in progress.+ * Will wait for the download to finish if necessary.+ *+ * **Usage**+ *+ * ```js+ * await download.saveAs('/path/to/save/at/' + download.suggestedFilename());+ * ```+ *+ * @param path Path where the download should be copied.+ */+ saveAs(path: string): Promise<void>;++ /**+ * Returns suggested filename for this download. It is typically computed by the browser from the+ * [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) response+ * header or the `download` attribute. See the spec on [whatwg](https://html.spec.whatwg.org/#downloading-resources).+ * Different browsers can use different logic for computing it.+ */+ suggestedFilename(): string;++ /**+ * Returns downloaded url.+ */+ url(): string;+}++/**+ * [FileChooser](https://playwright.dev/docs/api/class-filechooser) objects are dispatched by the page in the+ * [page.on('filechooser')](https://playwright.dev/docs/api/class-page#page-event-file-chooser) event.+ *+ * ```js+ * // Start waiting for file chooser before clicking. Note no await.+ * const fileChooserPromise = page.waitForEvent('filechooser');+ * await page.getByText('Upload file').click();+ * const fileChooser = await fileChooserPromise;+ * await fileChooser.setFiles(path.join(__dirname, 'myfile.pdf'));+ * ```+ *+ */+export interface FileChooser {+ /**+ * Returns input element associated with this file chooser.+ */+ element(): ElementHandle;++ /**+ * Returns whether this file chooser accepts multiple files.+ */+ isMultiple(): boolean;++ /**+ * Returns page this file chooser belongs to.+ */+ page(): Page;++ /**+ * Sets the value of the file input this chooser is associated with. If some of the `filePaths` are relative paths,+ * then they are resolved relative to the current working directory. For empty array, clears the selected files.+ * @param files* @param options*/- head(url: string, options?: {+ setFiles(files: string|ReadonlyArray<string>|{/**- * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string- * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`- * header will be set to `application/octet-stream` if not explicitly set.+ * File name*/- data?: string|Buffer|Serializable;+ name: string;/**- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status- * codes.+ * File type*/- failOnStatusCode?: boolean;+ mimeType: string;/**- * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent- * as this request body. If this parameter is specified `content-type` header will be set to- * `application/x-www-form-urlencoded` unless explicitly provided.+ * File content*/- form?: { [key: string]: string|number|boolean; }|FormData;-+ buffer: Buffer;+ }|ReadonlyArray<{/**- * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by- * it.+ * File name*/- headers?: { [key: string]: string; };+ name: string;/**- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.+ * File type*/- ignoreHTTPSErrors?: boolean;+ mimeType: string;/**- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.+ * File content*/- maxRedirects?: number;-+ buffer: Buffer;+ }>, options?: {/**- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.+ * This option has no effect.+ * @deprecated This option has no effect.*/- maxRetries?: number;+ noWaitAfter?: boolean;/**- * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this- * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless- * explicitly provided. File values can be passed either as- * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file- * name, mime-type and its content.+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`+ * option in the config, or by using the+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.*/- multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{- /**- * File name- */- name: string;-- /**- * File type- */- mimeType: string;-- /**- * File content- */- buffer: Buffer;- }; };+ timeout?: number;+ }): Promise<void>;+}+/**+ * FrameLocator represents a view to the `iframe` on the page. It captures the logic sufficient to retrieve the+ * `iframe` and locate elements in that iframe. FrameLocator can be created with either+ * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame),+ * [page.frameLocator(selector)](https://playwright.dev/docs/api/class-page#page-frame-locator) or+ * [locator.frameLocator(selector)](https://playwright.dev/docs/api/class-locator#locator-frame-locator) method.+ *+ * ```js+ * const locator = page.locator('#my-frame').contentFrame().getByText('Submit');+ * await locator.click();+ * ```+ *+ * **Strictness**+ *+ * Frame locators are strict. This means that all operations on frame locators will throw if more than one element+ * matches a given selector.+ *+ * ```js+ * // Throws if there are several frames in DOM:+ * await page.locator('.result-frame').contentFrame().getByRole('button').click();+ *+ * // Works because we explicitly tell locator to pick the first frame:+ * await page.locator('.result-frame').contentFrame().first().getByRole('button').click();+ * ```+ *+ * **Converting Locator to FrameLocator**+ *+ * If you have a [Locator](https://playwright.dev/docs/api/class-locator) object pointing to an `iframe` it can be+ * converted to [FrameLocator](https://playwright.dev/docs/api/class-framelocator) using+ * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame).+ *+ * **Converting FrameLocator to Locator**+ *+ * If you have a [FrameLocator](https://playwright.dev/docs/api/class-framelocator) object it can be converted to+ * [Locator](https://playwright.dev/docs/api/class-locator) pointing to the same `iframe` using+ * [frameLocator.owner()](https://playwright.dev/docs/api/class-framelocator#frame-locator-owner).+ */+export interface FrameLocator {+ /**+ * Returns locator to the first matching frame.+ * @deprecated Use [locator.first()](https://playwright.dev/docs/api/class-locator#locator-first) followed by+ * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame) instead.+ */+ first(): FrameLocator;++ /**+ * When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements+ * in that iframe.+ * @param selector A selector to use when resolving DOM element.+ */+ frameLocator(selector: string): FrameLocator;++ /**+ * Allows locating elements by their alt text.+ *+ * **Usage**+ *+ * For example, this method will find the image by alt text "Playwright logo":+ *+ * ```html+ * <img alt='Playwright logo'>+ * ```+ *+ * ```js+ * await page.getByAltText('Playwright logo').click();+ * ```+ *+ * @param text Text to locate the element for.+ * @param options+ */+ getByAltText(text: string|RegExp, options?: {/**- * Query parameters to be sent with the URL.+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a+ * regular expression. Note that exact match still trims whitespace.*/- params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;+ exact?: boolean;+ }): Locator;+ /**+ * Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the+ * `aria-label` attribute.+ *+ * **Usage**+ *+ * For example, this method will find inputs by label "Username" and "Password" in the following DOM:+ *+ * ```html+ * <input aria-label="Username">+ * <label for="password-input">Password:</label>+ * <input id="password-input">+ * ```+ *+ * ```js+ * await page.getByLabel('Username').fill('john');+ * await page.getByLabel('Password').fill('secret');+ * ```+ *+ * @param text Text to locate the element for.+ * @param options+ */+ getByLabel(text: string|RegExp, options?: {/**- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a+ * regular expression. Note that exact match still trims whitespace.*/- timeout?: number;- }): Promise<APIResponse>;+ exact?: boolean;+ }): Locator;/**- * Sends HTTP(S) [PATCH](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) request and returns its- * response. The method will populate request cookies from the context and update context cookies from the response.- * The method will automatically follow redirects.- * @param url Target URL.+ * Allows locating input elements by the placeholder text.+ *+ * **Usage**+ *+ * For example, consider the following DOM structure.+ *+ * ```html+ * <input type="email" placeholder="[email protected]" />+ * ```+ *+ * You can fill the input after locating it by the placeholder text:+ *+ * ```js+ * await page+ * .getByPlaceholder('[email protected]')+ * .fill('[email protected]');+ * ```+ *+ * @param text Text to locate the element for.* @param options*/- patch(url: string, options?: {+ getByPlaceholder(text: string|RegExp, options?: {/**- * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string- * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`- * header will be set to `application/octet-stream` if not explicitly set.+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a+ * regular expression. Note that exact match still trims whitespace.*/- data?: string|Buffer|Serializable;+ exact?: boolean;+ }): Locator;+ /**+ * Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),+ * [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and+ * [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).+ *+ * **Usage**+ *+ * Consider the following DOM structure.+ *+ * ```html+ * <h3>Sign up</h3>+ * <label>+ * <input type="checkbox" /> Subscribe+ * </label>+ * <br/>+ * <button>Submit</button>+ * ```+ *+ * You can locate each element by its implicit role:+ *+ * ```js+ * await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible();+ *+ * await page.getByRole('checkbox', { name: 'Subscribe' }).check();+ *+ * await page.getByRole('button', { name: /submit/i }).click();+ * ```+ *+ * **Details**+ *+ * Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback+ * about the ARIA guidelines.+ *+ * Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)+ * that is recognized by the role selector. You can find all the+ * [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**+ * duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.+ * @param role Required aria role.+ * @param options+ */+ getByRole(role: "alert"|"alertdialog"|"application"|"article"|"banner"|"blockquote"|"button"|"caption"|"cell"|"checkbox"|"code"|"columnheader"|"combobox"|"complementary"|"contentinfo"|"definition"|"deletion"|"dialog"|"directory"|"document"|"emphasis"|"feed"|"figure"|"form"|"generic"|"grid"|"gridcell"|"group"|"heading"|"img"|"insertion"|"link"|"list"|"listbox"|"listitem"|"log"|"main"|"marquee"|"math"|"meter"|"menu"|"menubar"|"menuitem"|"menuitemcheckbox"|"menuitemradio"|"navigation"|"none"|"note"|"option"|"paragraph"|"presentation"|"progressbar"|"radio"|"radiogroup"|"region"|"row"|"rowgroup"|"rowheader"|"scrollbar"|"search"|"searchbox"|"separator"|"slider"|"spinbutton"|"status"|"strong"|"subscript"|"superscript"|"switch"|"tab"|"table"|"tablist"|"tabpanel"|"term"|"textbox"|"time"|"timer"|"toolbar"|"tooltip"|"tree"|"treegrid"|"treeitem", options?: {/**- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status- * codes.+ * An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.+ *+ * Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).*/- failOnStatusCode?: boolean;+ checked?: boolean;/**- * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent- * as this request body. If this parameter is specified `content-type` header will be set to- * `application/x-www-form-urlencoded` unless explicitly provided.+ * Option to match the [accessible description](https://w3c.github.io/accname/#dfn-accessible-description). By+ * default, matching is case-insensitive and searches for a substring, use+ * [`exact`](https://playwright.dev/docs/api/class-framelocator#frame-locator-get-by-role-option-exact) to control+ * this behavior.+ *+ * Learn more about [accessible description](https://w3c.github.io/accname/#dfn-accessible-description).*/- form?: { [key: string]: string|number|boolean; }|FormData;+ description?: string|RegExp;/**- * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by- * it.+ * An attribute that is usually set by `aria-disabled` or `disabled`.+ *+ * **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about+ * [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).+ **/- headers?: { [key: string]: string; };+ disabled?: boolean;/**- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.+ * Whether [`name`](https://playwright.dev/docs/api/class-framelocator#frame-locator-get-by-role-option-name) and+ * [`description`](https://playwright.dev/docs/api/class-framelocator#frame-locator-get-by-role-option-description)+ * are matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when the value is a regular+ * expression. Note that exact match still trims whitespace.*/- ignoreHTTPSErrors?: boolean;+ exact?: boolean;/**- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.+ * An attribute that is usually set by `aria-expanded`.+ *+ * Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).*/- maxRedirects?: number;+ expanded?: boolean;/**- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.+ * Option that controls whether hidden elements are matched. By default, only non-hidden elements, as+ * [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.+ *+ * Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).*/- maxRetries?: number;+ includeHidden?: boolean;/**- * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this- * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless- * explicitly provided. File values can be passed either as- * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file- * name, mime-type and its content.+ * A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values+ * for `<h1>-<h6>` elements.+ *+ * Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).*/- multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{- /**- * File name- */- name: string;-- /**- * File type- */- mimeType: string;-- /**- * File content- */- buffer: Buffer;- }; };+ level?: number;/**- * Query parameters to be sent with the URL.+ * Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is+ * case-insensitive and searches for a substring, use+ * [`exact`](https://playwright.dev/docs/api/class-framelocator#frame-locator-get-by-role-option-exact) to control+ * this behavior.+ *+ * Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).*/- params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;+ name?: string|RegExp;/**- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.+ * An attribute that is usually set by `aria-pressed`.+ *+ * Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).*/- timeout?: number;- }): Promise<APIResponse>;+ pressed?: boolean;++ /**+ * An attribute that is usually set by `aria-selected`.+ *+ * Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).+ */+ selected?: boolean;+ }): Locator;/**- * Sends HTTP(S) [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) request and returns its- * response. The method will populate request cookies from the context and update context cookies from the response.- * The method will automatically follow redirects.+ * Locate element by the test id.** **Usage***- * JSON objects can be passed directly to the request:+ * Consider the following DOM structure.+ *+ * ```html+ * <button data-testid="directions">Itinéraire</button>+ * ```+ *+ * You can locate the element by its test id:** ```js- * await request.post('https://example.com/api/createBook', {- * data: {- * title: 'Book Title',- * author: 'John Doe',- * }- * });+ * await page.getByTestId('directions').click();* ```*- * To send form data to the server use `form` option. Its value will be encoded into the request body with- * `application/x-www-form-urlencoded` encoding (see below how to use `multipart/form-data` form encoding to send- * files):+ * **Details**+ *+ * By default, the `data-testid` attribute is used as a test id. Use+ * [selectors.setTestIdAttribute(attributeName)](https://playwright.dev/docs/api/class-selectors#selectors-set-test-id-attribute)+ * to configure a different test id attribute if necessary.** ```js- * await request.post('https://example.com/api/findBook', {- * form: {- * title: 'Book Title',- * author: 'John Doe',- * }+ * // Set custom test id attribute from @playwright/test config:+ * import { defineConfig } from '@playwright/test';+ *+ * export default defineConfig({+ * use: {+ * testIdAttribute: 'data-pw'+ * },* });* ```*- * The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data`- * encoding. Use [FormData] to construct request body and pass it to the request as `multipart` parameter:+ * @param testId Id to locate the element by.+ */+ getByTestId(testId: string|RegExp): Locator;++ /**+ * Allows locating elements that contain given text.+ *+ * See also [locator.filter([options])](https://playwright.dev/docs/api/class-locator#locator-filter) that allows to+ * match by another criteria, like an accessible role, and then filter by the text content.+ *+ * **Usage**+ *+ * Consider the following DOM structure:+ *+ * ```html+ * <div>Hello <span>world</span></div>+ * <div>Hello</div>+ * ```+ *+ * You can locate by text substring, exact string, or a regular expression:** ```js- * const form = new FormData();- * form.set('name', 'John');- * form.append('name', 'Doe');- * // Send two file fields with the same name.- * form.append('file', new File(['console.log(2024);'], 'f1.js', { type: 'text/javascript' }));- * form.append('file', new File(['hello'], 'f2.txt', { type: 'text/plain' }));- * await request.post('https://example.com/api/uploadForm', {- * multipart: form- * });+ * // Matches <span>+ * page.getByText('world');+ *+ * // Matches first <div>+ * page.getByText('Hello world');+ *+ * // Matches second <div>+ * page.getByText('Hello', { exact: true });+ *+ * // Matches both <div>s+ * page.getByText(/Hello/);+ *+ * // Matches second <div>+ * page.getByText(/^hello$/i);* ```*- * @param url Target URL.+ * **Details**+ *+ * Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into+ * one, turns line breaks into spaces and ignores leading and trailing whitespace.+ *+ * Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For+ * example, locating by text `"Log in"` matches `<input type=button value="Log in">`.+ * @param text Text to locate the element for.* @param options*/- post(url: string, options?: {- /**- * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string- * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`- * header will be set to `application/octet-stream` if not explicitly set.- */- data?: string|Buffer|Serializable;-- /**- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status- * codes.- */- failOnStatusCode?: boolean;-+ getByText(text: string|RegExp, options?: {/**- * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent- * as this request body. If this parameter is specified `content-type` header will be set to- * `application/x-www-form-urlencoded` unless explicitly provided.+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a+ * regular expression. Note that exact match still trims whitespace.*/- form?: { [key: string]: string|number|boolean; }|FormData;+ exact?: boolean;+ }): Locator;+ /**+ * Allows locating elements by their title attribute.+ *+ * **Usage**+ *+ * Consider the following DOM structure.+ *+ * ```html+ * <span title='Issues count'>25 issues</span>+ * ```+ *+ * You can check the issues count after locating it by the title text:+ *+ * ```js+ * await expect(page.getByTitle('Issues count')).toHaveText('25 issues');+ * ```+ *+ * @param text Text to locate the element for.+ * @param options+ */+ getByTitle(text: string|RegExp, options?: {/**- * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by- * it.+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a+ * regular expression. Note that exact match still trims whitespace.*/- headers?: { [key: string]: string; };+ exact?: boolean;+ }): Locator;- /**- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.- */- ignoreHTTPSErrors?: boolean;+ /**+ * Returns locator to the last matching frame.+ * @deprecated Use [locator.last()](https://playwright.dev/docs/api/class-locator#locator-last) followed by+ * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame) instead.+ */+ last(): FrameLocator;+ /**+ * The method finds an element matching the specified selector in the locator's subtree. It also accepts filter+ * options, similar to [locator.filter([options])](https://playwright.dev/docs/api/class-locator#locator-filter)+ * method.+ *+ * [Learn more about locators](https://playwright.dev/docs/locators).+ * @param selectorOrLocator A selector or locator to use when resolving DOM element.+ * @param options+ */+ locator(selectorOrLocator: string|Locator, options?: {/**- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.+ * Narrows down the results of the method to those which contain elements matching this relative locator. For example,+ * `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.+ *+ * Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not+ * the document root. For example, you can find `content` that has `div` in+ * `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article+ * div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.+ *+ * Note that outer and inner locators must belong to the same frame. Inner locator must not contain+ * [FrameLocator](https://playwright.dev/docs/api/class-framelocator)s.*/- maxRedirects?: number;+ has?: Locator;/**- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.+ * Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the+ * outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.+ *+ * Note that outer and inner locators must belong to the same frame. Inner locator must not contain+ * [FrameLocator](https://playwright.dev/docs/api/class-framelocator)s.*/- maxRetries?: number;+ hasNot?: Locator;/**- * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this- * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless- * explicitly provided. File values can be passed either as- * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file- * name, mime-type and its content.+ * Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.+ * When passed a [string], matching is case-insensitive and searches for a substring.*/- multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{- /**- * File name- */- name: string;-- /**- * File type- */- mimeType: string;-- /**- * File content- */- buffer: Buffer;- }; };+ hasNotText?: string|RegExp;/**- * Query parameters to be sent with the URL.+ * Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When+ * passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches+ * `<article><div>Playwright</div></article>`.*/- params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;+ hasText?: string|RegExp;+ }): Locator;- /**- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.- */- timeout?: number;- }): Promise<APIResponse>;+ /**+ * Returns locator to the n-th matching frame. It's zero based, `nth(0)` selects the first frame.+ * @deprecated Use [locator.nth(index)](https://playwright.dev/docs/api/class-locator#locator-nth) followed by+ * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame) instead.+ * @param index+ */+ nth(index: number): FrameLocator;/**- * Sends HTTP(S) [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) request and returns its- * response. The method will populate request cookies from the context and update context cookies from the response.- * The method will automatically follow redirects.- * @param url Target URL.- * @param options- */- put(url: string, options?: {- /**- * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string- * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`- * header will be set to `application/octet-stream` if not explicitly set.- */- data?: string|Buffer|Serializable;-- /**- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status- * codes.- */- failOnStatusCode?: boolean;-- /**- * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent- * as this request body. If this parameter is specified `content-type` header will be set to- * `application/x-www-form-urlencoded` unless explicitly provided.- */- form?: { [key: string]: string|number|boolean; }|FormData;-- /**- * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by- * it.- */- headers?: { [key: string]: string; };-- /**- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.- */- ignoreHTTPSErrors?: boolean;-- /**- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.- */- maxRedirects?: number;-- /**- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.- */- maxRetries?: number;-- /**- * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this- * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless- * explicitly provided. File values can be passed either as- * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file- * name, mime-type and its content.- */- multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{- /**- * File name- */- name: string;-- /**- * File type- */- mimeType: string;-- /**- * File content- */- buffer: Buffer;- }; };-- /**- * Query parameters to be sent with the URL.- */- params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;-- /**- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.- */- timeout?: number;- }): Promise<APIResponse>;-- /**- * Returns storage state for this request context, contains current cookies and local storage snapshot if it was- * passed to the constructor.- * @param options+ * Returns a [Locator](https://playwright.dev/docs/api/class-locator) object pointing to the same `iframe` as this+ * frame locator.+ *+ * Useful when you have a [FrameLocator](https://playwright.dev/docs/api/class-framelocator) object obtained+ * somewhere, and later on would like to interact with the `iframe` element.+ *+ * For a reverse operation, use+ * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame).+ *+ * **Usage**+ *+ * ```js+ * const frameLocator = page.locator('iframe[name="embedded"]').contentFrame();+ * // ...+ * const locator = frameLocator.owner();+ * await expect(locator).toBeVisible();+ * ```+ **/- storageState(options?: {- /**- * Set to `true` to include IndexedDB in the storage state snapshot.- */- indexedDB?: boolean;-- /**- * The file path to save the storage state to. If- * [`path`](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-storage-state-option-path) is- * a relative path, then it is resolved relative to current working directory. If no path is provided, storage state- * is still returned, but won't be saved to the disk.- */- path?: string;- }): Promise<{- cookies: Array<{- name: string;-- value: string;-- domain: string;-- path: string;-- /**- * Unix time in seconds.- */- expires: number;-- httpOnly: boolean;-- secure: boolean;-- sameSite: "Strict"|"Lax"|"None";- }>;-- origins: Array<{- origin: string;-- localStorage: Array<{- name: string;-- value: string;- }>;- }>;- }>;-- tracing: Tracing;-- [Symbol.asyncDispose](): Promise<void>;+ owner(): Locator;}/**- * [APIResponse](https://playwright.dev/docs/api/class-apiresponse) class represents responses returned by- * [apiRequestContext.get(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-get)- * and similar methods.+ * Keyboard provides an api for managing a virtual keyboard. The high level api is+ * [keyboard.type(text[, options])](https://playwright.dev/docs/api/class-keyboard#keyboard-type), which takes raw+ * characters and generates proper `keydown`, `keypress`/`input`, and `keyup` events on your page.+ *+ * For finer control, you can use [keyboard.down(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-down),+ * [keyboard.up(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-up), and+ * [keyboard.insertText(text)](https://playwright.dev/docs/api/class-keyboard#keyboard-insert-text) to manually fire+ * events as if they were generated from a real keyboard.+ *+ * An example of holding down `Shift` in order to select and delete some text:+ *+ * ```js+ * await page.keyboard.type('Hello World!');+ * await page.keyboard.press('ArrowLeft');+ *+ * await page.keyboard.down('Shift');+ * for (let i = 0; i < ' World'.length; i++)+ * await page.keyboard.press('ArrowLeft');+ * await page.keyboard.up('Shift');+ *+ * await page.keyboard.press('Backspace');+ * // Result text will end up saying 'Hello!'+ * ```+ *+ * An example of pressing uppercase `A`+ *+ * ```js+ * await page.keyboard.press('Shift+KeyA');+ * // or+ * await page.keyboard.press('Shift+A');+ * ```+ *+ * An example to trigger select-all with the keyboard+ *+ * ```js+ * await page.keyboard.press('ControlOrMeta+A');+ * ```+ **/-export interface APIResponse {+export interface Keyboard {/**- * Returns the buffer with response body.+ * Dispatches a `keydown` event.+ *+ * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-down-option-key) can specify the intended+ * [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character+ * to generate the text for. A superset of the+ * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-down-option-key) values can be found+ * [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:+ *+ * `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,+ * `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,+ * etc.+ *+ * Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,+ * `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.+ *+ * Holding down `Shift` will type the text that corresponds to the+ * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-down-option-key) in the upper case.+ *+ * If [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-down-option-key) is a single character, it is+ * case-sensitive, so the values `a` and `A` will generate different respective texts.+ *+ * If [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-down-option-key) is a modifier key, `Shift`,+ * `Meta`, `Control`, or `Alt`, subsequent key presses will be sent with that modifier active. To release the modifier+ * key, use [keyboard.up(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-up).+ *+ * After the key is pressed once, subsequent calls to+ * [keyboard.down(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-down) will have+ * [repeat](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat) set to true. To release the key,+ * use [keyboard.up(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-up).+ *+ * **NOTE** Modifier keys DO influence `keyboard.down`. Holding down `Shift` will type the text in upper case.+ *+ * @param key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.*/- body(): Promise<Buffer>;+ down(key: string): Promise<void>;/**- * Disposes the body of this response. If not called then the body will stay in memory until the context closes.+ * Dispatches only `input` event, does not emit the `keydown`, `keyup` or `keypress` events.+ *+ * **Usage**+ *+ * ```js+ * page.keyboard.insertText('嗨');+ * ```+ *+ * **NOTE** Modifier keys DO NOT effect `keyboard.insertText`. Holding down `Shift` will not type the text in upper+ * case.+ *+ * @param text Sets input to the specified text value.*/- dispose(): Promise<void>;+ insertText(text: string): Promise<void>;/**- * An object with all the response HTTP headers associated with this response.+ * **NOTE** In most cases, you should use+ * [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press) instead.+ *+ * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-press-option-key) can specify the intended+ * [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character+ * to generate the text for. A superset of the+ * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-press-option-key) values can be found+ * [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:+ *+ * `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,+ * `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,+ * etc.+ *+ * Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,+ * `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.+ *+ * Holding down `Shift` will type the text that corresponds to the+ * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-press-option-key) in the upper case.+ *+ * If [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-press-option-key) is a single character, it is+ * case-sensitive, so the values `a` and `A` will generate different respective texts.+ *+ * Shortcuts such as `key: "Control+o"`, `key: "Control++` or `key: "Control+Shift+T"` are supported as well. When+ * specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.+ *+ * **Usage**+ *+ * ```js+ * const page = await browser.newPage();+ * await page.goto('https://keycode.info');+ * await page.keyboard.press('A');+ * await page.screenshot({ path: 'A.png' });+ * await page.keyboard.press('ArrowLeft');+ * await page.screenshot({ path: 'ArrowLeft.png' });+ * await page.keyboard.press('Shift+O');+ * await page.screenshot({ path: 'O.png' });+ * await browser.close();+ * ```+ *+ * Shortcut for [keyboard.down(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-down) and+ * [keyboard.up(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-up).+ * @param key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.+ * @param options*/- headers(): { [key: string]: string; };+ press(key: string, options?: {+ /**+ * Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.+ */+ delay?: number;+ }): Promise<void>;/**- * An array with all the response HTTP headers associated with this response. Header names are not lower-cased.- * Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple times.+ * **NOTE** In most cases, you should use+ * [locator.fill(value[, options])](https://playwright.dev/docs/api/class-locator#locator-fill) instead. You only need+ * to press keys one by one if there is special keyboard handling on the page - in this case use+ * [locator.pressSequentially(text[, options])](https://playwright.dev/docs/api/class-locator#locator-press-sequentially).+ *+ * Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text.+ *+ * To press a special key, like `Control` or `ArrowDown`, use+ * [keyboard.press(key[, options])](https://playwright.dev/docs/api/class-keyboard#keyboard-press).+ *+ * **Usage**+ *+ * ```js+ * await page.keyboard.type('Hello'); // Types instantly+ * await page.keyboard.type('World', { delay: 100 }); // Types slower, like a user+ * ```+ *+ * **NOTE** Modifier keys DO NOT effect `keyboard.type`. Holding down `Shift` will not type the text in upper case.+ *+ * **NOTE** For characters that are not on a US keyboard, only an `input` event will be sent.+ *+ * @param text A text to type into a focused element.+ * @param options*/- headersArray(): Array<{+ type(text: string, options?: {/**- * Name of the header.+ * Time to wait between key presses in milliseconds. Defaults to 0.*/- name: string;+ delay?: number;+ }): Promise<void>;- /**- * Value of the header.- */- value: string;- }>;+ /**+ * Dispatches a `keyup` event.+ * @param key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.+ */+ up(key: string): Promise<void>;+}+/**+ * Playwright generates a lot of logs and they are accessible via the pluggable logger sink.+ *+ * ```js+ * const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.+ *+ * (async () => {+ * const browser = await chromium.launch({+ * logger: {+ * isEnabled: (name, severity) => name === 'api',+ * log: (name, severity, message, args) => console.log(`${name} ${message}`)+ * }+ * });+ * // ...+ * })();+ * ```+ *+ */+export interface Logger {/**- * Returns the JSON representation of response body.- *- * This method will throw if the response body is not parsable via `JSON.parse`.+ * Determines whether sink is interested in the logger with the given name and severity.+ * @param name logger name+ * @param severity*/- json(): Promise<Serializable>;+ isEnabled(name: string, severity: "verbose"|"info"|"warning"|"error"): boolean;/**- * Contains a boolean stating whether the response was successful (status in the range 200-299) or not.+ * @param name logger name+ * @param severity+ * @param message log message format+ * @param args message arguments+ * @param hints optional formatting hints*/- ok(): boolean;+ log(name: string, severity: "verbose"|"info"|"warning"|"error", message: string|Error, args: ReadonlyArray<Object>, hints: {+ /**+ * Optional preferred logger color.+ */+ color?: string;+ }): void;+}+/**+ * The Mouse class operates in main-frame CSS pixels relative to the top-left corner of the viewport.+ *+ * **NOTE** If you want to debug where the mouse moved, you can use the [Trace viewer](https://playwright.dev/docs/trace-viewer-intro) or+ * [Playwright Inspector](https://playwright.dev/docs/running-tests). A red dot showing the location of the mouse will be shown for every+ * mouse action.+ *+ * Every `page` object has its own Mouse, accessible with+ * [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse).+ *+ * ```js+ * // Using ‘page.mouse’ to trace a 100x100 square.+ * await page.mouse.move(0, 0);+ * await page.mouse.down();+ * await page.mouse.move(0, 100);+ * await page.mouse.move(100, 100);+ * await page.mouse.move(100, 0);+ * await page.mouse.move(0, 0);+ * await page.mouse.up();+ * ```+ *+ */+export interface Mouse {/**- * Contains the status code of the response (e.g., 200 for a success).+ * Shortcut for [mouse.move(x, y[, options])](https://playwright.dev/docs/api/class-mouse#mouse-move),+ * [mouse.down([options])](https://playwright.dev/docs/api/class-mouse#mouse-down),+ * [mouse.up([options])](https://playwright.dev/docs/api/class-mouse#mouse-up).+ * @param x X coordinate relative to the main frame's viewport in CSS pixels.+ * @param y Y coordinate relative to the main frame's viewport in CSS pixels.+ * @param options*/- status(): number;+ click(x: number, y: number, options?: {+ /**+ * Defaults to `left`.+ */+ button?: "left"|"right"|"middle";- /**- * Contains the status text of the response (e.g. usually an "OK" for a success).- */- statusText(): string;+ /**+ * defaults to 1. See [UIEvent.detail].+ */+ clickCount?: number;- /**- * Returns the text representation of response body.- */- text(): Promise<string>;+ /**+ * Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.+ */+ delay?: number;+ }): Promise<void>;/**- * Contains the URL of the response.+ * Shortcut for [mouse.move(x, y[, options])](https://playwright.dev/docs/api/class-mouse#mouse-move),+ * [mouse.down([options])](https://playwright.dev/docs/api/class-mouse#mouse-down),+ * [mouse.up([options])](https://playwright.dev/docs/api/class-mouse#mouse-up),+ * [mouse.down([options])](https://playwright.dev/docs/api/class-mouse#mouse-down) and+ * [mouse.up([options])](https://playwright.dev/docs/api/class-mouse#mouse-up).+ * @param x X coordinate relative to the main frame's viewport in CSS pixels.+ * @param y Y coordinate relative to the main frame's viewport in CSS pixels.+ * @param options*/- url(): string;+ dblclick(x: number, y: number, options?: {+ /**+ * Defaults to `left`.+ */+ button?: "left"|"right"|"middle";- [Symbol.asyncDispose](): Promise<void>;-}+ /**+ * Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.+ */+ delay?: number;+ }): Promise<void>;-export interface BrowserServer {/**- * Emitted when the browser server closes.+ * Dispatches a `mousedown` event.+ * @param options*/- on(event: 'close', listener: () => any): this;+ down(options?: {+ /**+ * Defaults to `left`.+ */+ button?: "left"|"right"|"middle";- /**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.- */- once(event: 'close', listener: () => any): this;+ /**+ * defaults to 1. See [UIEvent.detail].+ */+ clickCount?: number;+ }): Promise<void>;/**- * Emitted when the browser server closes.+ * Dispatches a `mousemove` event.+ * @param x X coordinate relative to the main frame's viewport in CSS pixels.+ * @param y Y coordinate relative to the main frame's viewport in CSS pixels.+ * @param options*/- addListener(event: 'close', listener: () => any): this;+ move(x: number, y: number, options?: {+ /**+ * Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor+ * position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.+ */+ steps?: number;+ }): Promise<void>;/**- * Removes an event listener added by `on` or `addListener`.+ * Dispatches a `mouseup` event.+ * @param options*/- removeListener(event: 'close', listener: () => any): this;+ up(options?: {+ /**+ * Defaults to `left`.+ */+ button?: "left"|"right"|"middle";- /**- * Removes an event listener added by `on` or `addListener`.- */- off(event: 'close', listener: () => any): this;+ /**+ * defaults to 1. See [UIEvent.detail].+ */+ clickCount?: number;+ }): Promise<void>;/**- * Emitted when the browser server closes.+ * Dispatches a `wheel` event. This method is usually used to manually scroll the page. See+ * [scrolling](https://playwright.dev/docs/input#scrolling) for alternative ways to scroll.+ *+ * **NOTE** Wheel events may cause scrolling if they are not handled, and this method does not wait for the scrolling+ * to finish before returning.+ *+ * @param deltaX Pixels to scroll horizontally.+ * @param deltaY Pixels to scroll vertically.*/- prependListener(event: 'close', listener: () => any): this;+ wheel(deltaX: number, deltaY: number): Promise<void>;+}- /**- * Closes the browser gracefully and makes sure the process is terminated.- */- close(): Promise<void>;+/**+ * This object can be used to launch or connect to Chromium, returning instances of+ * [Browser](https://playwright.dev/docs/api/class-browser).+ */+export const chromium: BrowserType;- /**- * Kills the browser process and waits for the process to exit.- */- kill(): Promise<void>;+/**+ * This object can be used to launch or connect to Firefox, returning instances of+ * [Browser](https://playwright.dev/docs/api/class-browser).+ */+export const firefox: BrowserType;- /**- * Spawned browser application process.- */- process(): ChildProcess;+/**+ * Exposes API that can be used for the Web API testing.+ */+export const request: APIRequest;- /**- * Browser websocket url.- *- * Browser websocket endpoint which can be used as an argument to- * [browserType.connect(endpoint[, options])](https://playwright.dev/docs/api/class-browsertype#browser-type-connect)- * to establish connection to the browser.- */- wsEndpoint(): string;+/**+ * Selectors can be used to install custom selector engines. See [extensibility](https://playwright.dev/docs/extensibility) for more+ * information.+ */+export const selectors: Selectors;- [Symbol.asyncDispose](): Promise<void>;-}+/**+ * This object can be used to launch or connect to WebKit, returning instances of+ * [Browser](https://playwright.dev/docs/api/class-browser).+ */+export const webkit: BrowserType;/**- * Accurately simulating time-dependent behavior is essential for verifying the correctness of applications. Learn- * more about [clock emulation](https://playwright.dev/docs/clock).+ * Whenever the page sends a request for a network resource the following sequence of events are emitted by+ * [Page](https://playwright.dev/docs/api/class-page):+ * - [page.on('request')](https://playwright.dev/docs/api/class-page#page-event-request) emitted when the request is+ * issued by the page.+ * - [page.on('response')](https://playwright.dev/docs/api/class-page#page-event-response) emitted when/if the+ * response status and headers are received for the request.+ * - [page.on('requestfinished')](https://playwright.dev/docs/api/class-page#page-event-request-finished) emitted+ * when the response body is downloaded and the request is complete.*- * Note that clock is installed for the entire [BrowserContext](https://playwright.dev/docs/api/class-browsercontext),- * so the time in all the pages and iframes is controlled by the same clock.+ * If request fails at some point, then instead of `'requestfinished'` event (and possibly instead of 'response'+ * event), the [page.on('requestfailed')](https://playwright.dev/docs/api/class-page#page-event-request-failed) event+ * is emitted.+ *+ * **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request+ * will complete with `'requestfinished'` event.+ *+ * If request gets a 'redirect' response, the request is successfully finished with the `requestfinished` event, and a+ * new request is issued to a redirected url.*/-export interface Clock {- /**- * Advance the clock by jumping forward in time. Only fires due timers at most once. This is equivalent to user- * closing the laptop lid for a while and reopening it later, after given time.- *- * **Usage**- *- * ```js- * await page.clock.fastForward(1000);- * await page.clock.fastForward('30:00');- * ```- *- * @param ticks Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are- * "08" for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.- */- fastForward(ticks: number|string): Promise<void>;-- /**- * Install fake implementations for the following time-related functions:- * - `Date`- * - `setTimeout`- * - `clearTimeout`- * - `setInterval`- * - `clearInterval`- * - `requestAnimationFrame`- * - `cancelAnimationFrame`- * - `requestIdleCallback`- * - `cancelIdleCallback`- * - `performance`- *- * Fake timers are used to manually control the flow of time in tests. They allow you to advance time, fire timers,- * and control the behavior of time-dependent functions. See- * [clock.runFor(ticks)](https://playwright.dev/docs/api/class-clock#clock-run-for) and- * [clock.fastForward(ticks)](https://playwright.dev/docs/api/class-clock#clock-fast-forward) for more information.- * @param options- */- install(options?: {- /**- * Time to initialize with, current system time by default.- */- time?: number|string|Date;- }): Promise<void>;-- /**- * Advance the clock by jumping forward in time and pause the time. Once this method is called, no timers are fired- * unless [clock.runFor(ticks)](https://playwright.dev/docs/api/class-clock#clock-run-for),- * [clock.fastForward(ticks)](https://playwright.dev/docs/api/class-clock#clock-fast-forward),- * [clock.pauseAt(time)](https://playwright.dev/docs/api/class-clock#clock-pause-at) or- * [clock.resume()](https://playwright.dev/docs/api/class-clock#clock-resume) is called.- *- * Only fires due timers at most once. This is equivalent to user closing the laptop lid for a while and reopening it- * at the specified time and pausing.- *- * **Usage**- *- * ```js- * await page.clock.pauseAt(new Date('2020-02-02'));- * await page.clock.pauseAt('2020-02-02');- * ```- *- * For best results, install the clock before navigating the page and set it to a time slightly before the intended- * test time. This ensures that all timers run normally during page loading, preventing the page from getting stuck.- * Once the page has fully loaded, you can safely use- * [clock.pauseAt(time)](https://playwright.dev/docs/api/class-clock#clock-pause-at) to pause the clock.- *- * ```js- * // Initialize clock with some time before the test time and let the page load- * // naturally. `Date.now` will progress as the timers fire.- * await page.clock.install({ time: new Date('2024-12-10T08:00:00') });- * await page.goto('http://localhost:3333');- * await page.clock.pauseAt(new Date('2024-12-10T10:00:00'));- * ```- *- * @param time Time to pause at.+export interface Request {+ /**+ * An object with all the request HTTP headers associated with this request. The header names are lower-cased.*/- pauseAt(time: number|string|Date): Promise<void>;+ allHeaders(): Promise<{ [key: string]: string; }>;/**- * Resumes timers. Once this method is called, time resumes flowing, timers are fired as usual.+ * Returns the [Response](https://playwright.dev/docs/api/class-response) object if the response has already been+ * received, `null` otherwise.+ *+ * Unlike [request.response()](https://playwright.dev/docs/api/class-request#request-response), this method does not+ * wait for the response to arrive. It returns immediately with the response object if the response has been received,+ * or `null` if the response has not been received yet.*/- resume(): Promise<void>;+ existingResponse(): null|Response;/**- * Advance the clock, firing all the time-related callbacks.+ * The method returns `null` unless this request has failed, as reported by `requestfailed` event.** **Usage***+ * Example of logging of all the failed requests:+ ** ```js- * await page.clock.runFor(1000);- * await page.clock.runFor('30:00');+ * page.on('requestfailed', request => {+ * console.log(request.url() + ' ' + request.failure().errorText);+ * });* ```*- * @param ticks Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are- * "08" for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.*/- runFor(ticks: number|string): Promise<void>;+ failure(): null|{+ /**+ * Human-readable error message, e.g. `'net::ERR_FAILED'`.+ */+ errorText: string;+ };/**- * Makes `Date.now` and `new Date()` return fixed fake time at all times, keeps all the timers running.- *- * Use this method for simple scenarios where you only need to test with a predefined time. For more advanced- * scenarios, use [clock.install([options])](https://playwright.dev/docs/api/class-clock#clock-install) instead. Read- * docs on [clock emulation](https://playwright.dev/docs/clock) to learn more.+ * Returns the [Frame](https://playwright.dev/docs/api/class-frame) that initiated this request.** **Usage**** ```js- * await page.clock.setFixedTime(Date.now());- * await page.clock.setFixedTime(new Date('2020-02-02'));- * await page.clock.setFixedTime('2020-02-02');+ * const frameUrl = request.frame().url();* ```*- * @param time Time to be set in milliseconds.- */- setFixedTime(time: number|string|Date): Promise<void>;-- /**- * Sets system time, but does not trigger any timers. Use this to test how the web page reacts to a time shift, for- * example switching from summer to winter time, or changing time zones.+ * **Details***- * **Usage**+ * Note that in some cases the frame is not available, and this method will throw.+ * - When request originates in the Service Worker. You can use `request.serviceWorker()` to check that.+ * - When navigation request is issued before the corresponding frame is created. You can use+ * [request.isNavigationRequest()](https://playwright.dev/docs/api/class-request#request-is-navigation-request) to+ * check that.+ *+ * Here is an example that handles all the cases:** ```js- * await page.clock.setSystemTime(Date.now());- * await page.clock.setSystemTime(new Date('2020-02-02'));- * await page.clock.setSystemTime('2020-02-02');+ * if (request.serviceWorker())+ * console.log(`request ${request.url()} from a service worker`);+ * else if (request.isNavigationRequest())+ * console.log(`request ${request.url()} is a navigation request`);+ * else+ * console.log(`request ${request.url()} from a frame ${request.frame().url()}`);* ```*- * @param time Time to be set in milliseconds.*/- setSystemTime(time: number|string|Date): Promise<void>;-}+ frame(): Frame;-/**- * [ConsoleMessage](https://playwright.dev/docs/api/class-consolemessage) objects are dispatched by page via the- * [page.on('console')](https://playwright.dev/docs/api/class-page#page-event-console) event. For each console message- * logged in the page there will be corresponding event in the Playwright context.- *- * ```js- * // Listen for all console logs- * page.on('console', msg => console.log(msg.text()));- *- * // Listen for all console events and handle errors- * page.on('console', msg => {- * if (msg.type() === 'error')- * console.log(`Error text: "${msg.text()}"`);- * });- *- * // Get the next console log- * const msgPromise = page.waitForEvent('console');- * await page.evaluate(() => {- * console.log('hello', 42, { foo: 'bar' }); // Issue console.log inside the page- * });- * const msg = await msgPromise;- *- * // Deconstruct console log arguments- * await msg.args()[0].jsonValue(); // hello- * await msg.args()[1].jsonValue(); // 42- * ```- *- */-export interface ConsoleMessage {/**- * List of arguments passed to a `console` function call. See also- * [page.on('console')](https://playwright.dev/docs/api/class-page#page-event-console).+ * An object with the request HTTP headers. The header names are lower-cased. Note that this method does not return+ * security-related headers, including cookie-related ones. You can use+ * [request.allHeaders()](https://playwright.dev/docs/api/class-request#request-all-headers) for complete list of+ * headers that include `cookie` information.*/- args(): Array<JSHandle>;+ headers(): { [key: string]: string; };- location(): {+ /**+ * An array with all the request HTTP headers associated with this request. Unlike+ * [request.allHeaders()](https://playwright.dev/docs/api/class-request#request-all-headers), header names are NOT+ * lower-cased. Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple times.+ */+ headersArray(): Promise<Array<{/**- * URL of the resource.+ * Name of the header.*/- url: string;+ name: string;/**- * 0-based line number in the resource.+ * Value of the header.*/- line: number;+ value: string;+ }>>;- /**- * 0-based column number in the resource.- */- column: number;+ /**+ * Returns the value of the header matching the name. The name is case-insensitive.+ * @param name Name of the header.+ */+ headerValue(name: string): Promise<null|string>;- /**- * 0-based line number in the resource. Deprecated, use `line` instead.- */- lineNumber: number;+ /**+ * Whether this request is driving frame's navigation.+ *+ * Some navigation requests are issued before the corresponding frame is created, and therefore do not have+ * [request.frame()](https://playwright.dev/docs/api/class-request#request-frame) available.+ */+ isNavigationRequest(): boolean;- /**- * 0-based column number in the resource. Deprecated, use `column` instead.- */- columnNumber: number;- };+ /**+ * Request's method (GET, POST, etc.)+ */+ method(): string;/**- * The page that produced this console message, if any.+ * Request's post body, if any.*/- page(): null|Page;+ postData(): null|string;/**- * The text of the console message.+ * Request's post body in a binary form, if any.*/- text(): string;+ postDataBuffer(): null|Buffer;/**- * The timestamp of the console message in milliseconds since the Unix epoch.+ * Returns parsed request's body for `form-urlencoded` and JSON as a fallback if any.+ *+ * When the response is `application/x-www-form-urlencoded` then a key/value object of the values will be returned.+ * Otherwise it will be parsed as JSON.*/- timestamp(): number;+ postDataJSON(): null|Serializable;- type(): "log"|"debug"|"info"|"error"|"warning"|"dir"|"dirxml"|"table"|"trace"|"clear"|"startGroup"|"startGroupCollapsed"|"endGroup"|"assert"|"profile"|"profileEnd"|"count"|"time"|"timeEnd";+ /**+ * Request that was redirected by the server to this one, if any.+ *+ * When the server responds with a redirect, Playwright creates a new+ * [Request](https://playwright.dev/docs/api/class-request) object. The two requests are connected by+ * `redirectedFrom()` and `redirectedTo()` methods. When multiple server redirects has happened, it is possible to+ * construct the whole redirect chain by repeatedly calling `redirectedFrom()`.+ *+ * **Usage**+ *+ * For example, if the website `http://example.com` redirects to `https://example.com`:+ *+ * ```js+ * const response = await page.goto('http://example.com');+ * console.log(response.request().redirectedFrom().url()); // 'http://example.com'+ * ```+ *+ * If the website `https://google.com` has no redirects:+ *+ * ```js+ * const response = await page.goto('https://google.com');+ * console.log(response.request().redirectedFrom()); // null+ * ```+ *+ */+ redirectedFrom(): null|Request;/**- * The web worker or service worker that produced this console message, if any. Note that console messages from web- * workers also have non-null- * [consoleMessage.page()](https://playwright.dev/docs/api/class-consolemessage#console-message-page).+ * New request issued by the browser if the server responded with redirect.+ *+ * **Usage**+ *+ * This method is the opposite of+ * [request.redirectedFrom()](https://playwright.dev/docs/api/class-request#request-redirected-from):+ *+ * ```js+ * console.log(request.redirectedFrom().redirectedTo() === request); // true+ * ```+ **/- worker(): null|Worker;-}+ redirectedTo(): null|Request;-/**- * Coverage gathers information about parts of JavaScript and CSS that were used by the page.- *- * An example of using JavaScript coverage to produce Istanbul report for page load:- *- * **NOTE** Coverage APIs are only supported on Chromium-based browsers.- *- * ```js- * const { chromium } = require('playwright');- * const v8toIstanbul = require('v8-to-istanbul');- *- * (async () => {- * const browser = await chromium.launch();- * const page = await browser.newPage();- * await page.coverage.startJSCoverage();- * await page.goto('https://chromium.org');- * const coverage = await page.coverage.stopJSCoverage();- * for (const entry of coverage) {- * const converter = v8toIstanbul('', 0, { source: entry.source });- * await converter.load();- * converter.applyCoverage(entry.functions);- * console.log(JSON.stringify(converter.toIstanbul()));- * }- * await browser.close();- * })();- * ```- *- */-export interface Coverage {/**- * Returns coverage is started- * @param options+ * Contains the request's resource type as it was perceived by the rendering engine. ResourceType will be one of the+ * following: `document`, `stylesheet`, `image`, `media`, `font`, `script`, `texttrack`, `xhr`, `fetch`,+ * `eventsource`, `websocket`, `manifest`, `other`.*/- startCSSCoverage(options?: {- /**- * Whether to reset coverage on every navigation. Defaults to `true`.- */- resetOnNavigation?: boolean;- }): Promise<void>;+ resourceType(): string;++ /**+ * Returns the matching [Response](https://playwright.dev/docs/api/class-response) object, or `null` if the response+ * was not received due to error.+ */+ response(): Promise<null|Response>;/**- * Returns coverage is started+ * The Service [Worker](https://playwright.dev/docs/api/class-worker) that is performing the request.*- * **NOTE** Anonymous scripts are ones that don't have an associated url. These are scripts that are dynamically- * created on the page using `eval` or `new Function`. If- * [`reportAnonymousScripts`](https://playwright.dev/docs/api/class-coverage#coverage-start-js-coverage-option-report-anonymous-scripts)- * is set to `true`, anonymous scripts will have `__playwright_evaluation_script__` as their URL.+ * **Details***- * @param options+ * This method is Chromium only. It's safe to call when using other browsers, but it will always be `null`.+ *+ * Requests originated in a Service Worker do not have a+ * [request.frame()](https://playwright.dev/docs/api/class-request#request-frame) available.*/- startJSCoverage(options?: {+ serviceWorker(): null|Worker;++ /**+ * Returns resource size information for given request.+ */+ sizes(): Promise<{/**- * Whether anonymous scripts generated by the page should be reported. Defaults to `false`.+ * Size of the request body (POST data payload) in bytes. Set to 0 if there was no body.*/- reportAnonymousScripts?: boolean;+ requestBodySize: number;/**- * Whether to reset coverage on every navigation. Defaults to `true`.+ * Total number of bytes from the start of the HTTP request message until (and including) the double CRLF before the+ * body.*/- resetOnNavigation?: boolean;- }): Promise<void>;+ requestHeadersSize: number;++ /**+ * Size of the received response body (encoded) in bytes.+ */+ responseBodySize: number;++ /**+ * Total number of bytes from the start of the HTTP response message until (and including) the double CRLF before the+ * body.+ */+ responseHeadersSize: number;+ }>;/**- * Returns the array of coverage reports for all stylesheets+ * Returns resource timing information for given request. Most of the timing values become available upon the+ * response, `responseEnd` becomes available when request finishes. Find more information at+ * [Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming).*- * **NOTE** CSS Coverage doesn't include dynamically injected style tags without sourceURLs.+ * **Usage**+ *+ * ```js+ * const requestFinishedPromise = page.waitForEvent('requestfinished');+ * await page.goto('http://example.com');+ * const request = await requestFinishedPromise;+ * console.log(request.timing());+ * ```**/- stopCSSCoverage(): Promise<Array<{+ timing(): {/**- * StyleSheet URL+ * Request start time in milliseconds elapsed since January 1, 1970 00:00:00 UTC*/- url: string;+ startTime: number;/**- * StyleSheet content, if available.+ * Time immediately before the browser starts the domain name lookup for the resource. The value is given in+ * milliseconds relative to `startTime`, -1 if not available.*/- text?: string;+ domainLookupStart: number;/**- * StyleSheet ranges that were used. Ranges are sorted and non-overlapping.+ * Time immediately after the browser starts the domain name lookup for the resource. The value is given in+ * milliseconds relative to `startTime`, -1 if not available.*/- ranges: Array<{- /**- * A start offset in text, inclusive- */- start: number;-- /**- * An end offset in text, exclusive- */- end: number;- }>;- }>>;+ domainLookupEnd: number;- /**- * Returns the array of coverage reports for all scripts- *- * **NOTE** JavaScript Coverage doesn't include anonymous scripts by default. However, scripts with sourceURLs are- * reported.- *- */- stopJSCoverage(): Promise<Array<{/**- * Script URL+ * Time immediately before the user agent starts establishing the connection to the server to retrieve the resource.+ * The value is given in milliseconds relative to `startTime`, -1 if not available.*/- url: string;+ connectStart: number;/**- * Script ID+ * Time immediately before the browser starts the handshake process to secure the current connection. The value is+ * given in milliseconds relative to `startTime`, -1 if not available.*/- scriptId: string;+ secureConnectionStart: number;/**- * Script content, if applicable.+ * Time immediately before the user agent starts establishing the connection to the server to retrieve the resource.+ * The value is given in milliseconds relative to `startTime`, -1 if not available.*/- source?: string;+ connectEnd: number;/**- * V8-specific coverage format.+ * Time immediately before the browser starts requesting the resource from the server, cache, or local resource. The+ * value is given in milliseconds relative to `startTime`, -1 if not available.*/- functions: Array<{- functionName: string;-- isBlockCoverage: boolean;+ requestStart: number;- ranges: Array<{- count: number;+ /**+ * Time immediately after the browser receives the first byte of the response from the server, cache, or local+ * resource. The value is given in milliseconds relative to `startTime`, -1 if not available.+ */+ responseStart: number;- startOffset: number;+ /**+ * Time immediately after the browser receives the last byte of the resource or immediately before the transport+ * connection is closed, whichever comes first. The value is given in milliseconds relative to `startTime`, -1 if not+ * available.+ */+ responseEnd: number;+ };- endOffset: number;- }>;- }>;- }>>;+ /**+ * URL of the request.+ */+ url(): string;}/**- * API for controlling the Playwright debugger. The debugger allows pausing script execution and inspecting the page.- * Obtain the debugger instance via- * [browserContext.debugger](https://playwright.dev/docs/api/class-browsercontext#browser-context-debugger).+ * [Response](https://playwright.dev/docs/api/class-response) class represents responses which are received by page.*/-export interface Debugger {+export interface Response {/**- * Emitted when the debugger pauses or resumes.+ * An object with all the response HTTP headers associated with this response.*/- on(event: 'pausedstatechanged', listener: () => any): this;+ allHeaders(): Promise<{ [key: string]: string; }>;/**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ * Returns the buffer with response body.*/- once(event: 'pausedstatechanged', listener: () => any): this;+ body(): Promise<Buffer>;/**- * Emitted when the debugger pauses or resumes.+ * Waits for this response to finish, returns always `null`.*/- addListener(event: 'pausedstatechanged', listener: () => any): this;+ finished(): Promise<null|Error>;/**- * Removes an event listener added by `on` or `addListener`.+ * Returns the [Frame](https://playwright.dev/docs/api/class-frame) that initiated this response.*/- removeListener(event: 'pausedstatechanged', listener: () => any): this;+ frame(): Frame;/**- * Removes an event listener added by `on` or `addListener`.+ * Indicates whether this Response was fulfilled by a Service Worker's Fetch Handler (i.e. via+ * [FetchEvent.respondWith](https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent/respondWith)).*/- off(event: 'pausedstatechanged', listener: () => any): this;+ fromServiceWorker(): boolean;/**- * Emitted when the debugger pauses or resumes.+ * An object with the response HTTP headers. The header names are lower-cased. Note that this method does not return+ * security-related headers, including cookie-related ones. You can use+ * [response.allHeaders()](https://playwright.dev/docs/api/class-response#response-all-headers) for complete list of+ * headers that include `cookie` information.*/- prependListener(event: 'pausedstatechanged', listener: () => any): this;+ headers(): { [key: string]: string; };/**- * Resumes script execution and pauses again before the next action. Throws if the debugger is not paused.+ * An array with all the request HTTP headers associated with this response. Unlike+ * [response.allHeaders()](https://playwright.dev/docs/api/class-response#response-all-headers), header names are NOT+ * lower-cased. Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple times.*/- next(): Promise<void>;+ headersArray(): Promise<Array<{+ /**+ * Name of the header.+ */+ name: string;++ /**+ * Value of the header.+ */+ value: string;+ }>>;/**- * Returns details about the currently paused call. Returns `null` if the debugger is not paused.+ * Returns the value of the header matching the name. The name is case-insensitive. If multiple headers have the same+ * name (except `set-cookie`), they are returned as a list separated by `, `. For `set-cookie`, the `\n` separator is+ * used. If no headers are found, `null` is returned.+ * @param name Name of the header.*/- pausedDetails(): null|{- location: {- file: string;+ headerValue(name: string): Promise<null|string>;- line?: number;+ /**+ * Returns all values of the headers matching the name, for example `set-cookie`. The name is case-insensitive.+ * @param name Name of the header.+ */+ headerValues(name: string): Promise<Array<string>>;++ /**+ * Returns the http version used by the response.+ */+ httpVersion(): Promise<string>;++ /**+ * Returns the JSON representation of response body.+ *+ * This method will throw if the response body is not parsable via `JSON.parse`.+ */+ json(): Promise<Serializable>;++ /**+ * Contains a boolean stating whether the response was successful (status in the range 200-299) or not.+ */+ ok(): boolean;++ /**+ * Returns the matching [Request](https://playwright.dev/docs/api/class-request) object.+ */+ request(): Request;++ /**+ * Returns SSL and other security information.+ */+ securityDetails(): Promise<null|{+ /**+ * Common Name component of the Issuer field. from the certificate. This should only be used for informational+ * purposes. Optional.+ */+ issuer?: string;++ /**+ * The specific TLS protocol used. (e.g. `TLS 1.3`). Optional.+ */+ protocol?: string;++ /**+ * Common Name component of the Subject field from the certificate. This should only be used for informational+ * purposes. Optional.+ */+ subjectName?: string;++ /**+ * Unix timestamp (in seconds) specifying when this cert becomes valid. Optional.+ */+ validFrom?: number;++ /**+ * Unix timestamp (in seconds) specifying when this cert becomes invalid. Optional.+ */+ validTo?: number;+ }>;- column?: number;- };+ /**+ * Returns the IP address and port of the server.+ */+ serverAddr(): Promise<null|{+ /**+ * IPv4 or IPV6 address of the server.+ */+ ipAddress: string;- title: string;- };+ port: number;+ }>;/**- * Configures the debugger to pause before the next action is executed.- *- * Throws if the debugger is already paused. Use- * [debugger.next()](https://playwright.dev/docs/api/class-debugger#debugger-next) or- * [debugger.runTo(location)](https://playwright.dev/docs/api/class-debugger#debugger-run-to) to step while paused.- *- * Note that [page.pause()](https://playwright.dev/docs/api/class-page#page-pause) is equivalent to a "debugger"- * statement — it pauses execution at the call site immediately. On the contrary,- * [debugger.requestPause()](https://playwright.dev/docs/api/class-debugger#debugger-request-pause) is equivalent to- * "pause on next statement" — it configures the debugger to pause before the next action is executed.+ * Contains the status code of the response (e.g., 200 for a success).*/- requestPause(): Promise<void>;+ status(): number;/**- * Resumes script execution. Throws if the debugger is not paused.+ * Contains the status text of the response (e.g. usually an "OK" for a success).*/- resume(): Promise<void>;+ statusText(): string;/**- * Resumes script execution and pauses when an action originates from the given source location. Throws if the- * debugger is not paused.- * @param location The source location to pause at.+ * Returns the text representation of response body.*/- runTo(location: {- file: string;-- line?: number;+ text(): Promise<string>;- column?: number;- }): Promise<void>;+ /**+ * Contains the URL of the response.+ */+ url(): string;}/**- * [Dialog](https://playwright.dev/docs/api/class-dialog) objects are dispatched by page via the- * [page.on('dialog')](https://playwright.dev/docs/api/class-page#page-event-dialog) event.- *- * An example of using `Dialog` class:- *- * ```js- * const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.- *- * (async () => {- * const browser = await chromium.launch();- * const page = await browser.newPage();- * page.on('dialog', async dialog => {- * console.log(dialog.message());- * await dialog.dismiss();- * });- * await page.evaluate(() => alert('1'));- * await browser.close();- * })();- * ```- *- * **NOTE** Dialogs are dismissed automatically, unless there is a- * [page.on('dialog')](https://playwright.dev/docs/api/class-page#page-event-dialog) listener. When listener is- * present, it **must** either- * [dialog.accept([promptText])](https://playwright.dev/docs/api/class-dialog#dialog-accept) or- * [dialog.dismiss()](https://playwright.dev/docs/api/class-dialog#dialog-dismiss) the dialog - otherwise the page- * will [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the- * dialog, and actions like click will never finish.+ * Whenever a network route is set up with+ * [page.route(url, handler[, options])](https://playwright.dev/docs/api/class-page#page-route) or+ * [browserContext.route(url, handler[, options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-route),+ * the `Route` object allows to handle the route.*+ * Learn more about [networking](https://playwright.dev/docs/network).*/-export interface Dialog {+export interface Route {/**- * Returns when the dialog has been accepted.- * @param promptText A text to enter in prompt. Does not cause any effects if the dialog's `type` is not prompt. Optional.+ * Aborts the route's request.+ * @param errorCode Optional error code. Defaults to `failed`, could be one of the following:+ * - `'aborted'` - An operation was aborted (due to user action)+ * - `'accessdenied'` - Permission to access a resource, other than the network, was denied+ * - `'addressunreachable'` - The IP address is unreachable. This usually means that there is no route to the+ * specified host or network.+ * - `'blockedbyclient'` - The client chose to block the request.+ * - `'blockedbyresponse'` - The request failed because the response was delivered along with requirements which are+ * not met ('X-Frame-Options' and 'Content-Security-Policy' ancestor checks, for instance).+ * - `'connectionaborted'` - A connection timed out as a result of not receiving an ACK for data sent.+ * - `'connectionclosed'` - A connection was closed (corresponding to a TCP FIN).+ * - `'connectionfailed'` - A connection attempt failed.+ * - `'connectionrefused'` - A connection attempt was refused.+ * - `'connectionreset'` - A connection was reset (corresponding to a TCP RST).+ * - `'internetdisconnected'` - The Internet connection has been lost.+ * - `'namenotresolved'` - The host name could not be resolved.+ * - `'timedout'` - An operation timed out.+ * - `'failed'` - A generic failure occurred.*/- accept(promptText?: string): Promise<void>;+ abort(errorCode?: string): Promise<void>;/**- * If dialog is prompt, returns default prompt value. Otherwise, returns empty string.+ * Sends route's request to the network with optional overrides.+ *+ * **Usage**+ *+ * ```js+ * await page.route('**\/*', async (route, request) => {+ * // Override headers+ * const headers = {+ * ...request.headers(),+ * foo: 'foo-value', // set "foo" header+ * bar: undefined, // remove "bar" header+ * };+ * await route.continue({ headers });+ * });+ * ```+ *+ * **Details**+ *+ * The [`headers`](https://playwright.dev/docs/api/class-route#route-continue-option-headers) option applies to both+ * the routed request and any redirects it initiates. However,+ * [`url`](https://playwright.dev/docs/api/class-route#route-continue-option-url),+ * [`method`](https://playwright.dev/docs/api/class-route#route-continue-option-method), and+ * [`postData`](https://playwright.dev/docs/api/class-route#route-continue-option-post-data) only apply to the+ * original request and are not carried over to redirected requests.+ *+ * [route.continue([options])](https://playwright.dev/docs/api/class-route#route-continue) will immediately send the+ * request to the network, other matching handlers won't be invoked. Use+ * [route.fallback([options])](https://playwright.dev/docs/api/class-route#route-fallback) If you want next matching+ * handler in the chain to be invoked.+ *+ * **NOTE** Some request headers are **forbidden** and cannot be overridden (for example, `Cookie`, `Host`,+ * `Content-Length` and others, see+ * [this MDN page](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_request_header) for full list). If an+ * override is provided for a forbidden header, it will be ignored and the original request header will be used.+ *+ * To set custom cookies, use+ * [browserContext.addCookies(cookies)](https://playwright.dev/docs/api/class-browsercontext#browser-context-add-cookies).+ *+ * @param options*/- defaultValue(): string;+ continue(options?: {+ /**+ * If set changes the request HTTP headers. Header values will be converted to a string.+ */+ headers?: { [key: string]: string; };++ /**+ * If set changes the request method (e.g. GET or POST).+ */+ method?: string;++ /**+ * If set changes the post data of request.+ */+ postData?: string|Buffer|Serializable;++ /**+ * If set changes the request URL. New URL must have same protocol as original one.+ */+ url?: string;+ }): Promise<void>;/**- * Returns when the dialog has been dismissed.+ * Continues route's request with optional overrides. The method is similar to+ * [route.continue([options])](https://playwright.dev/docs/api/class-route#route-continue) with the difference that+ * other matching handlers will be invoked before sending the request.+ *+ * **Usage**+ *+ * When several routes match the given pattern, they run in the order opposite to their registration. That way the+ * last registered route can always override all the previous ones. In the example below, request will be handled by+ * the bottom-most handler first, then it'll fall back to the previous one and in the end will be aborted by the first+ * registered route.+ *+ * ```js+ * await page.route('**\/*', async route => {+ * // Runs last.+ * await route.abort();+ * });+ * await page.route('**\/*', async route => {+ * // Runs second.+ * await route.fallback();+ * });+ * await page.route('**\/*', async route => {+ * // Runs first.+ * await route.fallback();+ * });+ * ```+ *+ * Registering multiple routes is useful when you want separate handlers to handle different kinds of requests, for+ * example API calls vs page resources or GET requests vs POST requests as in the example below.+ *+ * ```js+ * // Handle GET requests.+ * await page.route('**\/*', async route => {+ * if (route.request().method() !== 'GET') {+ * await route.fallback();+ * return;+ * }+ * // Handling GET only.+ * // ...+ * });+ *+ * // Handle POST requests.+ * await page.route('**\/*', async route => {+ * if (route.request().method() !== 'POST') {+ * await route.fallback();+ * return;+ * }+ * // Handling POST only.+ * // ...+ * });+ * ```+ *+ * One can also modify request while falling back to the subsequent handler, that way intermediate route handler can+ * modify url, method, headers and postData of the request.+ *+ * ```js+ * await page.route('**\/*', async (route, request) => {+ * // Override headers+ * const headers = {+ * ...request.headers(),+ * foo: 'foo-value', // set "foo" header+ * bar: undefined, // remove "bar" header+ * };+ * await route.fallback({ headers });+ * });+ * ```+ *+ * Use [route.continue([options])](https://playwright.dev/docs/api/class-route#route-continue) to immediately send the+ * request to the network, other matching handlers won't be invoked in that case.+ * @param options*/- dismiss(): Promise<void>;+ fallback(options?: {+ /**+ * If set changes the request HTTP headers. Header values will be converted to a string.+ */+ headers?: { [key: string]: string; };++ /**+ * If set changes the request method (e.g. GET or POST).+ */+ method?: string;++ /**+ * If set changes the post data of request.+ */+ postData?: string|Buffer|Serializable;++ /**+ * If set changes the request URL. New URL must have same protocol as original one. Changing the URL won't affect the+ * route matching, all the routes are matched using the original request URL.+ */+ url?: string;+ }): Promise<void>;/**- * A message displayed in the dialog.+ * Performs the request and fetches result without fulfilling it, so that the response could be modified and then+ * fulfilled.+ *+ * **Usage**+ *+ * ```js+ * await page.route('https://dog.ceo/api/breeds/list/all', async route => {+ * const response = await route.fetch();+ * const json = await response.json();+ * json.message['big_red_dog'] = [];+ * await route.fulfill({ response, json });+ * });+ * ```+ *+ * **Details**+ *+ * Note that [`headers`](https://playwright.dev/docs/api/class-route#route-fetch-option-headers) option will apply to+ * the fetched request as well as any redirects initiated by it. If you want to only apply+ * [`headers`](https://playwright.dev/docs/api/class-route#route-fetch-option-headers) to the original request, but+ * not to redirects, look into [route.continue([options])](https://playwright.dev/docs/api/class-route#route-continue)+ * instead.+ * @param options*/- message(): string;+ fetch(options?: {+ /**+ * If set changes the request HTTP headers. Header values will be converted to a string.+ */+ headers?: { [key: string]: string; };- /**- * The page that initiated this dialog, if available.- */- page(): null|Page;+ /**+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.+ */+ maxRedirects?: number;- /**- * Returns dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`.- */- type(): string;-}+ /**+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.+ */+ maxRetries?: number;-/**- * [Disposable](https://playwright.dev/docs/api/class-disposable) is returned from various methods to allow undoing- * the corresponding action. For example,- * [page.addInitScript(script[, arg])](https://playwright.dev/docs/api/class-page#page-add-init-script) returns a- * [Disposable](https://playwright.dev/docs/api/class-disposable) that can be used to remove the init script.- */-export interface Disposable {- /**- * Removes the associated resource. For example, removes the init script installed via- * [page.addInitScript(script[, arg])](https://playwright.dev/docs/api/class-page#page-add-init-script) or- * [browserContext.addInitScript(script[, arg])](https://playwright.dev/docs/api/class-browsercontext#browser-context-add-init-script).- */- dispose(): Promise<void>;+ /**+ * If set changes the request method (e.g. GET or POST).+ */+ method?: string;- [Symbol.asyncDispose](): Promise<void>;-}+ /**+ * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string+ * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`+ * header will be set to `application/octet-stream` if not explicitly set.+ */+ postData?: string|Buffer|Serializable;-/**- * [Download](https://playwright.dev/docs/api/class-download) objects are dispatched by page via the- * [page.on('download')](https://playwright.dev/docs/api/class-page#page-event-download) event.- *- * All the downloaded files belonging to the browser context are deleted when the browser context is closed.- *- * Download event is emitted once the download starts. Download path becomes available once download completes.- *- * ```js- * // Start waiting for download before clicking. Note no await.- * const downloadPromise = page.waitForEvent('download');- * await page.getByText('Download file').click();- * const download = await downloadPromise;- *- * // Wait for the download process to complete and save the downloaded file somewhere.- * await download.saveAs('/path/to/save/at/' + download.suggestedFilename());- * ```- *- */-export interface Download {- /**- * Cancels a download. Will not fail if the download is already finished or canceled. Upon successful cancellations,- * `download.failure()` would resolve to `'canceled'`.- */- cancel(): Promise<void>;+ /**+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.+ */+ timeout?: number;++ /**+ * If set changes the request URL. New URL must have same protocol as original one.+ */+ url?: string;+ }): Promise<APIResponse>;/**- * Returns a readable stream for a successful download, or throws for a failed/canceled download.+ * Fulfills route's request with given response.*- * **NOTE** If you don't need a readable stream, it's usually simpler to read the file from disk after the download- * completed. See [download.path()](https://playwright.dev/docs/api/class-download#download-path).+ * **Usage**+ *+ * An example of fulfilling all requests with 404 responses:+ *+ * ```js+ * await page.route('**\/*', async route => {+ * await route.fulfill({+ * status: 404,+ * contentType: 'text/plain',+ * body: 'Not Found!'+ * });+ * });+ * ```+ *+ * An example of serving static file:+ *+ * ```js+ * await page.route('**\/xhr_endpoint', route => route.fulfill({ path: 'mock_data.json' }));+ * ```*+ * @param options*/- createReadStream(): Promise<Readable>;+ fulfill(options?: {+ /**+ * Response body.+ */+ body?: string|Buffer;- /**- * Deletes the downloaded file. Will wait for the download to finish if necessary.- */- delete(): Promise<void>;+ /**+ * If set, equals to setting `Content-Type` response header.+ */+ contentType?: string;- /**- * Returns download error if any. Will wait for the download to finish if necessary.- */- failure(): Promise<null|string>;+ /**+ * Response headers. Header values will be converted to a string.+ */+ headers?: { [key: string]: string; };- /**- * Get the page that the download belongs to.- */- page(): Page;+ /**+ * JSON response. This method will set the content type to `application/json` if not set.+ */+ json?: Serializable;++ /**+ * File path to respond with. The content type will be inferred from file extension. If `path` is a relative path,+ * then it is resolved relative to the current working directory.+ */+ path?: string;++ /**+ * [APIResponse](https://playwright.dev/docs/api/class-apiresponse) to fulfill route's request with. Individual fields+ * of the response (such as headers) can be overridden using fulfill options.+ */+ response?: APIResponse;++ /**+ * Response status code, defaults to `200`.+ */+ status?: number;+ }): Promise<void>;/**- * Returns path to the downloaded file for a successful download, or throws for a failed/canceled download. The method- * will wait for the download to finish if necessary. The method throws when connected remotely.- *- * Note that the download's file name is a random GUID, use- * [download.suggestedFilename()](https://playwright.dev/docs/api/class-download#download-suggested-filename) to get- * suggested file name.+ * A request to be routed.*/- path(): Promise<string>;+ request(): Request;+}+/**+ * Selectors can be used to install custom selector engines. See [extensibility](https://playwright.dev/docs/extensibility) for more+ * information.+ */+export interface Selectors {/**- * Copy the download to a user-specified path. It is safe to call this method while the download is still in progress.- * Will wait for the download to finish if necessary.+ * Selectors must be registered before creating the page.** **Usage***+ * An example of registering selector engine that queries elements based on a tag name:+ ** ```js- * await download.saveAs('/path/to/save/at/' + download.suggestedFilename());+ * const { selectors, firefox } = require('@playwright/test'); // Or 'chromium' or 'webkit'.+ *+ * (async () => {+ * // Must be a function that evaluates to a selector engine instance.+ * const createTagNameEngine = () => ({+ * // Returns the first element matching given selector in the root's subtree.+ * query(root, selector) {+ * return root.querySelector(selector);+ * },+ *+ * // Returns all elements matching given selector in the root's subtree.+ * queryAll(root, selector) {+ * return Array.from(root.querySelectorAll(selector));+ * }+ * });+ *+ * // Register the engine. Selectors will be prefixed with "tag=".+ * await selectors.register('tag', createTagNameEngine);+ *+ * const browser = await firefox.launch();+ * const page = await browser.newPage();+ * await page.setContent(`<div><button>Click me</button></div>`);+ *+ * // Use the selector prefixed with its name.+ * const button = page.locator('tag=button');+ * // We can combine it with built-in locators.+ * await page.locator('tag=div').getByText('Click me').click();+ * // Can use it in any methods supporting selectors.+ * const buttonCount = await page.locator('tag=button').count();+ *+ * await browser.close();+ * })();* ```*- * @param path Path where the download should be copied.+ * @param name Name that is used in selectors as a prefix, e.g. `{name: 'foo'}` enables `foo=myselectorbody` selectors. May only+ * contain `[a-zA-Z0-9_]` characters.+ * @param script Script that evaluates to a selector engine instance. The script is evaluated in the page context.+ * @param options*/- saveAs(path: string): Promise<void>;+ register(name: string, script: Function|string|{+ /**+ * Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working+ * directory. Optional.+ */+ path?: string;++ /**+ * Raw script content. Optional.+ */+ content?: string;+ }, options?: {+ /**+ * Whether to run this selector engine in isolated JavaScript environment. This environment has access to the same+ * DOM, but not any JavaScript objects from the frame's scripts. Defaults to `false`. Note that running as a content+ * script is not guaranteed when this engine is used together with other registered engines.+ */+ contentScript?: boolean;+ }): Promise<void>;/**- * Returns suggested filename for this download. It is typically computed by the browser from the- * [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) response- * header or the `download` attribute. See the spec on [whatwg](https://html.spec.whatwg.org/#downloading-resources).- * Different browsers can use different logic for computing it.+ * Defines custom attribute name to be used in+ * [page.getByTestId(testId)](https://playwright.dev/docs/api/class-page#page-get-by-test-id). `data-testid` is used+ * by default.+ * @param attributeName Test id attribute name.*/- suggestedFilename(): string;+ setTestIdAttribute(attributeName: string): void;+}+/**+ * The Touchscreen class operates in main-frame CSS pixels relative to the top-left corner of the viewport. Methods on+ * the touchscreen can only be used in browser contexts that have been initialized with `hasTouch` set to true.+ *+ * This class is limited to emulating tap gestures. For examples of other gestures simulated by manually dispatching+ * touch events, see the [emulating legacy touch events](https://playwright.dev/docs/touch-events) page.+ */+export interface Touchscreen {/**- * Returns downloaded url.+ * Dispatches a `touchstart` and `touchend` event with a single touch at the position+ * ([`x`](https://playwright.dev/docs/api/class-touchscreen#touchscreen-tap-option-x),[`y`](https://playwright.dev/docs/api/class-touchscreen#touchscreen-tap-option-y)).+ *+ * **NOTE** [page.tap(selector[, options])](https://playwright.dev/docs/api/class-page#page-tap) the method will throw+ * if [`hasTouch`](https://playwright.dev/docs/api/class-browser#browser-new-context-option-has-touch) option of the+ * browser context is false.+ *+ * @param x X coordinate relative to the main frame's viewport in CSS pixels.+ * @param y Y coordinate relative to the main frame's viewport in CSS pixels.*/- url(): string;+ tap(x: number, y: number): Promise<void>;}/**- * [FileChooser](https://playwright.dev/docs/api/class-filechooser) objects are dispatched by the page in the- * [page.on('filechooser')](https://playwright.dev/docs/api/class-page#page-event-file-chooser) event.+ * API for collecting and saving Playwright traces. Playwright traces can be opened in+ * [Trace Viewer](https://playwright.dev/docs/trace-viewer) after Playwright script runs.+ *+ * **NOTE** You probably want to+ * [enable tracing in your config file](https://playwright.dev/docs/api/class-testoptions#test-options-trace) instead+ * of using `context.tracing`.+ *+ * The `context.tracing` API captures browser operations and network activity, but it doesn't record test assertions+ * (like `expect` calls). We recommend+ * [enabling tracing through Playwright Test configuration](https://playwright.dev/docs/api/class-testoptions#test-options-trace),+ * which includes those assertions and provides a more complete trace for debugging test failures.+ *+ * Start recording a trace before performing actions. At the end, stop tracing and save it to a file.** ```js- * // Start waiting for file chooser before clicking. Note no await.- * const fileChooserPromise = page.waitForEvent('filechooser');- * await page.getByText('Upload file').click();- * const fileChooser = await fileChooserPromise;- * await fileChooser.setFiles(path.join(__dirname, 'myfile.pdf'));+ * const browser = await chromium.launch();+ * const context = await browser.newContext();+ * await context.tracing.start({ screenshots: true, snapshots: true });+ * const page = await context.newPage();+ * await page.goto('https://playwright.dev');+ * expect(page.url()).toBe('https://playwright.dev');+ * await context.tracing.stop({ path: 'trace.zip' });* ```**/-export interface FileChooser {+export interface Tracing {/**- * Returns input element associated with this file chooser.+ * **NOTE** Use `test.step` instead when available.+ *+ * Creates a new group within the trace, assigning any subsequent API calls to this group, until+ * [tracing.groupEnd()](https://playwright.dev/docs/api/class-tracing#tracing-group-end) is called. Groups can be+ * nested and will be visible in the trace viewer.+ *+ * **Usage**+ *+ * ```js+ * // use test.step instead+ * await test.step('Log in', async () => {+ * // ...+ * });+ * ```+ *+ * @param name Group name shown in the trace viewer.+ * @param options*/- element(): ElementHandle;+ group(name: string, options?: {+ /**+ * Specifies a custom location for the group to be shown in the trace viewer. Defaults to the location of the+ * [tracing.group(name[, options])](https://playwright.dev/docs/api/class-tracing#tracing-group) call.+ */+ location?: {+ file: string;- /**- * Returns whether this file chooser accepts multiple files.- */- isMultiple(): boolean;+ line?: number;++ column?: number;+ };+ }): Promise<Disposable>;/**- * Returns page this file chooser belongs to.+ * Closes the last group created by+ * [tracing.group(name[, options])](https://playwright.dev/docs/api/class-tracing#tracing-group).*/- page(): Page;+ groupEnd(): Promise<void>;/**- * Sets the value of the file input this chooser is associated with. If some of the `filePaths` are relative paths,- * then they are resolved relative to the current working directory. For empty array, clears the selected files.- * @param files+ * Start tracing.+ *+ * **NOTE** You probably want to+ * [enable tracing in your config file](https://playwright.dev/docs/api/class-testoptions#test-options-trace) instead+ * of using `Tracing.start`.+ *+ * The `context.tracing` API captures browser operations and network activity, but it doesn't record test assertions+ * (like `expect` calls). We recommend+ * [enabling tracing through Playwright Test configuration](https://playwright.dev/docs/api/class-testoptions#test-options-trace),+ * which includes those assertions and provides a more complete trace for debugging test failures.+ *+ * **Usage**+ *+ * ```js+ * await context.tracing.start({ screenshots: true, snapshots: true });+ * const page = await context.newPage();+ * await page.goto('https://playwright.dev');+ * expect(page.url()).toBe('https://playwright.dev');+ * await context.tracing.stop({ path: 'trace.zip' });+ * ```+ ** @param options*/- setFiles(files: string|ReadonlyArray<string>|{+ start(options?: {/**- * File name+ * When enabled, the trace is written to an unarchived file that is updated in real time as actions occur, instead of+ * caching changes and archiving them into a zip file at the end. This is useful for live trace viewing during test+ * execution.*/- name: string;+ live?: boolean;/**- * File type+ * If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the+ * [`tracesDir`](https://playwright.dev/docs/api/class-browsertype#browser-type-launch-option-traces-dir) directory+ * specified in+ * [browserType.launch([options])](https://playwright.dev/docs/api/class-browsertype#browser-type-launch). To specify+ * the final trace zip file name, you need to pass `path` option to+ * [tracing.stop([options])](https://playwright.dev/docs/api/class-tracing#tracing-stop) instead.*/- mimeType: string;+ name?: string;/**- * File content- */- buffer: Buffer;- }|ReadonlyArray<{- /**- * File name+ * Whether to capture screenshots during tracing. Screenshots are used to build a timeline preview.*/- name: string;+ screenshots?: boolean;/**- * File type+ * If this option is true tracing will+ * - capture DOM snapshot on every action+ * - record network activity*/- mimeType: string;+ snapshots?: boolean;/**- * File content- */- buffer: Buffer;- }>, options?: {- /**- * This option has no effect.- * @deprecated This option has no effect.+ * Whether to include source files for trace actions.*/- noWaitAfter?: boolean;+ sources?: boolean;/**- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`- * option in the config, or by using the- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.+ * Trace name to be shown in the Trace Viewer.*/- timeout?: number;+ title?: string;}): Promise<void>;-}--/**- * FrameLocator represents a view to the `iframe` on the page. It captures the logic sufficient to retrieve the- * `iframe` and locate elements in that iframe. FrameLocator can be created with either- * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame),- * [page.frameLocator(selector)](https://playwright.dev/docs/api/class-page#page-frame-locator) or- * [locator.frameLocator(selector)](https://playwright.dev/docs/api/class-locator#locator-frame-locator) method.- *- * ```js- * const locator = page.locator('#my-frame').contentFrame().getByText('Submit');- * await locator.click();- * ```- *- * **Strictness**- *- * Frame locators are strict. This means that all operations on frame locators will throw if more than one element- * matches a given selector.- *- * ```js- * // Throws if there are several frames in DOM:- * await page.locator('.result-frame').contentFrame().getByRole('button').click();- *- * // Works because we explicitly tell locator to pick the first frame:- * await page.locator('.result-frame').contentFrame().first().getByRole('button').click();- * ```- *- * **Converting Locator to FrameLocator**- *- * If you have a [Locator](https://playwright.dev/docs/api/class-locator) object pointing to an `iframe` it can be- * converted to [FrameLocator](https://playwright.dev/docs/api/class-framelocator) using- * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame).- *- * **Converting FrameLocator to Locator**- *- * If you have a [FrameLocator](https://playwright.dev/docs/api/class-framelocator) object it can be converted to- * [Locator](https://playwright.dev/docs/api/class-locator) pointing to the same `iframe` using- * [frameLocator.owner()](https://playwright.dev/docs/api/class-framelocator#frame-locator-owner).- */-export interface FrameLocator {- /**- * Returns locator to the first matching frame.- * @deprecated Use [locator.first()](https://playwright.dev/docs/api/class-locator#locator-first) followed by- * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame) instead.- */- first(): FrameLocator;-- /**- * When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements- * in that iframe.- * @param selector A selector to use when resolving DOM element.- */- frameLocator(selector: string): FrameLocator;-- /**- * Allows locating elements by their alt text.- *- * **Usage**- *- * For example, this method will find the image by alt text "Playwright logo":- *- * ```html- * <img alt='Playwright logo'>- * ```- *- * ```js- * await page.getByAltText('Playwright logo').click();- * ```- *- * @param text Text to locate the element for.- * @param options- */- getByAltText(text: string|RegExp, options?: {- /**- * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a- * regular expression. Note that exact match still trims whitespace.- */- exact?: boolean;- }): Locator;/**- * Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the- * `aria-label` attribute.+ * Start a new trace chunk. If you'd like to record multiple traces on the same+ * [BrowserContext](https://playwright.dev/docs/api/class-browsercontext), use+ * [tracing.start([options])](https://playwright.dev/docs/api/class-tracing#tracing-start) once, and then create+ * multiple trace chunks with+ * [tracing.startChunk([options])](https://playwright.dev/docs/api/class-tracing#tracing-start-chunk) and+ * [tracing.stopChunk([options])](https://playwright.dev/docs/api/class-tracing#tracing-stop-chunk).** **Usage***- * For example, this method will find inputs by label "Username" and "Password" in the following DOM:+ * ```js+ * await context.tracing.start({ screenshots: true, snapshots: true });+ * const page = await context.newPage();+ * await page.goto('https://playwright.dev');*- * ```html- * <input aria-label="Username">- * <label for="password-input">Password:</label>- * <input id="password-input">- * ```+ * await context.tracing.startChunk();+ * await page.getByText('Get Started').click();+ * // Everything between startChunk and stopChunk will be recorded in the trace.+ * await context.tracing.stopChunk({ path: 'trace1.zip' });*- * ```js- * await page.getByLabel('Username').fill('john');- * await page.getByLabel('Password').fill('secret');+ * await context.tracing.startChunk();+ * await page.goto('http://example.com');+ * // Save a second trace file with different actions.+ * await context.tracing.stopChunk({ path: 'trace2.zip' });* ```*- * @param text Text to locate the element for.* @param options*/- getByLabel(text: string|RegExp, options?: {+ startChunk(options?: {/**- * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a- * regular expression. Note that exact match still trims whitespace.+ * If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the+ * [`tracesDir`](https://playwright.dev/docs/api/class-browsertype#browser-type-launch-option-traces-dir) directory+ * specified in+ * [browserType.launch([options])](https://playwright.dev/docs/api/class-browsertype#browser-type-launch). To specify+ * the final trace zip file name, you need to pass `path` option to+ * [tracing.stopChunk([options])](https://playwright.dev/docs/api/class-tracing#tracing-stop-chunk) instead.*/- exact?: boolean;- }): Locator;+ name?: string;++ /**+ * Trace name to be shown in the Trace Viewer.+ */+ title?: string;+ }): Promise<void>;/**- * Allows locating input elements by the placeholder text.- *- * **Usage**- *- * For example, consider the following DOM structure.+ * Start recording a HAR (HTTP Archive) of network activity in this context. The HAR file is written to disk when+ * [tracing.stopHar()](https://playwright.dev/docs/api/class-tracing#tracing-stop-har) is called, or when the returned+ * [Disposable](https://playwright.dev/docs/api/class-disposable) is disposed.*- * ```html- * <input type="email" placeholder="[email protected]" />- * ```+ * Only one HAR recording can be active at a time per+ * [BrowserContext](https://playwright.dev/docs/api/class-browsercontext).*- * You can fill the input after locating it by the placeholder text:+ * **Usage**** ```js- * await page- * .getByPlaceholder('[email protected]')- * .fill('[email protected]');+ * await context.tracing.startHar('trace.har');+ * const page = await context.newPage();+ * await page.goto('https://playwright.dev');+ * await context.tracing.stopHar();* ```*- * @param text Text to locate the element for.+ * @param path Path on the filesystem to write the HAR file to. If the file name ends with `.zip`, the HAR is saved as a zip+ * archive with response bodies attached as separate files.* @param options*/- getByPlaceholder(text: string|RegExp, options?: {+ startHar(path: string, options?: {/**- * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a- * regular expression. Note that exact match still trims whitespace.+ * Optional setting to control resource content management. If `omit` is specified, content is not persisted. If+ * `attach` is specified, resources are persisted as separate files or entries in the ZIP archive. If `embed` is+ * specified, content is stored inline the HAR file as per HAR specification. Defaults to `attach` for `.zip` output+ * files and to `embed` for all other file extensions.*/- exact?: boolean;- }): Locator;+ content?: "omit"|"embed"|"attach";++ /**+ * When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,+ * cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.+ */+ mode?: "full"|"minimal";++ /**+ * Only used together with `content: 'attach'`. When set, response bodies are placed in this directory instead of next+ * to the HAR file. Not compatible with a `.zip` HAR file.+ */+ resourcesDir?: string;++ /**+ * A glob or regex pattern to filter requests that are stored in the HAR. Defaults to none.+ */+ urlFilter?: string|RegExp;+ }): Promise<Disposable>;/**- * Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),- * [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and- * [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).- *- * **Usage**- *- * Consider the following DOM structure.- *- * ```html- * <h3>Sign up</h3>- * <label>- * <input type="checkbox" /> Subscribe- * </label>- * <br/>- * <button>Submit</button>- * ```- *- * You can locate each element by its implicit role:- *- * ```js- * await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible();- *- * await page.getByRole('checkbox', { name: 'Subscribe' }).check();- *- * await page.getByRole('button', { name: /submit/i }).click();- * ```- *- * **Details**- *- * Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback- * about the ARIA guidelines.- *- * Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)- * that is recognized by the role selector. You can find all the- * [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**- * duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.- * @param role Required aria role.+ * Stop tracing.* @param options*/- getByRole(role: "alert"|"alertdialog"|"application"|"article"|"banner"|"blockquote"|"button"|"caption"|"cell"|"checkbox"|"code"|"columnheader"|"combobox"|"complementary"|"contentinfo"|"definition"|"deletion"|"dialog"|"directory"|"document"|"emphasis"|"feed"|"figure"|"form"|"generic"|"grid"|"gridcell"|"group"|"heading"|"img"|"insertion"|"link"|"list"|"listbox"|"listitem"|"log"|"main"|"marquee"|"math"|"meter"|"menu"|"menubar"|"menuitem"|"menuitemcheckbox"|"menuitemradio"|"navigation"|"none"|"note"|"option"|"paragraph"|"presentation"|"progressbar"|"radio"|"radiogroup"|"region"|"row"|"rowgroup"|"rowheader"|"scrollbar"|"search"|"searchbox"|"separator"|"slider"|"spinbutton"|"status"|"strong"|"subscript"|"superscript"|"switch"|"tab"|"table"|"tablist"|"tabpanel"|"term"|"textbox"|"time"|"timer"|"toolbar"|"tooltip"|"tree"|"treegrid"|"treeitem", options?: {+ stop(options?: {/**- * An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.- *- * Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).+ * Export trace into the file with the given path.*/- checked?: boolean;+ path?: string;+ }): Promise<void>;+ /**+ * Stop the trace chunk. See+ * [tracing.startChunk([options])](https://playwright.dev/docs/api/class-tracing#tracing-start-chunk) for more details+ * about multiple trace chunks.+ * @param options+ */+ stopChunk(options?: {/**- * Option to match the [accessible description](https://w3c.github.io/accname/#dfn-accessible-description). By- * default, matching is case-insensitive and searches for a substring, use- * [`exact`](https://playwright.dev/docs/api/class-framelocator#frame-locator-get-by-role-option-exact) to control- * this behavior.- *- * Learn more about [accessible description](https://w3c.github.io/accname/#dfn-accessible-description).+ * Export trace collected since the last+ * [tracing.startChunk([options])](https://playwright.dev/docs/api/class-tracing#tracing-start-chunk) call into the+ * file with the given path.*/- description?: string|RegExp;+ path?: string;+ }): Promise<void>;++ /**+ * Stop HAR recording and save the HAR file to the path given to+ * [tracing.startHar(path[, options])](https://playwright.dev/docs/api/class-tracing#tracing-start-har).+ */+ stopHar(): Promise<void>;+}++/**+ * When browser context is created with the `recordVideo` option, each page has a video object associated with it.+ *+ * ```js+ * console.log(await page.video().path());+ * ```+ *+ */+export interface Video {+ /**+ * Deletes the video file. Will wait for the video to finish if necessary.+ */+ delete(): Promise<void>;++ /**+ * Returns the file system path this video will be recorded to. The video is guaranteed to be written to the+ * filesystem upon closing the browser context. This method throws when connected remotely.+ */+ path(): Promise<string>;++ /**+ * Saves the video to a user-specified path. It is safe to call this method while the video is still in progress, or+ * after the page has closed. This method waits until the page is closed and the video is fully saved.+ * @param path Path where the video should be saved.+ */+ saveAs(path: string): Promise<void>;+}++/**+ * [WebError](https://playwright.dev/docs/api/class-weberror) class represents an unhandled exception thrown in the+ * page. It is dispatched via the+ * [browserContext.on('weberror')](https://playwright.dev/docs/api/class-browsercontext#browser-context-event-web-error)+ * event.+ *+ * ```js+ * // Log all uncaught errors to the terminal+ * context.on('weberror', webError => {+ * console.log(`Uncaught exception: "${webError.error()}"`);+ * });+ *+ * // Navigate to a page with an exception.+ * await page.goto('data:text/html,<script>throw new Error("Test")</script>');+ * ```+ *+ */+export interface WebError {+ /**+ * Unhandled error that was thrown.+ */+ error(): Error;++ location(): {+ /**+ * URL of the resource.+ */+ url: string;++ /**+ * 0-based line number in the resource.+ */+ line: number;++ /**+ * 0-based column number in the resource.+ */+ column: number;+ };++ /**+ * The page that produced this unhandled exception, if any.+ */+ page(): null|Page;+}++/**+ * The [WebSocket](https://playwright.dev/docs/api/class-websocket) class represents WebSocket connections within a+ * page. It provides the ability to inspect and manipulate the data being transmitted and received.+ *+ * If you want to intercept or modify WebSocket frames, consider using+ * [WebSocketRoute](https://playwright.dev/docs/api/class-websocketroute).+ */+export interface WebSocket {+ /**+ * Fired when the websocket closes.+ */+ on(event: 'close', listener: (webSocket: WebSocket) => any): this;+ /**+ * Fired when the websocket receives a frame.+ */+ on(event: 'framereceived', listener: (data: {/**- * An attribute that is usually set by `aria-disabled` or `disabled`.- *- * **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about- * [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).- *+ * frame payload*/- disabled?: boolean;+ payload: string|Buffer;+ }) => any): this;+ /**+ * Fired when the websocket sends a frame.+ */+ on(event: 'framesent', listener: (data: {/**- * Whether [`name`](https://playwright.dev/docs/api/class-framelocator#frame-locator-get-by-role-option-name) and- * [`description`](https://playwright.dev/docs/api/class-framelocator#frame-locator-get-by-role-option-description)- * are matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when the value is a regular- * expression. Note that exact match still trims whitespace.+ * frame payload*/- exact?: boolean;+ payload: string|Buffer;+ }) => any): this;+ /**+ * Fired when the websocket has an error.+ */+ on(event: 'socketerror', listener: (string: string) => any): this;++ /**+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ */+ once(event: 'close', listener: (webSocket: WebSocket) => any): this;++ /**+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ */+ once(event: 'framereceived', listener: (data: {/**- * An attribute that is usually set by `aria-expanded`.- *- * Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).+ * frame payload*/- expanded?: boolean;+ payload: string|Buffer;+ }) => any): this;+ /**+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ */+ once(event: 'framesent', listener: (data: {/**- * Option that controls whether hidden elements are matched. By default, only non-hidden elements, as- * [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.- *- * Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).+ * frame payload*/- includeHidden?: boolean;+ payload: string|Buffer;+ }) => any): this;++ /**+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ */+ once(event: 'socketerror', listener: (string: string) => any): this;++ /**+ * Fired when the websocket closes.+ */+ addListener(event: 'close', listener: (webSocket: WebSocket) => any): this;+ /**+ * Fired when the websocket receives a frame.+ */+ addListener(event: 'framereceived', listener: (data: {/**- * A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values- * for `<h1>-<h6>` elements.- *- * Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).+ * frame payload*/- level?: number;+ payload: string|Buffer;+ }) => any): this;+ /**+ * Fired when the websocket sends a frame.+ */+ addListener(event: 'framesent', listener: (data: {/**- * Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is- * case-insensitive and searches for a substring, use- * [`exact`](https://playwright.dev/docs/api/class-framelocator#frame-locator-get-by-role-option-exact) to control- * this behavior.- *- * Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).+ * frame payload*/- name?: string|RegExp;+ payload: string|Buffer;+ }) => any): this;++ /**+ * Fired when the websocket has an error.+ */+ addListener(event: 'socketerror', listener: (string: string) => any): this;++ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ removeListener(event: 'close', listener: (webSocket: WebSocket) => any): this;+ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ removeListener(event: 'framereceived', listener: (data: {/**- * An attribute that is usually set by `aria-pressed`.- *- * Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).+ * frame payload*/- pressed?: boolean;+ payload: string|Buffer;+ }) => any): this;+ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ removeListener(event: 'framesent', listener: (data: {/**- * An attribute that is usually set by `aria-selected`.- *- * Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).+ * frame payload*/- selected?: boolean;- }): Locator;+ payload: string|Buffer;+ }) => any): this;/**- * Locate element by the test id.- *- * **Usage**- *- * Consider the following DOM structure.- *- * ```html- * <button data-testid="directions">Itinéraire</button>- * ```- *- * You can locate the element by its test id:- *- * ```js- * await page.getByTestId('directions').click();- * ```- *- * **Details**- *- * By default, the `data-testid` attribute is used as a test id. Use- * [selectors.setTestIdAttribute(attributeName)](https://playwright.dev/docs/api/class-selectors#selectors-set-test-id-attribute)- * to configure a different test id attribute if necessary.- *- * ```js- * // Set custom test id attribute from @playwright/test config:- * import { defineConfig } from '@playwright/test';- *- * export default defineConfig({- * use: {- * testIdAttribute: 'data-pw'- * },- * });- * ```- *- * @param testId Id to locate the element by.+ * Removes an event listener added by `on` or `addListener`.*/- getByTestId(testId: string|RegExp): Locator;+ removeListener(event: 'socketerror', listener: (string: string) => any): this;/**- * Allows locating elements that contain given text.- *- * See also [locator.filter([options])](https://playwright.dev/docs/api/class-locator#locator-filter) that allows to- * match by another criteria, like an accessible role, and then filter by the text content.- *- * **Usage**- *- * Consider the following DOM structure:- *- * ```html- * <div>Hello <span>world</span></div>- * <div>Hello</div>- * ```- *- * You can locate by text substring, exact string, or a regular expression:- *- * ```js- * // Matches <span>- * page.getByText('world');- *- * // Matches first <div>- * page.getByText('Hello world');- *- * // Matches second <div>- * page.getByText('Hello', { exact: true });- *- * // Matches both <div>s- * page.getByText(/Hello/);- *- * // Matches second <div>- * page.getByText(/^hello$/i);- * ```- *- * **Details**- *- * Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into- * one, turns line breaks into spaces and ignores leading and trailing whitespace.- *- * Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For- * example, locating by text `"Log in"` matches `<input type=button value="Log in">`.- * @param text Text to locate the element for.- * @param options+ * Removes an event listener added by `on` or `addListener`.*/- getByText(text: string|RegExp, options?: {+ off(event: 'close', listener: (webSocket: WebSocket) => any): this;++ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ off(event: 'framereceived', listener: (data: {/**- * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a- * regular expression. Note that exact match still trims whitespace.+ * frame payload*/- exact?: boolean;- }): Locator;+ payload: string|Buffer;+ }) => any): this;/**- * Allows locating elements by their title attribute.- *- * **Usage**- *- * Consider the following DOM structure.- *- * ```html- * <span title='Issues count'>25 issues</span>- * ```- *- * You can check the issues count after locating it by the title text:- *- * ```js- * await expect(page.getByTitle('Issues count')).toHaveText('25 issues');- * ```- *- * @param text Text to locate the element for.- * @param options+ * Removes an event listener added by `on` or `addListener`.*/- getByTitle(text: string|RegExp, options?: {+ off(event: 'framesent', listener: (data: {/**- * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a- * regular expression. Note that exact match still trims whitespace.+ * frame payload*/- exact?: boolean;- }): Locator;+ payload: string|Buffer;+ }) => any): this;/**- * Returns locator to the last matching frame.- * @deprecated Use [locator.last()](https://playwright.dev/docs/api/class-locator#locator-last) followed by- * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame) instead.+ * Removes an event listener added by `on` or `addListener`.*/- last(): FrameLocator;+ off(event: 'socketerror', listener: (string: string) => any): this;/**- * The method finds an element matching the specified selector in the locator's subtree. It also accepts filter- * options, similar to [locator.filter([options])](https://playwright.dev/docs/api/class-locator#locator-filter)- * method.- *- * [Learn more about locators](https://playwright.dev/docs/locators).- * @param selectorOrLocator A selector or locator to use when resolving DOM element.- * @param options+ * Fired when the websocket closes.*/- locator(selectorOrLocator: string|Locator, options?: {- /**- * Narrows down the results of the method to those which contain elements matching this relative locator. For example,- * `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.- *- * Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not- * the document root. For example, you can find `content` that has `div` in- * `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article- * div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.- *- * Note that outer and inner locators must belong to the same frame. Inner locator must not contain- * [FrameLocator](https://playwright.dev/docs/api/class-framelocator)s.- */- has?: Locator;-- /**- * Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the- * outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.- *- * Note that outer and inner locators must belong to the same frame. Inner locator must not contain- * [FrameLocator](https://playwright.dev/docs/api/class-framelocator)s.- */- hasNot?: Locator;+ prependListener(event: 'close', listener: (webSocket: WebSocket) => any): this;+ /**+ * Fired when the websocket receives a frame.+ */+ prependListener(event: 'framereceived', listener: (data: {/**- * Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.- * When passed a [string], matching is case-insensitive and searches for a substring.+ * frame payload*/- hasNotText?: string|RegExp;+ payload: string|Buffer;+ }) => any): this;+ /**+ * Fired when the websocket sends a frame.+ */+ prependListener(event: 'framesent', listener: (data: {/**- * Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When- * passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches- * `<article><div>Playwright</div></article>`.+ * frame payload*/- hasText?: string|RegExp;- }): Locator;+ payload: string|Buffer;+ }) => any): this;/**- * Returns locator to the n-th matching frame. It's zero based, `nth(0)` selects the first frame.- * @deprecated Use [locator.nth(index)](https://playwright.dev/docs/api/class-locator#locator-nth) followed by- * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame) instead.- * @param index+ * Fired when the websocket has an error.*/- nth(index: number): FrameLocator;+ prependListener(event: 'socketerror', listener: (string: string) => any): this;/**- * Returns a [Locator](https://playwright.dev/docs/api/class-locator) object pointing to the same `iframe` as this- * frame locator.- *- * Useful when you have a [FrameLocator](https://playwright.dev/docs/api/class-framelocator) object obtained- * somewhere, and later on would like to interact with the `iframe` element.- *- * For a reverse operation, use- * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame).- *- * **Usage**- *- * ```js- * const frameLocator = page.locator('iframe[name="embedded"]').contentFrame();- * // ...- * const locator = frameLocator.owner();- * await expect(locator).toBeVisible();- * ```- *+ * Indicates that the web socket has been closed.*/- owner(): Locator;-}+ isClosed(): boolean;-/**- * Keyboard provides an api for managing a virtual keyboard. The high level api is- * [keyboard.type(text[, options])](https://playwright.dev/docs/api/class-keyboard#keyboard-type), which takes raw- * characters and generates proper `keydown`, `keypress`/`input`, and `keyup` events on your page.- *- * For finer control, you can use [keyboard.down(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-down),- * [keyboard.up(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-up), and- * [keyboard.insertText(text)](https://playwright.dev/docs/api/class-keyboard#keyboard-insert-text) to manually fire- * events as if they were generated from a real keyboard.- *- * An example of holding down `Shift` in order to select and delete some text:- *- * ```js- * await page.keyboard.type('Hello World!');- * await page.keyboard.press('ArrowLeft');- *- * await page.keyboard.down('Shift');- * for (let i = 0; i < ' World'.length; i++)- * await page.keyboard.press('ArrowLeft');- * await page.keyboard.up('Shift');- *- * await page.keyboard.press('Backspace');- * // Result text will end up saying 'Hello!'- * ```- *- * An example of pressing uppercase `A`- *- * ```js- * await page.keyboard.press('Shift+KeyA');- * // or- * await page.keyboard.press('Shift+A');- * ```- *- * An example to trigger select-all with the keyboard- *- * ```js- * await page.keyboard.press('ControlOrMeta+A');- * ```- *- */-export interface Keyboard {/**- * Dispatches a `keydown` event.- *- * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-down-option-key) can specify the intended- * [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character- * to generate the text for. A superset of the- * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-down-option-key) values can be found- * [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:- *- * `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,- * `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,- * etc.- *- * Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,- * `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.- *- * Holding down `Shift` will type the text that corresponds to the- * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-down-option-key) in the upper case.- *- * If [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-down-option-key) is a single character, it is- * case-sensitive, so the values `a` and `A` will generate different respective texts.- *- * If [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-down-option-key) is a modifier key, `Shift`,- * `Meta`, `Control`, or `Alt`, subsequent key presses will be sent with that modifier active. To release the modifier- * key, use [keyboard.up(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-up).- *- * After the key is pressed once, subsequent calls to- * [keyboard.down(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-down) will have- * [repeat](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat) set to true. To release the key,- * use [keyboard.up(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-up).- *- * **NOTE** Modifier keys DO influence `keyboard.down`. Holding down `Shift` will type the text in upper case.- *- * @param key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.+ * Contains the URL of the WebSocket.*/- down(key: string): Promise<void>;+ url(): string;/**- * Dispatches only `input` event, does not emit the `keydown`, `keyup` or `keypress` events.- *- * **Usage**- *- * ```js- * page.keyboard.insertText('嗨');- * ```- *- * **NOTE** Modifier keys DO NOT effect `keyboard.insertText`. Holding down `Shift` will not type the text in upper- * case.- *- * @param text Sets input to the specified text value.+ * Fired when the websocket closes.*/- insertText(text: string): Promise<void>;+ waitForEvent(event: 'close', optionsOrPredicate?: { predicate?: (webSocket: WebSocket) => boolean | Promise<boolean>, timeout?: number } | ((webSocket: WebSocket) => boolean | Promise<boolean>)): Promise<WebSocket>;/**- * **NOTE** In most cases, you should use- * [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press) instead.- *- * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-press-option-key) can specify the intended- * [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character- * to generate the text for. A superset of the- * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-press-option-key) values can be found- * [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:- *- * `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,- * `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,- * etc.- *- * Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,- * `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.- *- * Holding down `Shift` will type the text that corresponds to the- * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-press-option-key) in the upper case.- *- * If [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-press-option-key) is a single character, it is- * case-sensitive, so the values `a` and `A` will generate different respective texts.- *- * Shortcuts such as `key: "Control+o"`, `key: "Control++` or `key: "Control+Shift+T"` are supported as well. When- * specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.- *- * **Usage**- *- * ```js- * const page = await browser.newPage();- * await page.goto('https://keycode.info');- * await page.keyboard.press('A');- * await page.screenshot({ path: 'A.png' });- * await page.keyboard.press('ArrowLeft');- * await page.screenshot({ path: 'ArrowLeft.png' });- * await page.keyboard.press('Shift+O');- * await page.screenshot({ path: 'O.png' });- * await browser.close();- * ```- *- * Shortcut for [keyboard.down(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-down) and- * [keyboard.up(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-up).- * @param key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.- * @param options+ * Fired when the websocket receives a frame.*/- press(key: string, options?: {+ waitForEvent(event: 'framereceived', optionsOrPredicate?: { predicate?: (data: {/**- * Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.- */- delay?: number;- }): Promise<void>;-- /**- * **NOTE** In most cases, you should use- * [locator.fill(value[, options])](https://playwright.dev/docs/api/class-locator#locator-fill) instead. You only need- * to press keys one by one if there is special keyboard handling on the page - in this case use- * [locator.pressSequentially(text[, options])](https://playwright.dev/docs/api/class-locator#locator-press-sequentially).- *- * Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text.- *- * To press a special key, like `Control` or `ArrowDown`, use- * [keyboard.press(key[, options])](https://playwright.dev/docs/api/class-keyboard#keyboard-press).- *- * **Usage**- *- * ```js- * await page.keyboard.type('Hello'); // Types instantly- * await page.keyboard.type('World', { delay: 100 }); // Types slower, like a user- * ```- *- * **NOTE** Modifier keys DO NOT effect `keyboard.type`. Holding down `Shift` will not type the text in upper case.- *- * **NOTE** For characters that are not on a US keyboard, only an `input` event will be sent.- *- * @param text A text to type into a focused element.- * @param options+ * frame payload+ */+ payload: string|Buffer;+ }) => boolean | Promise<boolean>, timeout?: number } | ((data: {+ /**+ * frame payload+ */+ payload: string|Buffer;+ }) => boolean | Promise<boolean>)): Promise<{+ /**+ * frame payload+ */+ payload: string|Buffer;+ }>;++ /**+ * Fired when the websocket sends a frame.*/- type(text: string, options?: {+ waitForEvent(event: 'framesent', optionsOrPredicate?: { predicate?: (data: {/**- * Time to wait between key presses in milliseconds. Defaults to 0.+ * frame payload*/- delay?: number;- }): Promise<void>;+ payload: string|Buffer;+ }) => boolean | Promise<boolean>, timeout?: number } | ((data: {+ /**+ * frame payload+ */+ payload: string|Buffer;+ }) => boolean | Promise<boolean>)): Promise<{+ /**+ * frame payload+ */+ payload: string|Buffer;+ }>;/**- * Dispatches a `keyup` event.- * @param key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.+ * Fired when the websocket has an error.*/- up(key: string): Promise<void>;+ waitForEvent(event: 'socketerror', optionsOrPredicate?: { predicate?: (string: string) => boolean | Promise<boolean>, timeout?: number } | ((string: string) => boolean | Promise<boolean>)): Promise<string>;+}/**- * Playwright generates a lot of logs and they are accessible via the pluggable logger sink.+ * Playwright has **experimental** support for Electron automation, exposed as `_electron`. An example of the Electron+ * automation script would be:** ```js- * const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.+ * import { _electron as electron } from 'playwright';** (async () => {- * const browser = await chromium.launch({- * logger: {- * isEnabled: (name, severity) => name === 'api',- * log: (name, severity, message, args) => console.log(`${name} ${message}`)- * }+ * // Launch Electron app.+ * const electronApp = await electron.launch({ args: ['main.js'] });+ *+ * // Evaluation expression in the Electron context.+ * const appPath = await electronApp.evaluate(async ({ app }) => {+ * // This runs in the main Electron process, parameter here is always+ * // the result of the require('electron') in the main app script.+ * return app.getAppPath();* });- * // ...+ * console.log(appPath);+ *+ * // Get the first window that the app opens, wait if necessary.+ * const window = await electronApp.firstWindow();+ * // Print the title.+ * console.log(await window.title());+ * // Capture a screenshot.+ * await window.screenshot({ path: 'intro.png' });+ * // Direct Electron console to Node terminal.+ * window.on('console', console.log);+ * // Click button.+ * await window.click('text=Click me');+ * // Exit app.+ * await electronApp.close();* })();* ```*- */-export interface Logger {- /**- * Determines whether sink is interested in the logger with the given name and severity.- * @param name logger name- * @param severity- */- isEnabled(name: string, severity: "verbose"|"info"|"warning"|"error"): boolean;-- /**- * @param name logger name- * @param severity- * @param message log message format- * @param args message arguments- * @param hints optional formatting hints- */- log(name: string, severity: "verbose"|"info"|"warning"|"error", message: string|Error, args: ReadonlyArray<Object>, hints: {- /**- * Optional preferred logger color.- */- color?: string;- }): void;-}--/**- * The Mouse class operates in main-frame CSS pixels relative to the top-left corner of the viewport.+ * **Supported Electron versions are:**+ * - v12.2.0++ * - v13.4.0++ * - v14+*- * **NOTE** If you want to debug where the mouse moved, you can use the [Trace viewer](https://playwright.dev/docs/trace-viewer-intro) or- * [Playwright Inspector](https://playwright.dev/docs/running-tests). A red dot showing the location of the mouse will be shown for every- * mouse action.+ * **Known issues:***- * Every `page` object has its own Mouse, accessible with- * [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse).+ * If you are not able to launch Electron and it will end up in timeouts during launch, try the following:+ * - Ensure that `nodeCliInspect`+ * ([FuseV1Options.EnableNodeCliInspectArguments](https://www.electronjs.org/docs/latest/tutorial/fuses#nodecliinspect))+ * fuse is **not** set to `false`.*- * ```js- * // Using ‘page.mouse’ to trace a 100x100 square.- * await page.mouse.move(0, 0);- * await page.mouse.down();- * await page.mouse.move(0, 100);- * await page.mouse.move(100, 100);- * await page.mouse.move(100, 0);- * await page.mouse.move(0, 0);- * await page.mouse.up();- * ```+ * **Migrating from v1.59***- */-export interface Mouse {- /**- * Shortcut for [mouse.move(x, y[, options])](https://playwright.dev/docs/api/class-mouse#mouse-move),- * [mouse.down([options])](https://playwright.dev/docs/api/class-mouse#mouse-down),- * [mouse.up([options])](https://playwright.dev/docs/api/class-mouse#mouse-up).- * @param x X coordinate relative to the main frame's viewport in CSS pixels.- * @param y Y coordinate relative to the main frame's viewport in CSS pixels.- * @param options- */- click(x: number, y: number, options?: {- /**- * Defaults to `left`.- */- button?: "left"|"right"|"middle";-- /**- * defaults to 1. See [UIEvent.detail].- */- clickCount?: number;-- /**- * Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.- */- delay?: number;- }): Promise<void>;-+ * A number of launch options have been removed after v1.59. See below for alternatives.+ * - `recordHar` - use+ * [tracing.startHar(path[, options])](https://playwright.dev/docs/api/class-tracing#tracing-start-har).+ *+ * ```js+ * const electronApp = await electron.launch({ args: ['main.js'] });+ * await electronApp.context().tracing.startHar('network.har');+ * // ... drive the app ...+ * await electronApp.context().tracing.stopHar();+ * await electronApp.close();+ * ```+ *+ * - `recordVideo` - use+ * [screencast.start([options])](https://playwright.dev/docs/api/class-screencast#screencast-start) on each+ * window.+ *+ * ```js+ * const electronApp = await electron.launch({ args: ['main.js'] });+ * const window = await electronApp.firstWindow();+ * await window.screencast.start({ path: 'video.webm' });+ * // ... drive the window ...+ * await window.screencast.stop();+ * await electronApp.close();+ * ```+ *+ * - `colorScheme` - use+ * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) on each window.+ *+ * ```js+ * const window = await electronApp.firstWindow();+ * await window.emulateMedia({ colorScheme: 'dark' });+ * ```+ *+ * - `extraHTTPHeaders` - use+ * [browserContext.setExtraHTTPHeaders(headers)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-extra-http-headers).+ *+ * ```js+ * await electronApp.context().setExtraHTTPHeaders({ 'X-My-Header': 'value' });+ * ```+ *+ * - `geolocation` - use+ * [browserContext.setGeolocation(geolocation)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-geolocation).+ *+ * ```js+ * await electronApp.context().setGeolocation({ latitude: 48.858455, longitude: 2.294474 });+ * ```+ *+ * - `httpCredentials` - use+ * [browserContext.setHTTPCredentials(httpCredentials)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-http-credentials).+ *+ * ```js+ * await electronApp.context().setHTTPCredentials({ username: 'user', password: 'pass' });+ * ```+ *+ * - `offline` - use+ * [browserContext.setOffline(offline)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-offline).+ *+ * ```js+ * await electronApp.context().setOffline(true);+ * ```+ *+ * - `bypassCSP` - disable CSP at the `BrowserWindow` level via Electron's+ * [web preferences](https://www.electronjs.org/docs/latest/api/structures/web-preferences). Note that+ * `webSecurity: false` also disables CORS and the Same-Origin Policy.+ *+ * ```js+ * const win = new BrowserWindow({+ * webPreferences: {+ * webSecurity: false,+ * },+ * });+ * ```+ *+ * - `ignoreHTTPSErrors`+ *+ * There are several ways to relax HTTPS checks in Electron. Pick the one that matches the scope you need.+ *+ * Per-window, allow mixed content through+ * [web preferences](https://www.electronjs.org/docs/latest/api/structures/web-preferences):+ *+ * ```js+ * const win = new BrowserWindow({+ * webPreferences: {+ * allowRunningInsecureContent: true,+ * },+ * });+ * ```+ *+ * Process-wide, ignore certificate errors via Chromium command-line switches (must run before the `ready` event):+ *+ * ```js+ * const { app } = require('electron');+ * app.commandLine.appendSwitch('ignore-certificate-errors');+ * // Optional: also ignore localhost certificate errors when testing on an IP.+ * app.commandLine.appendSwitch('allow-insecure-localhost', 'true');+ * ```+ *+ * Per-request, accept the certificate manually via the+ * [`certificate-error`](https://www.electronjs.org/docs/latest/api/app#event-certificate-error) event:+ *+ * ```js+ * app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {+ * event.preventDefault();+ * callback(true);+ * });+ * ```+ *+ * - `timezoneId` - set an environment variable at the very top of the main file, before any other logic or Chromium+ * windows are initialized.+ *+ * ```js+ * // main.js+ * process.env.TZ = 'Europe/London';+ *+ * const { app } = require('electron');+ * // ... rest of your app logic+ * ```+ *+ */+export interface Electron {/**- * Shortcut for [mouse.move(x, y[, options])](https://playwright.dev/docs/api/class-mouse#mouse-move),- * [mouse.down([options])](https://playwright.dev/docs/api/class-mouse#mouse-down),- * [mouse.up([options])](https://playwright.dev/docs/api/class-mouse#mouse-up),- * [mouse.down([options])](https://playwright.dev/docs/api/class-mouse#mouse-down) and- * [mouse.up([options])](https://playwright.dev/docs/api/class-mouse#mouse-up).- * @param x X coordinate relative to the main frame's viewport in CSS pixels.- * @param y Y coordinate relative to the main frame's viewport in CSS pixels.+ * Launches electron application specified with the+ * [`executablePath`](https://playwright.dev/docs/api/class-electron#electron-launch-option-executable-path).* @param options*/- dblclick(x: number, y: number, options?: {- /**- * Defaults to `left`.- */- button?: "left"|"right"|"middle";-+ launch(options?: {/**- * Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.+ * Additional arguments to pass to the application when launching. You typically pass the main script name here.*/- delay?: number;- }): Promise<void>;+ args?: Array<string>;- /**- * Dispatches a `mousedown` event.- * @param options- */- down(options?: {/**- * Defaults to `left`.+ * Enable Chromium sandboxing. Defaults to `false`.*/- button?: "left"|"right"|"middle";+ chromiumSandbox?: boolean;/**- * defaults to 1. See [UIEvent.detail].+ * Current working directory to launch application from.*/- clickCount?: number;- }): Promise<void>;+ cwd?: string;- /**- * Dispatches a `mousemove` event.- * @param x X coordinate relative to the main frame's viewport in CSS pixels.- * @param y Y coordinate relative to the main frame's viewport in CSS pixels.- * @param options- */- move(x: number, y: number, options?: {/**- * Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor- * position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.+ * Specifies environment variables that will be visible to Electron. Defaults to `process.env`.*/- steps?: number;- }): Promise<void>;+ env?: { [key: string]: string; };- /**- * Dispatches a `mouseup` event.- * @param options- */- up(options?: {/**- * Defaults to `left`.+ * Launches given Electron application. If not specified, launches the default Electron executable installed in this+ * package, located at `node_modules/.bin/electron`.*/- button?: "left"|"right"|"middle";+ executablePath?: string;/**- * defaults to 1. See [UIEvent.detail].+ * Maximum time in milliseconds to wait for the application to start. Defaults to `30000` (30 seconds). Pass `0` to+ * disable timeout.*/- clickCount?: number;- }): Promise<void>;-- /**- * Dispatches a `wheel` event. This method is usually used to manually scroll the page. See- * [scrolling](https://playwright.dev/docs/input#scrolling) for alternative ways to scroll.- *- * **NOTE** Wheel events may cause scrolling if they are not handled, and this method does not wait for the scrolling- * to finish before returning.- *- * @param deltaX Pixels to scroll horizontally.- * @param deltaY Pixels to scroll vertically.- */- wheel(deltaX: number, deltaY: number): Promise<void>;+ timeout?: number;+ }): Promise<ElectronApplication>;}/**- * This object can be used to launch or connect to Chromium, returning instances of- * [Browser](https://playwright.dev/docs/api/class-browser).- */-export const chromium: BrowserType;--/**- * This object can be used to launch or connect to Firefox, returning instances of- * [Browser](https://playwright.dev/docs/api/class-browser).- */-export const firefox: BrowserType;--/**- * Exposes API that can be used for the Web API testing.- */-export const request: APIRequest;--/**- * Selectors can be used to install custom selector engines. See [extensibility](https://playwright.dev/docs/extensibility) for more- * information.- */-export const selectors: Selectors;--/**- * This object can be used to launch or connect to WebKit, returning instances of- * [Browser](https://playwright.dev/docs/api/class-browser).- */-export const webkit: BrowserType;--/**- * Whenever the page sends a request for a network resource the following sequence of events are emitted by- * [Page](https://playwright.dev/docs/api/class-page):- * - [page.on('request')](https://playwright.dev/docs/api/class-page#page-event-request) emitted when the request is- * issued by the page.- * - [page.on('response')](https://playwright.dev/docs/api/class-page#page-event-response) emitted when/if the- * response status and headers are received for the request.- * - [page.on('requestfinished')](https://playwright.dev/docs/api/class-page#page-event-request-finished) emitted- * when the response body is downloaded and the request is complete.+ * Playwright has **experimental** support for Android automation. This includes Chrome for Android and Android+ * WebView.*- * If request fails at some point, then instead of `'requestfinished'` event (and possibly instead of 'response'- * event), the [page.on('requestfailed')](https://playwright.dev/docs/api/class-page#page-event-request-failed) event- * is emitted.+ * *Requirements*+ * - Android device or AVD Emulator.+ * - [ADB daemon](https://developer.android.com/studio/command-line/adb) running and authenticated with your device.+ * Typically running `adb devices` is all you need to do.+ * - [`Chrome 87`](https://play.google.com/store/apps/details?id=com.android.chrome) or newer installed on the+ * device+ * - "Enable command line on non-rooted devices" enabled in `chrome://flags`.*- * **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request- * will complete with `'requestfinished'` event.+ * *Known limitations*+ * - Raw USB operation is not yet supported, so you need ADB.+ * - Device needs to be awake to produce screenshots. Enabling "Stay awake" developer mode will help.+ * - We didn't run all the tests against the device, so not everything works.*- * If request gets a 'redirect' response, the request is successfully finished with the `requestfinished` event, and a- * new request is issued to a redirected url.- */-export interface Request {- /**- * An object with all the request HTTP headers associated with this request. The header names are lower-cased.- */- allHeaders(): Promise<{ [key: string]: string; }>;-- /**- * Returns the [Response](https://playwright.dev/docs/api/class-response) object if the response has already been- * received, `null` otherwise.- *- * Unlike [request.response()](https://playwright.dev/docs/api/class-request#request-response), this method does not- * wait for the response to arrive. It returns immediately with the response object if the response has been received,- * or `null` if the response has not been received yet.- */- existingResponse(): null|Response;-- /**- * The method returns `null` unless this request has failed, as reported by `requestfailed` event.- *- * **Usage**- *- * Example of logging of all the failed requests:- *- * ```js- * page.on('requestfailed', request => {- * console.log(request.url() + ' ' + request.failure().errorText);- * });- * ```- *- */- failure(): null|{- /**- * Human-readable error message, e.g. `'net::ERR_FAILED'`.- */- errorText: string;- };-- /**- * Returns the [Frame](https://playwright.dev/docs/api/class-frame) that initiated this request.- *- * **Usage**- *- * ```js- * const frameUrl = request.frame().url();- * ```- *- * **Details**- *- * Note that in some cases the frame is not available, and this method will throw.- * - When request originates in the Service Worker. You can use `request.serviceWorker()` to check that.- * - When navigation request is issued before the corresponding frame is created. You can use- * [request.isNavigationRequest()](https://playwright.dev/docs/api/class-request#request-is-navigation-request) to- * check that.- *- * Here is an example that handles all the cases:- *- * ```js- * if (request.serviceWorker())- * console.log(`request ${request.url()} from a service worker`);- * else if (request.isNavigationRequest())- * console.log(`request ${request.url()} is a navigation request`);- * else- * console.log(`request ${request.url()} from a frame ${request.frame().url()}`);- * ```- *- */- frame(): Frame;-- /**- * An object with the request HTTP headers. The header names are lower-cased. Note that this method does not return- * security-related headers, including cookie-related ones. You can use- * [request.allHeaders()](https://playwright.dev/docs/api/class-request#request-all-headers) for complete list of- * headers that include `cookie` information.- */- headers(): { [key: string]: string; };-+ * *How to run*+ *+ * An example of the Android automation script would be:+ *+ * ```js+ * const { _android: android } = require('playwright');+ *+ * (async () => {+ * // Connect to the device.+ * const [device] = await android.devices();+ * console.log(`Model: ${device.model()}`);+ * console.log(`Serial: ${device.serial()}`);+ * // Take screenshot of the whole device.+ * await device.screenshot({ path: 'device.png' });+ *+ * {+ * // --------------------- WebView -----------------------+ *+ * // Launch an application with WebView.+ * await device.shell('am force-stop org.chromium.webview_shell');+ * await device.shell('am start org.chromium.webview_shell/.WebViewBrowserActivity');+ * // Get the WebView.+ * const webview = await device.webView({ pkg: 'org.chromium.webview_shell' });+ *+ * // Fill the input box.+ * await device.fill({+ * res: 'org.chromium.webview_shell:id/url_field',+ * }, 'github.com/microsoft/playwright');+ * await device.press({+ * res: 'org.chromium.webview_shell:id/url_field',+ * }, 'Enter');+ *+ * // Work with WebView's page as usual.+ * const page = await webview.page();+ * await page.waitForNavigation({ url: /.*microsoft\/playwright.*\/ });+ * console.log(await page.title());+ * }+ *+ * {+ * // --------------------- Browser -----------------------+ *+ * // Launch Chrome browser.+ * await device.shell('am force-stop com.android.chrome');+ * const context = await device.launchBrowser();+ *+ * // Use BrowserContext as usual.+ * const page = await context.newPage();+ * await page.goto('https://webkit.org/');+ * console.log(await page.evaluate(() => window.location.href));+ * await page.screenshot({ path: 'page.png' });+ *+ * await context.close();+ * }+ *+ * // Close the device.+ * await device.close();+ * })();+ * ```+ *+ */+export interface Android {/**- * An array with all the request HTTP headers associated with this request. Unlike- * [request.allHeaders()](https://playwright.dev/docs/api/class-request#request-all-headers), header names are NOT- * lower-cased. Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple times.+ * This methods attaches Playwright to an existing Android device. Use+ * [android.launchServer([options])](https://playwright.dev/docs/api/class-android#android-launch-server) to launch a+ * new Android server instance.+ * @param endpoint A browser websocket endpoint to connect to.+ * @param options*/- headersArray(): Promise<Array<{+ connect(endpoint: string, options?: {/**- * Name of the header.+ * Additional HTTP headers to be sent with web socket connect request. Optional.*/- name: string;+ headers?: { [key: string]: string; };/**- * Value of the header.+ * Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going+ * on. Defaults to `0`.*/- value: string;- }>>;-- /**- * Returns the value of the header matching the name. The name is case-insensitive.- * @param name Name of the header.- */- headerValue(name: string): Promise<null|string>;-- /**- * Whether this request is driving frame's navigation.- *- * Some navigation requests are issued before the corresponding frame is created, and therefore do not have- * [request.frame()](https://playwright.dev/docs/api/class-request#request-frame) available.- */- isNavigationRequest(): boolean;+ slowMo?: number;- /**- * Request's method (GET, POST, etc.)- */- method(): string;+ /**+ * Maximum time in milliseconds to wait for the connection to be established. Defaults to `30000` (30 seconds). Pass+ * `0` to disable timeout.+ */+ timeout?: number;+ }): Promise<AndroidDevice>;/**- * Request's post body, if any.+ * Returns the list of detected Android devices.+ * @param options*/- postData(): null|string;+ devices(options?: {+ /**+ * Optional host to establish ADB server connection. Default to `127.0.0.1`.+ */+ host?: string;- /**- * Request's post body in a binary form, if any.- */- postDataBuffer(): null|Buffer;+ /**+ * Prevents automatic playwright driver installation on attach. Assumes that the drivers have been installed already.+ */+ omitDriverInstall?: boolean;- /**- * Returns parsed request's body for `form-urlencoded` and JSON as a fallback if any.- *- * When the response is `application/x-www-form-urlencoded` then a key/value object of the values will be returned.- * Otherwise it will be parsed as JSON.- */- postDataJSON(): null|Serializable;+ /**+ * Optional port to establish ADB server connection. Default to `5037`.+ */+ port?: number;+ }): Promise<Array<AndroidDevice>>;/**- * Request that was redirected by the server to this one, if any.- *- * When the server responds with a redirect, Playwright creates a new- * [Request](https://playwright.dev/docs/api/class-request) object. The two requests are connected by- * `redirectedFrom()` and `redirectedTo()` methods. When multiple server redirects has happened, it is possible to- * construct the whole redirect chain by repeatedly calling `redirectedFrom()`.+ * Launches Playwright Android server that clients can connect to. See the following example:** **Usage***- * For example, if the website `http://example.com` redirects to `https://example.com`:+ * Server Side:** ```js- * const response = await page.goto('http://example.com');- * console.log(response.request().redirectedFrom().url()); // 'http://example.com'- * ```- *- * If the website `https://google.com` has no redirects:+ * const { _android } = require('playwright');*- * ```js- * const response = await page.goto('https://google.com');- * console.log(response.request().redirectedFrom()); // null+ * (async () => {+ * const browserServer = await _android.launchServer({+ * // If you have multiple devices connected and want to use a specific one.+ * // deviceSerialNumber: '<deviceSerialNumber>',+ * });+ * const wsEndpoint = browserServer.wsEndpoint();+ * console.log(wsEndpoint);+ * })();* ```*- */- redirectedFrom(): null|Request;-- /**- * New request issued by the browser if the server responded with redirect.- *- * **Usage**- *- * This method is the opposite of- * [request.redirectedFrom()](https://playwright.dev/docs/api/class-request#request-redirected-from):+ * Client Side:** ```js- * console.log(request.redirectedFrom().redirectedTo() === request); // true- * ```- *- */- redirectedTo(): null|Request;-- /**- * Contains the request's resource type as it was perceived by the rendering engine. ResourceType will be one of the- * following: `document`, `stylesheet`, `image`, `media`, `font`, `script`, `texttrack`, `xhr`, `fetch`,- * `eventsource`, `websocket`, `manifest`, `other`.- */- resourceType(): string;-- /**- * Returns the matching [Response](https://playwright.dev/docs/api/class-response) object, or `null` if the response- * was not received due to error.- */- response(): Promise<null|Response>;-- /**- * The Service [Worker](https://playwright.dev/docs/api/class-worker) that is performing the request.- *- * **Details**+ * const { _android } = require('playwright');*- * This method is Chromium only. It's safe to call when using other browsers, but it will always be `null`.+ * (async () => {+ * const device = await _android.connect('<wsEndpoint>');*- * Requests originated in a Service Worker do not have a- * [request.frame()](https://playwright.dev/docs/api/class-request#request-frame) available.- */- serviceWorker(): null|Worker;-- /**- * Returns resource size information for given request.- */- sizes(): Promise<{- /**- * Size of the request body (POST data payload) in bytes. Set to 0 if there was no body.- */- requestBodySize: number;-- /**- * Total number of bytes from the start of the HTTP request message until (and including) the double CRLF before the- * body.- */- requestHeadersSize: number;-- /**- * Size of the received response body (encoded) in bytes.- */- responseBodySize: number;-- /**- * Total number of bytes from the start of the HTTP response message until (and including) the double CRLF before the- * body.- */- responseHeadersSize: number;- }>;-- /**- * Returns resource timing information for given request. Most of the timing values become available upon the- * response, `responseEnd` becomes available when request finishes. Find more information at- * [Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming).+ * console.log(device.model());+ * console.log(device.serial());+ * await device.shell('am force-stop com.android.chrome');+ * const context = await device.launchBrowser();*- * **Usage**+ * const page = await context.newPage();+ * await page.goto('https://webkit.org/');+ * console.log(await page.evaluate(() => window.location.href));+ * await page.screenshot({ path: 'page-chrome-1.png' });*- * ```js- * const requestFinishedPromise = page.waitForEvent('requestfinished');- * await page.goto('http://example.com');- * const request = await requestFinishedPromise;- * console.log(request.timing());+ * await context.close();+ * })();* ```*+ * @param options*/- timing(): {- /**- * Request start time in milliseconds elapsed since January 1, 1970 00:00:00 UTC- */- startTime: number;-- /**- * Time immediately before the browser starts the domain name lookup for the resource. The value is given in- * milliseconds relative to `startTime`, -1 if not available.- */- domainLookupStart: number;-+ launchServer(options?: {/**- * Time immediately after the browser starts the domain name lookup for the resource. The value is given in- * milliseconds relative to `startTime`, -1 if not available.+ * Optional host to establish ADB server connection. Default to `127.0.0.1`.*/- domainLookupEnd: number;+ adbHost?: string;/**- * Time immediately before the user agent starts establishing the connection to the server to retrieve the resource.- * The value is given in milliseconds relative to `startTime`, -1 if not available.+ * Optional port to establish ADB server connection. Default to `5037`.*/- connectStart: number;+ adbPort?: number;/**- * Time immediately before the browser starts the handshake process to secure the current connection. The value is- * given in milliseconds relative to `startTime`, -1 if not available.+ * Optional device serial number to launch the browser on. If not specified, it will throw if multiple devices are+ * connected.*/- secureConnectionStart: number;+ deviceSerialNumber?: string;/**- * Time immediately before the user agent starts establishing the connection to the server to retrieve the resource.- * The value is given in milliseconds relative to `startTime`, -1 if not available.+ * Host to use for the web socket. It is optional and defaults to `localhost`, accepting connections only from the+ * loopback interface. Pass an explicit address (e.g. `0.0.0.0`) to accept connections from the network — be aware+ * this exposes the device RPC to anything that can reach the listening port.*/- connectEnd: number;+ host?: string;/**- * Time immediately before the browser starts requesting the resource from the server, cache, or local resource. The- * value is given in milliseconds relative to `startTime`, -1 if not available.+ * Prevents automatic playwright driver installation on attach. Assumes that the drivers have been installed already.*/- requestStart: number;+ omitDriverInstall?: boolean;/**- * Time immediately after the browser receives the first byte of the response from the server, cache, or local- * resource. The value is given in milliseconds relative to `startTime`, -1 if not available.+ * Port to use for the web socket. Defaults to 0 that picks any available port.*/- responseStart: number;+ port?: number;/**- * Time immediately after the browser receives the last byte of the resource or immediately before the transport- * connection is closed, whichever comes first. The value is given in milliseconds relative to `startTime`, -1 if not- * available.+ * Path at which to serve the Android Server. For security, this defaults to an unguessable string.+ *+ * **NOTE** Any process or web page (including those running in Playwright) with knowledge of the `wsPath` can take+ * control of the OS user. For this reason, you should use an unguessable token when using this option.+ **/- responseEnd: number;- };+ wsPath?: string;+ }): Promise<BrowserServer>;/**- * URL of the request.+ * This setting will change the default maximum time for all the methods accepting+ * [`timeout`](https://playwright.dev/docs/api/class-android#android-set-default-timeout-option-timeout) option.+ * @param timeout Maximum time in milliseconds*/- url(): string;+ setDefaultTimeout(timeout: number): void;}/**- * [Response](https://playwright.dev/docs/api/class-response) class represents responses which are received by page.+ * [AndroidDevice](https://playwright.dev/docs/api/class-androiddevice) represents a connected device, either real+ * hardware or emulated. Devices can be obtained using+ * [android.devices([options])](https://playwright.dev/docs/api/class-android#android-devices).*/-export interface Response {- /**- * An object with all the response HTTP headers associated with this response.- */- allHeaders(): Promise<{ [key: string]: string; }>;-- /**- * Returns the buffer with response body.- */- body(): Promise<Buffer>;-- /**- * Waits for this response to finish, returns always `null`.- */- finished(): Promise<null|Error>;-- /**- * Returns the [Frame](https://playwright.dev/docs/api/class-frame) that initiated this response.- */- frame(): Frame;-- /**- * Indicates whether this Response was fulfilled by a Service Worker's Fetch Handler (i.e. via- * [FetchEvent.respondWith](https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent/respondWith)).- */- fromServiceWorker(): boolean;-- /**- * An object with the response HTTP headers. The header names are lower-cased. Note that this method does not return- * security-related headers, including cookie-related ones. You can use- * [response.allHeaders()](https://playwright.dev/docs/api/class-response#response-all-headers) for complete list of- * headers that include `cookie` information.- */- headers(): { [key: string]: string; };-- /**- * An array with all the request HTTP headers associated with this response. Unlike- * [response.allHeaders()](https://playwright.dev/docs/api/class-response#response-all-headers), header names are NOT- * lower-cased. Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple times.- */- headersArray(): Promise<Array<{- /**- * Name of the header.- */- name: string;-- /**- * Value of the header.- */- value: string;- }>>;-+export interface AndroidDevice {/**- * Returns the value of the header matching the name. The name is case-insensitive. If multiple headers have the same- * name (except `set-cookie`), they are returned as a list separated by `, `. For `set-cookie`, the `\n` separator is- * used. If no headers are found, `null` is returned.- * @param name Name of the header.+ * Emitted when the device connection gets closed.*/- headerValue(name: string): Promise<null|string>;+ on(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;/**- * Returns all values of the headers matching the name, for example `set-cookie`. The name is case-insensitive.- * @param name Name of the header.+ * Emitted when a new WebView instance is detected.*/- headerValues(name: string): Promise<Array<string>>;+ on(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;/**- * Returns the http version used by the response.+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.*/- httpVersion(): Promise<string>;+ once(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;/**- * Returns the JSON representation of response body.- *- * This method will throw if the response body is not parsable via `JSON.parse`.+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.*/- json(): Promise<Serializable>;+ once(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;/**- * Contains a boolean stating whether the response was successful (status in the range 200-299) or not.+ * Emitted when the device connection gets closed.*/- ok(): boolean;+ addListener(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;/**- * Returns the matching [Request](https://playwright.dev/docs/api/class-request) object.+ * Emitted when a new WebView instance is detected.*/- request(): Request;+ addListener(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;/**- * Returns SSL and other security information.+ * Removes an event listener added by `on` or `addListener`.*/- securityDetails(): Promise<null|{- /**- * Common Name component of the Issuer field. from the certificate. This should only be used for informational- * purposes. Optional.- */- issuer?: string;-- /**- * The specific TLS protocol used. (e.g. `TLS 1.3`). Optional.- */- protocol?: string;-- /**- * Common Name component of the Subject field from the certificate. This should only be used for informational- * purposes. Optional.- */- subjectName?: string;-- /**- * Unix timestamp (in seconds) specifying when this cert becomes valid. Optional.- */- validFrom?: number;-- /**- * Unix timestamp (in seconds) specifying when this cert becomes invalid. Optional.- */- validTo?: number;- }>;+ removeListener(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;/**- * Returns the IP address and port of the server.+ * Removes an event listener added by `on` or `addListener`.*/- serverAddr(): Promise<null|{- /**- * IPv4 or IPV6 address of the server.- */- ipAddress: string;-- port: number;- }>;+ removeListener(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;/**- * Contains the status code of the response (e.g., 200 for a success).+ * Removes an event listener added by `on` or `addListener`.*/- status(): number;+ off(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;/**- * Contains the status text of the response (e.g. usually an "OK" for a success).+ * Removes an event listener added by `on` or `addListener`.*/- statusText(): string;+ off(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;/**- * Returns the text representation of response body.+ * Emitted when the device connection gets closed.*/- text(): Promise<string>;+ prependListener(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;/**- * Contains the URL of the response.+ * Emitted when a new WebView instance is detected.*/- url(): string;-}+ prependListener(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;-/**- * Whenever a network route is set up with- * [page.route(url, handler[, options])](https://playwright.dev/docs/api/class-page#page-route) or- * [browserContext.route(url, handler[, options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-route),- * the `Route` object allows to handle the route.- *- * Learn more about [networking](https://playwright.dev/docs/network).- */-export interface Route {/**- * Aborts the route's request.- * @param errorCode Optional error code. Defaults to `failed`, could be one of the following:- * - `'aborted'` - An operation was aborted (due to user action)- * - `'accessdenied'` - Permission to access a resource, other than the network, was denied- * - `'addressunreachable'` - The IP address is unreachable. This usually means that there is no route to the- * specified host or network.- * - `'blockedbyclient'` - The client chose to block the request.- * - `'blockedbyresponse'` - The request failed because the response was delivered along with requirements which are- * not met ('X-Frame-Options' and 'Content-Security-Policy' ancestor checks, for instance).- * - `'connectionaborted'` - A connection timed out as a result of not receiving an ACK for data sent.- * - `'connectionclosed'` - A connection was closed (corresponding to a TCP FIN).- * - `'connectionfailed'` - A connection attempt failed.- * - `'connectionrefused'` - A connection attempt was refused.- * - `'connectionreset'` - A connection was reset (corresponding to a TCP RST).- * - `'internetdisconnected'` - The Internet connection has been lost.- * - `'namenotresolved'` - The host name could not be resolved.- * - `'timedout'` - An operation timed out.- * - `'failed'` - A generic failure occurred.+ * Disconnects from the device.*/- abort(errorCode?: string): Promise<void>;+ close(): Promise<void>;/**- * Sends route's request to the network with optional overrides.- *- * **Usage**- *- * ```js- * await page.route('**\/*', async (route, request) => {- * // Override headers- * const headers = {- * ...request.headers(),- * foo: 'foo-value', // set "foo" header- * bar: undefined, // remove "bar" header- * };- * await route.continue({ headers });- * });- * ```- *- * **Details**- *- * The [`headers`](https://playwright.dev/docs/api/class-route#route-continue-option-headers) option applies to both- * the routed request and any redirects it initiates. However,- * [`url`](https://playwright.dev/docs/api/class-route#route-continue-option-url),- * [`method`](https://playwright.dev/docs/api/class-route#route-continue-option-method), and- * [`postData`](https://playwright.dev/docs/api/class-route#route-continue-option-post-data) only apply to the- * original request and are not carried over to redirected requests.- *- * [route.continue([options])](https://playwright.dev/docs/api/class-route#route-continue) will immediately send the- * request to the network, other matching handlers won't be invoked. Use- * [route.fallback([options])](https://playwright.dev/docs/api/class-route#route-fallback) If you want next matching- * handler in the chain to be invoked.- *- * **NOTE** Some request headers are **forbidden** and cannot be overridden (for example, `Cookie`, `Host`,- * `Content-Length` and others, see- * [this MDN page](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_request_header) for full list). If an- * override is provided for a forbidden header, it will be ignored and the original request header will be used.- *- * To set custom cookies, use- * [browserContext.addCookies(cookies)](https://playwright.dev/docs/api/class-browsercontext#browser-context-add-cookies).- *- * @param options- */- continue(options?: {- /**- * If set changes the request HTTP headers. Header values will be converted to a string.- */- headers?: { [key: string]: string; };+ * Drags the widget defined by+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-drag-option-selector) towards+ * [`dest`](https://playwright.dev/docs/api/class-androiddevice#android-device-drag-option-dest) point.+ * @param selector Selector to drag.+ * @param dest Point to drag to.+ * @param options+ */+ drag(selector: AndroidSelector, dest: {+ x: number;+ y: number;+ }, options?: {/**- * If set changes the request method (e.g. GET or POST).+ * Optional speed of the drag in pixels per second.*/- method?: string;+ speed?: number;/**- * If set changes the post data of request.+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.*/- postData?: string|Buffer|Serializable;+ timeout?: number;+ }): Promise<void>;+ /**+ * Fills the specific+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-fill-option-selector) input box+ * with [`text`](https://playwright.dev/docs/api/class-androiddevice#android-device-fill-option-text).+ * @param selector Selector to fill.+ * @param text Text to be filled in the input box.+ * @param options+ */+ fill(selector: AndroidSelector, text: string, options?: {/**- * If set changes the request URL. New URL must have same protocol as original one.+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.*/- url?: string;+ timeout?: number;}): Promise<void>;/**- * Continues route's request with optional overrides. The method is similar to- * [route.continue([options])](https://playwright.dev/docs/api/class-route#route-continue) with the difference that- * other matching handlers will be invoked before sending the request.- *- * **Usage**- *- * When several routes match the given pattern, they run in the order opposite to their registration. That way the- * last registered route can always override all the previous ones. In the example below, request will be handled by- * the bottom-most handler first, then it'll fall back to the previous one and in the end will be aborted by the first- * registered route.- *- * ```js- * await page.route('**\/*', async route => {- * // Runs last.- * await route.abort();- * });- * await page.route('**\/*', async route => {- * // Runs second.- * await route.fallback();- * });- * await page.route('**\/*', async route => {- * // Runs first.- * await route.fallback();- * });- * ```- *- * Registering multiple routes is useful when you want separate handlers to handle different kinds of requests, for- * example API calls vs page resources or GET requests vs POST requests as in the example below.- *- * ```js- * // Handle GET requests.- * await page.route('**\/*', async route => {- * if (route.request().method() !== 'GET') {- * await route.fallback();- * return;- * }- * // Handling GET only.- * // ...- * });- *- * // Handle POST requests.- * await page.route('**\/*', async route => {- * if (route.request().method() !== 'POST') {- * await route.fallback();- * return;- * }- * // Handling POST only.- * // ...- * });- * ```- *- * One can also modify request while falling back to the subsequent handler, that way intermediate route handler can- * modify url, method, headers and postData of the request.- *- * ```js- * await page.route('**\/*', async (route, request) => {- * // Override headers- * const headers = {- * ...request.headers(),- * foo: 'foo-value', // set "foo" header- * bar: undefined, // remove "bar" header- * };- * await route.fallback({ headers });- * });- * ```- *- * Use [route.continue([options])](https://playwright.dev/docs/api/class-route#route-continue) to immediately send the- * request to the network, other matching handlers won't be invoked in that case.+ * Flings the widget defined by+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-fling-option-selector) in the+ * specified [`direction`](https://playwright.dev/docs/api/class-androiddevice#android-device-fling-option-direction).+ * @param selector Selector to fling.+ * @param direction Fling direction.* @param options*/- fallback(options?: {+ fling(selector: AndroidSelector, direction: "down"|"up"|"left"|"right", options?: {/**- * If set changes the request HTTP headers. Header values will be converted to a string.+ * Optional speed of the fling in pixels per second.*/- headers?: { [key: string]: string; };+ speed?: number;/**- * If set changes the request method (e.g. GET or POST).+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.*/- method?: string;+ timeout?: number;+ }): Promise<void>;- /**- * If set changes the post data of request.- */- postData?: string|Buffer|Serializable;+ /**+ * Returns information about a widget defined by+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-info-option-selector).+ * @param selector Selector to return information about.+ */+ info(selector: AndroidSelector): Promise<AndroidElementInfo>;+ /**+ * Installs an apk on the device.+ * @param file Either a path to the apk file, or apk file content.+ * @param options+ */+ installApk(file: string|Buffer, options?: {/**- * If set changes the request URL. New URL must have same protocol as original one. Changing the URL won't affect the- * route matching, all the routes are matched using the original request URL.+ * Optional arguments to pass to the `shell:cmd package install` call. Defaults to `-r -t -S`.*/- url?: string;+ args?: Array<string>;}): Promise<void>;/**- * Performs the request and fetches result without fulfilling it, so that the response could be modified and then- * fulfilled.- *- * **Usage**- *- * ```js- * await page.route('https://dog.ceo/api/breeds/list/all', async route => {- * const response = await route.fetch();- * const json = await response.json();- * json.message['big_red_dog'] = [];- * await route.fulfill({ response, json });- * });- * ```- *- * **Details**- *- * Note that [`headers`](https://playwright.dev/docs/api/class-route#route-fetch-option-headers) option will apply to- * the fetched request as well as any redirects initiated by it. If you want to only apply- * [`headers`](https://playwright.dev/docs/api/class-route#route-fetch-option-headers) to the original request, but- * not to redirects, look into [route.continue([options])](https://playwright.dev/docs/api/class-route#route-continue)- * instead.+ * Launches Chrome browser on the device, and returns its persistent context.* @param options*/- fetch(options?: {+ launchBrowser(options?: {/**- * If set changes the request HTTP headers. Header values will be converted to a string.+ * Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.*/- headers?: { [key: string]: string; };+ acceptDownloads?: boolean;/**- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.+ * **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality.+ *+ * Additional arguments to pass to the browser instance. The list of Chromium flags can be found+ * [here](https://peter.sh/experiments/chromium-command-line-switches/).*/- maxRedirects?: number;+ args?: Array<string>;/**- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.+ * When using [page.goto(url[, options])](https://playwright.dev/docs/api/class-page#page-goto),+ * [page.route(url, handler[, options])](https://playwright.dev/docs/api/class-page#page-route),+ * [page.waitForURL(url[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-url),+ * [page.waitForRequest(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-request),+ * or+ * [page.waitForResponse(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-response)+ * it takes the base URL in consideration by using the+ * [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL.+ * Unset by default. Examples:+ * - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`+ * - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in+ * `http://localhost:3000/foo/bar.html`+ * - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in+ * `http://localhost:3000/bar.html`*/- maxRetries?: number;+ baseURL?: string;/**- * If set changes the request method (e.g. GET or POST).+ * Toggles bypassing page's Content-Security-Policy. Defaults to `false`.*/- method?: string;+ bypassCSP?: boolean;/**- * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string- * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`- * header will be set to `application/octet-stream` if not explicitly set.+ * Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)+ * media feature, supported values are `'light'` and `'dark'`. See+ * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.+ * Passing `null` resets emulation to system defaults. Defaults to `'light'`.*/- postData?: string|Buffer|Serializable;+ colorScheme?: null|"light"|"dark"|"no-preference";/**- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.+ * Emulates `'prefers-contrast'` media feature, supported values are `'no-preference'`, `'more'`. See+ * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.+ * Passing `null` resets emulation to system defaults. Defaults to `'no-preference'`.*/- timeout?: number;+ contrast?: null|"no-preference"|"more";/**- * If set changes the request URL. New URL must have same protocol as original one.+ * Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about+ * [emulating devices with device scale factor](https://playwright.dev/docs/emulation#devices).*/- url?: string;- }): Promise<APIResponse>;+ deviceScaleFactor?: number;++ /**+ * An object containing additional HTTP headers to be sent with every request. Defaults to none.+ */+ extraHTTPHeaders?: { [key: string]: string; };++ /**+ * Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See+ * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.+ * Passing `null` resets emulation to system defaults. Defaults to `'none'`.+ */+ forcedColors?: null|"active"|"none";++ geolocation?: {+ /**+ * Latitude between -90 and 90.+ */+ latitude: number;++ /**+ * Longitude between -180 and 180.+ */+ longitude: number;++ /**+ * Non-negative accuracy value. Defaults to `0`.+ */+ accuracy?: number;+ };- /**- * Fulfills route's request with given response.- *- * **Usage**- *- * An example of fulfilling all requests with 404 responses:- *- * ```js- * await page.route('**\/*', async route => {- * await route.fulfill({- * status: 404,- * contentType: 'text/plain',- * body: 'Not Found!'- * });- * });- * ```- *- * An example of serving static file:- *- * ```js- * await page.route('**\/xhr_endpoint', route => route.fulfill({ path: 'mock_data.json' }));- * ```- *- * @param options- */- fulfill(options?: {/**- * Response body.+ * Specifies if viewport supports touch events. Defaults to false. Learn more about+ * [mobile emulation](https://playwright.dev/docs/emulation#devices).*/- body?: string|Buffer;+ hasTouch?: boolean;/**- * If set, equals to setting `Content-Type` response header.+ * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no+ * origin is specified, the username and password are sent to any servers upon unauthorized responses.*/- contentType?: string;+ httpCredentials?: {+ username: string;++ password: string;++ /**+ * Restrain sending http credentials on specific origin (scheme://host:port).+ */+ origin?: string;++ /**+ * This option only applies to the requests sent from corresponding+ * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) and does not affect requests sent from+ * the browser. `'always'` - `Authorization` header with basic authentication credentials will be sent with the each+ * API request. `'unauthorized` - the credentials are only sent when 401 (Unauthorized) response with+ * `WWW-Authenticate` header is received. Defaults to `'unauthorized'`.+ */+ send?: "unauthorized"|"always";+ };/**- * Response headers. Header values will be converted to a string.+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.*/- headers?: { [key: string]: string; };+ ignoreHTTPSErrors?: boolean;/**- * JSON response. This method will set the content type to `application/json` if not set.+ * Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,+ * so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more+ * about [mobile emulation](https://playwright.dev/docs/emulation#ismobile).*/- json?: Serializable;+ isMobile?: boolean;/**- * File path to respond with. The content type will be inferred from file extension. If `path` is a relative path,- * then it is resolved relative to the current working directory.+ * Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about+ * [disabling JavaScript](https://playwright.dev/docs/emulation#javascript-enabled).*/- path?: string;+ javaScriptEnabled?: boolean;/**- * [APIResponse](https://playwright.dev/docs/api/class-apiresponse) to fulfill route's request with. Individual fields- * of the response (such as headers) can be overridden using fulfill options.+ * Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value,+ * `Accept-Language` request header value as well as number and date formatting rules. Defaults to the system default+ * locale. Learn more about emulation in our [emulation guide](https://playwright.dev/docs/emulation#locale--timezone).*/- response?: APIResponse;+ locale?: string;/**- * Response status code, defaults to `200`.+ * Logger sink for Playwright logging.+ * @deprecated The logs received by the logger are incomplete. Please use tracing instead.*/- status?: number;- }): Promise<void>;+ logger?: Logger;- /**- * A request to be routed.- */- request(): Request;-}+ /**+ * Whether to emulate network being offline. Defaults to `false`. Learn more about+ * [network emulation](https://playwright.dev/docs/emulation#offline).+ */+ offline?: boolean;-/**- * Selectors can be used to install custom selector engines. See [extensibility](https://playwright.dev/docs/extensibility) for more- * information.- */-export interface Selectors {- /**- * Selectors must be registered before creating the page.- *- * **Usage**- *- * An example of registering selector engine that queries elements based on a tag name:- *- * ```js- * const { selectors, firefox } = require('@playwright/test'); // Or 'chromium' or 'webkit'.- *- * (async () => {- * // Must be a function that evaluates to a selector engine instance.- * const createTagNameEngine = () => ({- * // Returns the first element matching given selector in the root's subtree.- * query(root, selector) {- * return root.querySelector(selector);- * },- *- * // Returns all elements matching given selector in the root's subtree.- * queryAll(root, selector) {- * return Array.from(root.querySelectorAll(selector));- * }- * });- *- * // Register the engine. Selectors will be prefixed with "tag=".- * await selectors.register('tag', createTagNameEngine);- *- * const browser = await firefox.launch();- * const page = await browser.newPage();- * await page.setContent(`<div><button>Click me</button></div>`);- *- * // Use the selector prefixed with its name.- * const button = page.locator('tag=button');- * // We can combine it with built-in locators.- * await page.locator('tag=div').getByText('Click me').click();- * // Can use it in any methods supporting selectors.- * const buttonCount = await page.locator('tag=button').count();- *- * await browser.close();- * })();- * ```- *- * @param name Name that is used in selectors as a prefix, e.g. `{name: 'foo'}` enables `foo=myselectorbody` selectors. May only- * contain `[a-zA-Z0-9_]` characters.- * @param script Script that evaluates to a selector engine instance. The script is evaluated in the page context.- * @param options- */- register(name: string, script: Function|string|{/**- * Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working- * directory. Optional.+ * A list of permissions to grant to all pages in this context. See+ * [browserContext.grantPermissions(permissions[, options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-grant-permissions)+ * for more details. Defaults to none.*/- path?: string;+ permissions?: Array<string>;/**- * Raw script content. Optional.+ * Optional package name to launch instead of default Chrome for Android.*/- content?: string;- }, options?: {+ pkg?: string;+/**- * Whether to run this selector engine in isolated JavaScript environment. This environment has access to the same- * DOM, but not any JavaScript objects from the frame's scripts. Defaults to `false`. Note that running as a content- * script is not guaranteed when this engine is used together with other registered engines.+ * Network proxy settings.*/- contentScript?: boolean;- }): Promise<void>;+ proxy?: {+ /**+ * Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example `http://myproxy.com:3128` or+ * `socks5://myproxy.com:3128`. Short form `myproxy.com:3128` is considered an HTTP proxy.+ */+ server: string;- /**- * Defines custom attribute name to be used in- * [page.getByTestId(testId)](https://playwright.dev/docs/api/class-page#page-get-by-test-id). `data-testid` is used- * by default.- * @param attributeName Test id attribute name.- */- setTestIdAttribute(attributeName: string): void;-}+ /**+ * Optional comma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.+ */+ bypass?: string;-/**- * The Touchscreen class operates in main-frame CSS pixels relative to the top-left corner of the viewport. Methods on- * the touchscreen can only be used in browser contexts that have been initialized with `hasTouch` set to true.- *- * This class is limited to emulating tap gestures. For examples of other gestures simulated by manually dispatching- * touch events, see the [emulating legacy touch events](https://playwright.dev/docs/touch-events) page.- */-export interface Touchscreen {- /**- * Dispatches a `touchstart` and `touchend` event with a single touch at the position- * ([`x`](https://playwright.dev/docs/api/class-touchscreen#touchscreen-tap-option-x),[`y`](https://playwright.dev/docs/api/class-touchscreen#touchscreen-tap-option-y)).- *- * **NOTE** [page.tap(selector[, options])](https://playwright.dev/docs/api/class-page#page-tap) the method will throw- * if [`hasTouch`](https://playwright.dev/docs/api/class-browser#browser-new-context-option-has-touch) option of the- * browser context is false.- *- * @param x X coordinate relative to the main frame's viewport in CSS pixels.- * @param y Y coordinate relative to the main frame's viewport in CSS pixels.- */- tap(x: number, y: number): Promise<void>;-}+ /**+ * Optional username to use if HTTP proxy requires authentication.+ */+ username?: string;++ /**+ * Optional password to use if HTTP proxy requires authentication.+ */+ password?: string;+ };++ /**+ * Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into `recordHar.path` file.+ * If not specified, the HAR is not recorded. Make sure to await+ * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for+ * the HAR to be saved.+ */+ recordHar?: {+ /**+ * Optional setting to control whether to omit request content from the HAR. Defaults to `false`. Deprecated, use+ * `content` policy instead.+ */+ omitContent?: boolean;++ /**+ * Optional setting to control resource content management. If `omit` is specified, content is not persisted. If+ * `attach` is specified, resources are persisted as separate files or entries in the ZIP archive. If `embed` is+ * specified, content is stored inline the HAR file as per HAR specification. Defaults to `attach` for `.zip` output+ * files and to `embed` for all other file extensions.+ */+ content?: "omit"|"embed"|"attach";++ /**+ * Path on the filesystem to write the HAR file to. If the file name ends with `.zip`, `content: 'attach'` is used by+ * default.+ */+ path: string;++ /**+ * When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,+ * cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.+ */+ mode?: "full"|"minimal";++ /**+ * A glob or regex pattern to filter requests that are stored in the HAR. When a+ * [`baseURL`](https://playwright.dev/docs/api/class-browser#browser-new-context-option-base-url) via the context+ * options was provided and the passed URL is a path, it gets merged via the+ * [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor. Defaults to none.+ */+ urlFilter?: string|RegExp;+ };-/**- * API for collecting and saving Playwright traces. Playwright traces can be opened in- * [Trace Viewer](https://playwright.dev/docs/trace-viewer) after Playwright script runs.- *- * **NOTE** You probably want to- * [enable tracing in your config file](https://playwright.dev/docs/api/class-testoptions#test-options-trace) instead- * of using `context.tracing`.- *- * The `context.tracing` API captures browser operations and network activity, but it doesn't record test assertions- * (like `expect` calls). We recommend- * [enabling tracing through Playwright Test configuration](https://playwright.dev/docs/api/class-testoptions#test-options-trace),- * which includes those assertions and provides a more complete trace for debugging test failures.- *- * Start recording a trace before performing actions. At the end, stop tracing and save it to a file.- *- * ```js- * const browser = await chromium.launch();- * const context = await browser.newContext();- * await context.tracing.start({ screenshots: true, snapshots: true });- * const page = await context.newPage();- * await page.goto('https://playwright.dev');- * expect(page.url()).toBe('https://playwright.dev');- * await context.tracing.stop({ path: 'trace.zip' });- * ```- *- */-export interface Tracing {- /**- * **NOTE** Use `test.step` instead when available.- *- * Creates a new group within the trace, assigning any subsequent API calls to this group, until- * [tracing.groupEnd()](https://playwright.dev/docs/api/class-tracing#tracing-group-end) is called. Groups can be- * nested and will be visible in the trace viewer.- *- * **Usage**- *- * ```js- * // use test.step instead- * await test.step('Log in', async () => {- * // ...- * });- * ```- *- * @param name Group name shown in the trace viewer.- * @param options- */- group(name: string, options?: {/**- * Specifies a custom location for the group to be shown in the trace viewer. Defaults to the location of the- * [tracing.group(name[, options])](https://playwright.dev/docs/api/class-tracing#tracing-group) call.+ * Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded.+ * Make sure to await+ * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for+ * videos to be saved.*/- location?: {- file: string;+ recordVideo?: {+ /**+ * Path to the directory to put videos into. If not specified, the videos will be stored in `artifactsDir` (see+ * [browserType.launch([options])](https://playwright.dev/docs/api/class-browsertype#browser-type-launch) options).+ */+ dir?: string;- line?: number;+ /**+ * Optional dimensions of the recorded videos. If not specified the size will be equal to `viewport` scaled down to+ * fit into 800x800. If `viewport` is not configured explicitly the video size defaults to 800x450. Actual picture of+ * each page will be scaled down if necessary to fit the specified size.+ */+ size?: {+ /**+ * Video frame width.+ */+ width: number;- column?: number;+ /**+ * Video frame height.+ */+ height: number;+ };++ /**+ * If specified, enables visual annotations on interacted elements during video recording.+ */+ showActions?: {+ /**+ * How long each annotation is displayed in milliseconds. Defaults to `500`.+ */+ duration?: number;++ /**+ * Position of the action title overlay. Defaults to `"top-right"`.+ */+ position?: "top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right";++ /**+ * Font size of the action title in pixels. Defaults to `24`.+ */+ fontSize?: number;+ };};- }): Promise<Disposable>;- /**- * Closes the last group created by- * [tracing.group(name[, options])](https://playwright.dev/docs/api/class-tracing#tracing-group).- */- groupEnd(): Promise<void>;+ /**+ * Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See+ * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.+ * Passing `null` resets emulation to system defaults. Defaults to `'no-preference'`.+ */+ reducedMotion?: null|"reduce"|"no-preference";- /**- * Start tracing.- *- * **NOTE** You probably want to- * [enable tracing in your config file](https://playwright.dev/docs/api/class-testoptions#test-options-trace) instead- * of using `Tracing.start`.- *- * The `context.tracing` API captures browser operations and network activity, but it doesn't record test assertions- * (like `expect` calls). We recommend- * [enabling tracing through Playwright Test configuration](https://playwright.dev/docs/api/class-testoptions#test-options-trace),- * which includes those assertions and provides a more complete trace for debugging test failures.- *- * **Usage**- *- * ```js- * await context.tracing.start({ screenshots: true, snapshots: true });- * const page = await context.newPage();- * await page.goto('https://playwright.dev');- * expect(page.url()).toBe('https://playwright.dev');- * await context.tracing.stop({ path: 'trace.zip' });- * ```- *- * @param options- */- start(options?: {/**- * When enabled, the trace is written to an unarchived file that is updated in real time as actions occur, instead of- * caching changes and archiving them into a zip file at the end. This is useful for live trace viewing during test- * execution.+ * Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the+ * [`viewport`](https://playwright.dev/docs/api/class-androiddevice#android-device-launch-browser-option-viewport) is+ * set.*/- live?: boolean;+ screen?: {+ /**+ * page width in pixels.+ */+ width: number;++ /**+ * page height in pixels.+ */+ height: number;+ };/**- * If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the- * [`tracesDir`](https://playwright.dev/docs/api/class-browsertype#browser-type-launch-option-traces-dir) directory- * specified in- * [browserType.launch([options])](https://playwright.dev/docs/api/class-browsertype#browser-type-launch). To specify- * the final trace zip file name, you need to pass `path` option to- * [tracing.stop([options])](https://playwright.dev/docs/api/class-tracing#tracing-stop) instead.+ * Whether to allow sites to register Service workers. Defaults to `'allow'`.+ * - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be+ * registered.+ * - `'block'`: Playwright will block all registration of Service Workers.*/- name?: string;+ serviceWorkers?: "allow"|"block";/**- * Whether to capture screenshots during tracing. Screenshots are used to build a timeline preview.+ * If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on+ * selectors that imply single target DOM element will throw when more than one element matches the selector. This+ * option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See+ * [Locator](https://playwright.dev/docs/api/class-locator) to learn more about the strict mode.*/- screenshots?: boolean;+ strictSelectors?: boolean;/**- * If this option is true tracing will- * - capture DOM snapshot on every action- * - record network activity+ * Changes the timezone of the context. See+ * [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)+ * for a list of supported timezone IDs. Defaults to the system timezone.*/- snapshots?: boolean;+ timezoneId?: string;/**- * Whether to include source files for trace actions.+ * Specific user agent to use in this context.*/- sources?: boolean;+ userAgent?: string;/**- * Trace name to be shown in the Trace Viewer.+ * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use `null` to disable the consistent+ * viewport emulation. Learn more about [viewport emulation](https://playwright.dev/docs/emulation#viewport).+ *+ * **NOTE** The `null` value opts out from the default presets, makes viewport depend on the host window size defined+ * by the operating system. It makes the execution of the tests non-deterministic.+ **/- title?: string;- }): Promise<void>;+ viewport?: null|{+ /**+ * page width in pixels.+ */+ width: number;++ /**+ * page height in pixels.+ */+ height: number;+ };+ }): Promise<BrowserContext>;/**- * Start a new trace chunk. If you'd like to record multiple traces on the same- * [BrowserContext](https://playwright.dev/docs/api/class-browsercontext), use- * [tracing.start([options])](https://playwright.dev/docs/api/class-tracing#tracing-start) once, and then create- * multiple trace chunks with- * [tracing.startChunk([options])](https://playwright.dev/docs/api/class-tracing#tracing-start-chunk) and- * [tracing.stopChunk([options])](https://playwright.dev/docs/api/class-tracing#tracing-stop-chunk).- *- * **Usage**- *- * ```js- * await context.tracing.start({ screenshots: true, snapshots: true });- * const page = await context.newPage();- * await page.goto('https://playwright.dev');- *- * await context.tracing.startChunk();- * await page.getByText('Get Started').click();- * // Everything between startChunk and stopChunk will be recorded in the trace.- * await context.tracing.stopChunk({ path: 'trace1.zip' });- *- * await context.tracing.startChunk();- * await page.goto('http://example.com');- * // Save a second trace file with different actions.- * await context.tracing.stopChunk({ path: 'trace2.zip' });- * ```- *+ * Performs a long tap on the widget defined by+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-long-tap-option-selector).+ * @param selector Selector to tap on.* @param options*/- startChunk(options?: {- /**- * If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the- * [`tracesDir`](https://playwright.dev/docs/api/class-browsertype#browser-type-launch-option-traces-dir) directory- * specified in- * [browserType.launch([options])](https://playwright.dev/docs/api/class-browsertype#browser-type-launch). To specify- * the final trace zip file name, you need to pass `path` option to- * [tracing.stopChunk([options])](https://playwright.dev/docs/api/class-tracing#tracing-stop-chunk) instead.- */- name?: string;-+ longTap(selector: AndroidSelector, options?: {/**- * Trace name to be shown in the Trace Viewer.+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.*/- title?: string;+ timeout?: number;}): Promise<void>;/**- * Start recording a HAR (HTTP Archive) of network activity in this context. The HAR file is written to disk when- * [tracing.stopHar()](https://playwright.dev/docs/api/class-tracing#tracing-stop-har) is called, or when the returned- * [Disposable](https://playwright.dev/docs/api/class-disposable) is disposed.- *- * Only one HAR recording can be active at a time per- * [BrowserContext](https://playwright.dev/docs/api/class-browsercontext).- *- * **Usage**- *- * ```js- * await context.tracing.startHar('trace.har');- * const page = await context.newPage();- * await page.goto('https://playwright.dev');- * await context.tracing.stopHar();- * ```- *- * @param path Path on the filesystem to write the HAR file to. If the file name ends with `.zip`, the HAR is saved as a zip- * archive with response bodies attached as separate files.+ * Device model.+ */+ model(): string;++ /**+ * Launches a process in the shell on the device and returns a socket to communicate with the launched process.+ * @param command Shell command to execute.+ */+ open(command: string): Promise<AndroidSocket>;++ /**+ * Pinches the widget defined by+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-pinch-close-option-selector) in the+ * closing direction.+ * @param selector Selector to pinch close.+ * @param percent The size of the pinch as a percentage of the widget's size.* @param options*/- startHar(path: string, options?: {+ pinchClose(selector: AndroidSelector, percent: number, options?: {/**- * Optional setting to control resource content management. If `omit` is specified, content is not persisted. If- * `attach` is specified, resources are persisted as separate files or entries in the ZIP archive. If `embed` is- * specified, content is stored inline the HAR file as per HAR specification. Defaults to `attach` for `.zip` output- * files and to `embed` for all other file extensions.+ * Optional speed of the pinch in pixels per second.*/- content?: "omit"|"embed"|"attach";+ speed?: number;/**- * When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,- * cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.*/- mode?: "full"|"minimal";+ timeout?: number;+ }): Promise<void>;+ /**+ * Pinches the widget defined by+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-pinch-open-option-selector) in the+ * open direction.+ * @param selector Selector to pinch open.+ * @param percent The size of the pinch as a percentage of the widget's size.+ * @param options+ */+ pinchOpen(selector: AndroidSelector, percent: number, options?: {/**- * Only used together with `content: 'attach'`. When set, response bodies are placed in this directory instead of next- * to the HAR file. Not compatible with a `.zip` HAR file.+ * Optional speed of the pinch in pixels per second.*/- resourcesDir?: string;+ speed?: number;/**- * A glob or regex pattern to filter requests that are stored in the HAR. Defaults to none.+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.*/- urlFilter?: string|RegExp;- }): Promise<Disposable>;+ timeout?: number;+ }): Promise<void>;/**- * Stop tracing.+ * Presses the specific [`key`](https://playwright.dev/docs/api/class-androiddevice#android-device-press-option-key)+ * in the widget defined by+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-press-option-selector).+ * @param selector Selector to press the key in.+ * @param key The key to press.* @param options*/- stop(options?: {+ press(selector: AndroidSelector, key: AndroidKey, options?: {/**- * Export trace into the file with the given path.+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.*/- path?: string;+ timeout?: number;}): Promise<void>;/**- * Stop the trace chunk. See- * [tracing.startChunk([options])](https://playwright.dev/docs/api/class-tracing#tracing-start-chunk) for more details- * about multiple trace chunks.+ * Copies a file to the device.+ * @param file Either a path to the file, or file content.+ * @param path Path to the file on the device.* @param options*/- stopChunk(options?: {+ push(file: string|Buffer, path: string, options?: {/**- * Export trace collected since the last- * [tracing.startChunk([options])](https://playwright.dev/docs/api/class-tracing#tracing-start-chunk) call into the- * file with the given path.+ * Optional file mode, defaults to `644` (`rw-r--r--`).*/- path?: string;+ mode?: number;}): Promise<void>;/**- * Stop HAR recording and save the HAR file to the path given to- * [tracing.startHar(path[, options])](https://playwright.dev/docs/api/class-tracing#tracing-start-har).- */- stopHar(): Promise<void>;-}--/**- * When browser context is created with the `recordVideo` option, each page has a video object associated with it.- *- * ```js- * console.log(await page.video().path());- * ```- *- */-export interface Video {- /**- * Deletes the video file. Will wait for the video to finish if necessary.- */- delete(): Promise<void>;-- /**- * Returns the file system path this video will be recorded to. The video is guaranteed to be written to the- * filesystem upon closing the browser context. This method throws when connected remotely.- */- path(): Promise<string>;-- /**- * Saves the video to a user-specified path. It is safe to call this method while the video is still in progress, or- * after the page has closed. This method waits until the page is closed and the video is fully saved.- * @param path Path where the video should be saved.+ * Returns the buffer with the captured screenshot of the device.+ * @param options*/- saveAs(path: string): Promise<void>;-}+ screenshot(options?: {+ /**+ * The file path to save the image to. If+ * [`path`](https://playwright.dev/docs/api/class-androiddevice#android-device-screenshot-option-path) is a relative+ * path, then it is resolved relative to the current working directory. If no path is provided, the image won't be+ * saved to the disk.+ */+ path?: string;+ }): Promise<Buffer>;-/**- * [WebError](https://playwright.dev/docs/api/class-weberror) class represents an unhandled exception thrown in the- * page. It is dispatched via the- * [browserContext.on('weberror')](https://playwright.dev/docs/api/class-browsercontext#browser-context-event-web-error)- * event.- *- * ```js- * // Log all uncaught errors to the terminal- * context.on('weberror', webError => {- * console.log(`Uncaught exception: "${webError.error()}"`);- * });- *- * // Navigate to a page with an exception.- * await page.goto('data:text/html,<script>throw new Error("Test")</script>');- * ```- *- */-export interface WebError {/**- * Unhandled error that was thrown.+ * Scrolls the widget defined by+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-scroll-option-selector) in the+ * specified+ * [`direction`](https://playwright.dev/docs/api/class-androiddevice#android-device-scroll-option-direction).+ * @param selector Selector to scroll.+ * @param direction Scroll direction.+ * @param percent Distance to scroll as a percentage of the widget's size.+ * @param options*/- error(): Error;-- location(): {+ scroll(selector: AndroidSelector, direction: "down"|"up"|"left"|"right", percent: number, options?: {/**- * URL of the resource.+ * Optional speed of the scroll in pixels per second.*/- url: string;+ speed?: number;/**- * 0-based line number in the resource.+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.*/- line: number;+ timeout?: number;+ }): Promise<void>;- /**- * 0-based column number in the resource.- */- column: number;- };+ /**+ * Device serial number.+ */+ serial(): string;/**- * The page that produced this unhandled exception, if any.+ * This setting will change the default maximum time for all the methods accepting+ * [`timeout`](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout-option-timeout)+ * option.+ * @param timeout Maximum time in milliseconds*/- page(): null|Page;-}+ setDefaultTimeout(timeout: number): void;-/**- * The [WebSocket](https://playwright.dev/docs/api/class-websocket) class represents WebSocket connections within a- * page. It provides the ability to inspect and manipulate the data being transmitted and received.- *- * If you want to intercept or modify WebSocket frames, consider using- * [WebSocketRoute](https://playwright.dev/docs/api/class-websocketroute).- */-export interface WebSocket {/**- * Fired when the websocket closes.+ * Executes a shell command on the device and returns its output.+ * @param command Shell command to execute.*/- on(event: 'close', listener: (webSocket: WebSocket) => any): this;+ shell(command: string): Promise<Buffer>;/**- * Fired when the websocket receives a frame.+ * Swipes the widget defined by+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-swipe-option-selector) in the+ * specified [`direction`](https://playwright.dev/docs/api/class-androiddevice#android-device-swipe-option-direction).+ * @param selector Selector to swipe.+ * @param direction Swipe direction.+ * @param percent Distance to swipe as a percentage of the widget's size.+ * @param options*/- on(event: 'framereceived', listener: (data: {+ swipe(selector: AndroidSelector, direction: "down"|"up"|"left"|"right", percent: number, options?: {/**- * frame payload+ * Optional speed of the swipe in pixels per second.*/- payload: string|Buffer;- }) => any): this;+ speed?: number;- /**- * Fired when the websocket sends a frame.- */- on(event: 'framesent', listener: (data: {/**- * frame payload+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.*/- payload: string|Buffer;- }) => any): this;+ timeout?: number;+ }): Promise<void>;/**- * Fired when the websocket has an error.+ * Taps on the widget defined by+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-tap-option-selector).+ * @param selector Selector to tap on.+ * @param options*/- on(event: 'socketerror', listener: (string: string) => any): this;+ tap(selector: AndroidSelector, options?: {+ /**+ * Optional duration of the tap in milliseconds.+ */+ duration?: number;- /**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.- */- once(event: 'close', listener: (webSocket: WebSocket) => any): this;+ /**+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.+ */+ timeout?: number;+ }): Promise<void>;/**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ * Waits for the specific+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-wait-option-selector) to either+ * appear or disappear, depending on the+ * [`state`](https://playwright.dev/docs/api/class-androiddevice#android-device-wait-option-state).+ * @param selector Selector to wait for.+ * @param options*/- once(event: 'framereceived', listener: (data: {+ wait(selector: AndroidSelector, options?: {/**- * frame payload+ * Optional state. Can be either:+ * - default - wait for element to be present.+ * - `'gone'` - wait for element to not be present.*/- payload: string|Buffer;- }) => any): this;+ state?: "gone";- /**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.- */- once(event: 'framesent', listener: (data: {/**- * frame payload+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.*/- payload: string|Buffer;- }) => any): this;+ timeout?: number;+ }): Promise<void>;/**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ * Emitted when the device connection gets closed.*/- once(event: 'socketerror', listener: (string: string) => any): this;+ waitForEvent(event: 'close', optionsOrPredicate?: { predicate?: (androidDevice: AndroidDevice) => boolean | Promise<boolean>, timeout?: number } | ((androidDevice: AndroidDevice) => boolean | Promise<boolean>)): Promise<AndroidDevice>;/**- * Fired when the websocket closes.+ * Emitted when a new WebView instance is detected.*/- addListener(event: 'close', listener: (webSocket: WebSocket) => any): this;+ waitForEvent(event: 'webview', optionsOrPredicate?: { predicate?: (androidWebView: AndroidWebView) => boolean | Promise<boolean>, timeout?: number } | ((androidWebView: AndroidWebView) => boolean | Promise<boolean>)): Promise<AndroidWebView>;+/**- * Fired when the websocket receives a frame.+ * This method waits until [AndroidWebView](https://playwright.dev/docs/api/class-androidwebview) matching the+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-web-view-option-selector) is opened+ * and returns it. If there is already an open [AndroidWebView](https://playwright.dev/docs/api/class-androidwebview)+ * matching the+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-web-view-option-selector), returns+ * immediately.+ * @param selector+ * @param options*/- addListener(event: 'framereceived', listener: (data: {+ webView(selector: {/**- * frame payload+ * Optional Package identifier.*/- payload: string|Buffer;- }) => any): this;+ pkg?: string;- /**- * Fired when the websocket sends a frame.- */- addListener(event: 'framesent', listener: (data: {/**- * frame payload+ * Optional webview socket name.*/- payload: string|Buffer;- }) => any): this;+ socketName?: string;+ }, options?: {+ /**+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.+ */+ timeout?: number;+ }): Promise<AndroidWebView>;/**- * Fired when the websocket has an error.+ * Currently open WebViews.*/- addListener(event: 'socketerror', listener: (string: string) => any): this;+ webViews(): Array<AndroidWebView>;- /**- * Removes an event listener added by `on` or `addListener`.- */- removeListener(event: 'close', listener: (webSocket: WebSocket) => any): this;+ input: AndroidInput;++ [Symbol.asyncDispose](): Promise<void>;+}+export interface AndroidInput {/**- * Removes an event listener added by `on` or `addListener`.+ * Performs a drag between [`from`](https://playwright.dev/docs/api/class-androidinput#android-input-drag-option-from)+ * and [`to`](https://playwright.dev/docs/api/class-androidinput#android-input-drag-option-to) points.+ * @param from The start point of the drag.+ * @param to The end point of the drag.+ * @param steps The number of steps in the drag. Each step takes 5 milliseconds to complete.*/- removeListener(event: 'framereceived', listener: (data: {- /**- * frame payload- */- payload: string|Buffer;- }) => any): this;+ drag(from: {+ x: number;++ y: number;+ }, to: {+ x: number;++ y: number;+ }, steps: number): Promise<void>;/**- * Removes an event listener added by `on` or `addListener`.+ * Presses the [`key`](https://playwright.dev/docs/api/class-androidinput#android-input-press-option-key).+ * @param key Key to press.*/- removeListener(event: 'framesent', listener: (data: {- /**- * frame payload- */- payload: string|Buffer;- }) => any): this;+ press(key: AndroidKey): Promise<void>;/**- * Removes an event listener added by `on` or `addListener`.+ * Swipes following the path defined by+ * [`segments`](https://playwright.dev/docs/api/class-androidinput#android-input-swipe-option-segments).+ * @param from The point to start swiping from.+ * @param segments Points following the [`from`](https://playwright.dev/docs/api/class-androidinput#android-input-swipe-option-from)+ * point in the swipe gesture.+ * @param steps The number of steps for each segment. Each step takes 5 milliseconds to complete, so 100 steps means half a second+ * per each segment.*/- removeListener(event: 'socketerror', listener: (string: string) => any): this;+ swipe(from: {+ x: number;++ y: number;+ }, segments: ReadonlyArray<{+ x: number;++ y: number;+ }>, steps: number): Promise<void>;/**- * Removes an event listener added by `on` or `addListener`.+ * Taps at the specified [`point`](https://playwright.dev/docs/api/class-androidinput#android-input-tap-option-point).+ * @param point The point to tap at.*/- off(event: 'close', listener: (webSocket: WebSocket) => any): this;+ tap(point: {+ x: number;++ y: number;+ }): Promise<void>;/**- * Removes an event listener added by `on` or `addListener`.+ * Types [`text`](https://playwright.dev/docs/api/class-androidinput#android-input-type-option-text) into currently+ * focused widget.+ * @param text Text to type.*/- off(event: 'framereceived', listener: (data: {- /**- * frame payload- */- payload: string|Buffer;- }) => any): this;+ type(text: string): Promise<void>;+}+/**+ * [AndroidSocket](https://playwright.dev/docs/api/class-androidsocket) is a way to communicate with a process+ * launched on the [AndroidDevice](https://playwright.dev/docs/api/class-androiddevice). Use+ * [androidDevice.open(command)](https://playwright.dev/docs/api/class-androiddevice#android-device-open) to open a+ * socket.+ */+export interface AndroidSocket {/**- * Removes an event listener added by `on` or `addListener`.+ * Emitted when the socket is closed.*/- off(event: 'framesent', listener: (data: {- /**- * frame payload- */- payload: string|Buffer;- }) => any): this;+ on(event: 'close', listener: () => any): this;/**- * Removes an event listener added by `on` or `addListener`.+ * Emitted when data is available to read from the socket.*/- off(event: 'socketerror', listener: (string: string) => any): this;+ on(event: 'data', listener: (buffer: Buffer) => any): this;/**- * Fired when the websocket closes.+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.*/- prependListener(event: 'close', listener: (webSocket: WebSocket) => any): this;+ once(event: 'close', listener: () => any): this;/**- * Fired when the websocket receives a frame.+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.*/- prependListener(event: 'framereceived', listener: (data: {- /**- * frame payload- */- payload: string|Buffer;- }) => any): this;+ once(event: 'data', listener: (buffer: Buffer) => any): this;/**- * Fired when the websocket sends a frame.+ * Emitted when the socket is closed.*/- prependListener(event: 'framesent', listener: (data: {- /**- * frame payload- */- payload: string|Buffer;- }) => any): this;+ addListener(event: 'close', listener: () => any): this;/**- * Fired when the websocket has an error.+ * Emitted when data is available to read from the socket.*/- prependListener(event: 'socketerror', listener: (string: string) => any): this;+ addListener(event: 'data', listener: (buffer: Buffer) => any): this;/**- * Indicates that the web socket has been closed.+ * Removes an event listener added by `on` or `addListener`.*/- isClosed(): boolean;+ removeListener(event: 'close', listener: () => any): this;/**- * Contains the URL of the WebSocket.+ * Removes an event listener added by `on` or `addListener`.*/- url(): string;+ removeListener(event: 'data', listener: (buffer: Buffer) => any): this;/**- * Fired when the websocket closes.+ * Removes an event listener added by `on` or `addListener`.*/- waitForEvent(event: 'close', optionsOrPredicate?: { predicate?: (webSocket: WebSocket) => boolean | Promise<boolean>, timeout?: number } | ((webSocket: WebSocket) => boolean | Promise<boolean>)): Promise<WebSocket>;+ off(event: 'close', listener: () => any): this;/**- * Fired when the websocket receives a frame.+ * Removes an event listener added by `on` or `addListener`.*/- waitForEvent(event: 'framereceived', optionsOrPredicate?: { predicate?: (data: {- /**- * frame payload- */- payload: string|Buffer;- }) => boolean | Promise<boolean>, timeout?: number } | ((data: {- /**- * frame payload- */- payload: string|Buffer;- }) => boolean | Promise<boolean>)): Promise<{- /**- * frame payload- */- payload: string|Buffer;- }>;+ off(event: 'data', listener: (buffer: Buffer) => any): this;/**- * Fired when the websocket sends a frame.+ * Emitted when the socket is closed.*/- waitForEvent(event: 'framesent', optionsOrPredicate?: { predicate?: (data: {- /**- * frame payload- */- payload: string|Buffer;- }) => boolean | Promise<boolean>, timeout?: number } | ((data: {- /**- * frame payload- */- payload: string|Buffer;- }) => boolean | Promise<boolean>)): Promise<{- /**- * frame payload- */- payload: string|Buffer;- }>;+ prependListener(event: 'close', listener: () => any): this;/**- * Fired when the websocket has an error.+ * Emitted when data is available to read from the socket.*/- waitForEvent(event: 'socketerror', optionsOrPredicate?: { predicate?: (string: string) => boolean | Promise<boolean>, timeout?: number } | ((string: string) => boolean | Promise<boolean>)): Promise<string>;+ prependListener(event: 'data', listener: (buffer: Buffer) => any): this;++ /**+ * Closes the socket.+ */+ close(): Promise<void>;++ /**+ * Writes some [`data`](https://playwright.dev/docs/api/class-androidsocket#android-socket-write-option-data) to the+ * socket.+ * @param data Data to write.+ */+ write(data: Buffer): Promise<void>;+ [Symbol.asyncDispose](): Promise<void>;}/**- * Playwright has **experimental** support for Electron automation, exposed as `_electron`. An example of the Electron- * automation script would be:- *- * ```js- * import { _electron as electron } from 'playwright';- *- * (async () => {- * // Launch Electron app.- * const electronApp = await electron.launch({ args: ['main.js'] });- *- * // Evaluation expression in the Electron context.- * const appPath = await electronApp.evaluate(async ({ app }) => {- * // This runs in the main Electron process, parameter here is always- * // the result of the require('electron') in the main app script.- * return app.getAppPath();- * });- * console.log(appPath);- *- * // Get the first window that the app opens, wait if necessary.- * const window = await electronApp.firstWindow();- * // Print the title.- * console.log(await window.title());- * // Capture a screenshot.- * await window.screenshot({ path: 'intro.png' });- * // Direct Electron console to Node terminal.- * window.on('console', console.log);- * // Click button.- * await window.click('text=Click me');- * // Exit app.- * await electronApp.close();- * })();- * ```- *- * **Supported Electron versions are:**- * - v12.2.0+- * - v13.4.0+- * - v14+- *- * **Known issues:**- *- * If you are not able to launch Electron and it will end up in timeouts during launch, try the following:- * - Ensure that `nodeCliInspect`- * ([FuseV1Options.EnableNodeCliInspectArguments](https://www.electronjs.org/docs/latest/tutorial/fuses#nodecliinspect))- * fuse is **not** set to `false`.- *- * **Migrating from v1.59**- *- * A number of launch options have been removed after v1.59. See below for alternatives.- * - `recordHar` - use- * [tracing.startHar(path[, options])](https://playwright.dev/docs/api/class-tracing#tracing-start-har).- *- * ```js- * const electronApp = await electron.launch({ args: ['main.js'] });- * await electronApp.context().tracing.startHar('network.har');- * // ... drive the app ...- * await electronApp.context().tracing.stopHar();- * await electronApp.close();- * ```- *- * - `recordVideo` - use- * [screencast.start([options])](https://playwright.dev/docs/api/class-screencast#screencast-start) on each- * window.- *- * ```js- * const electronApp = await electron.launch({ args: ['main.js'] });- * const window = await electronApp.firstWindow();- * await window.screencast.start({ path: 'video.webm' });- * // ... drive the window ...- * await window.screencast.stop();- * await electronApp.close();- * ```- *- * - `colorScheme` - use- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) on each window.- *- * ```js- * const window = await electronApp.firstWindow();- * await window.emulateMedia({ colorScheme: 'dark' });- * ```- *- * - `extraHTTPHeaders` - use- * [browserContext.setExtraHTTPHeaders(headers)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-extra-http-headers).- *- * ```js- * await electronApp.context().setExtraHTTPHeaders({ 'X-My-Header': 'value' });- * ```- *- * - `geolocation` - use- * [browserContext.setGeolocation(geolocation)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-geolocation).- *- * ```js- * await electronApp.context().setGeolocation({ latitude: 48.858455, longitude: 2.294474 });- * ```- *- * - `httpCredentials` - use- * [browserContext.setHTTPCredentials(httpCredentials)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-http-credentials).- *- * ```js- * await electronApp.context().setHTTPCredentials({ username: 'user', password: 'pass' });- * ```- *- * - `offline` - use- * [browserContext.setOffline(offline)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-offline).- *- * ```js- * await electronApp.context().setOffline(true);- * ```- *- * - `bypassCSP` - disable CSP at the `BrowserWindow` level via Electron's- * [web preferences](https://www.electronjs.org/docs/latest/api/structures/web-preferences). Note that- * `webSecurity: false` also disables CORS and the Same-Origin Policy.- *- * ```js- * const win = new BrowserWindow({- * webPreferences: {- * webSecurity: false,- * },- * });- * ```- *- * - `ignoreHTTPSErrors`- *- * There are several ways to relax HTTPS checks in Electron. Pick the one that matches the scope you need.- *- * Per-window, allow mixed content through- * [web preferences](https://www.electronjs.org/docs/latest/api/structures/web-preferences):- *- * ```js- * const win = new BrowserWindow({- * webPreferences: {- * allowRunningInsecureContent: true,- * },- * });- * ```- *- * Process-wide, ignore certificate errors via Chromium command-line switches (must run before the `ready` event):- *- * ```js- * const { app } = require('electron');- * app.commandLine.appendSwitch('ignore-certificate-errors');- * // Optional: also ignore localhost certificate errors when testing on an IP.- * app.commandLine.appendSwitch('allow-insecure-localhost', 'true');- * ```- *- * Per-request, accept the certificate manually via the- * [`certificate-error`](https://www.electronjs.org/docs/latest/api/app#event-certificate-error) event:- *- * ```js- * app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {- * event.preventDefault();- * callback(true);- * });- * ```- *- * - `timezoneId` - set an environment variable at the very top of the main file, before any other logic or Chromium- * windows are initialized.- *- * ```js- * // main.js- * process.env.TZ = 'Europe/London';- *- * const { app } = require('electron');- * // ... rest of your app logic- * ```- *+ * [AndroidWebView](https://playwright.dev/docs/api/class-androidwebview) represents a WebView open on the+ * [AndroidDevice](https://playwright.dev/docs/api/class-androiddevice). WebView is usually obtained using+ * [androidDevice.webView(selector[, options])](https://playwright.dev/docs/api/class-androiddevice#android-device-web-view).*/-export interface Electron {+export interface AndroidWebView {/**- * Launches electron application specified with the- * [`executablePath`](https://playwright.dev/docs/api/class-electron#electron-launch-option-executable-path).- * @param options+ * Emitted when the WebView is closed.*/- launch(options?: {- /**- * Additional arguments to pass to the application when launching. You typically pass the main script name here.- */- args?: Array<string>;+ on(event: 'close', listener: () => any): this;- /**- * Enable Chromium sandboxing. Defaults to `false`.- */- chromiumSandbox?: boolean;+ /**+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ */+ once(event: 'close', listener: () => any): this;- /**- * Current working directory to launch application from.- */- cwd?: string;+ /**+ * Emitted when the WebView is closed.+ */+ addListener(event: 'close', listener: () => any): this;- /**- * Specifies environment variables that will be visible to Electron. Defaults to `process.env`.- */- env?: { [key: string]: string; };+ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ removeListener(event: 'close', listener: () => any): this;- /**- * Launches given Electron application. If not specified, launches the default Electron executable installed in this- * package, located at `node_modules/.bin/electron`.- */- executablePath?: string;+ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ off(event: 'close', listener: () => any): this;- /**- * Maximum time in milliseconds to wait for the application to start. Defaults to `30000` (30 seconds). Pass `0` to- * disable timeout.- */- timeout?: number;- }): Promise<ElectronApplication>;+ /**+ * Emitted when the WebView is closed.+ */+ prependListener(event: 'close', listener: () => any): this;++ /**+ * Connects to the WebView and returns a regular Playwright [Page](https://playwright.dev/docs/api/class-page) to+ * interact with.+ */+ page(): Promise<Page>;++ /**+ * WebView process PID.+ */+ pid(): number;++ /**+ * WebView package identifier.+ */+ pkg(): string;}export interface LaunchOptions {diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.tsindex bf34b0dabd..4a33756068 100644--- a/packages/playwright-core/types/types.d.ts+++ b/packages/playwright-core/types/types.d.ts@@ -17140,1180 +17140,1101 @@ export {};/**- * Playwright has **experimental** support for Android automation. This includes Chrome for Android and Android- * WebView.- *- * *Requirements*- * - Android device or AVD Emulator.- * - [ADB daemon](https://developer.android.com/studio/command-line/adb) running and authenticated with your device.- * Typically running `adb devices` is all you need to do.- * - [`Chrome 87`](https://play.google.com/store/apps/details?id=com.android.chrome) or newer installed on the- * device- * - "Enable command line on non-rooted devices" enabled in `chrome://flags`.- *- * *Known limitations*- * - Raw USB operation is not yet supported, so you need ADB.- * - Device needs to be awake to produce screenshots. Enabling "Stay awake" developer mode will help.- * - We didn't run all the tests against the device, so not everything works.- *- * *How to run*- *- * An example of the Android automation script would be:- *- * ```js- * const { _android: android } = require('playwright');- *- * (async () => {- * // Connect to the device.- * const [device] = await android.devices();- * console.log(`Model: ${device.model()}`);- * console.log(`Serial: ${device.serial()}`);- * // Take screenshot of the whole device.- * await device.screenshot({ path: 'device.png' });- *- * {- * // --------------------- WebView ------------------------ *- * // Launch an application with WebView.- * await device.shell('am force-stop org.chromium.webview_shell');- * await device.shell('am start org.chromium.webview_shell/.WebViewBrowserActivity');- * // Get the WebView.- * const webview = await device.webView({ pkg: 'org.chromium.webview_shell' });- *- * // Fill the input box.- * await device.fill({- * res: 'org.chromium.webview_shell:id/url_field',- * }, 'github.com/microsoft/playwright');- * await device.press({- * res: 'org.chromium.webview_shell:id/url_field',- * }, 'Enter');- *- * // Work with WebView's page as usual.- * const page = await webview.page();- * await page.waitForNavigation({ url: /.*microsoft\/playwright.*\/ });- * console.log(await page.title());- * }- *- * {- * // --------------------- Browser ------------------------ *- * // Launch Chrome browser.- * await device.shell('am force-stop com.android.chrome');- * const context = await device.launchBrowser();- *- * // Use BrowserContext as usual.- * const page = await context.newPage();- * await page.goto('https://webkit.org/');- * console.log(await page.evaluate(() => window.location.href));- * await page.screenshot({ path: 'page.png' });- *- * await context.close();- * }- *- * // Close the device.- * await device.close();- * })();- * ```- *+ * Exposes API that can be used for the Web API testing. This class is used for creating+ * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) instance which in turn can be used for+ * sending web requests. An instance of this class can be obtained via+ * [playwright.request](https://playwright.dev/docs/api/class-playwright#playwright-request). For more information see+ * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext).*/-export interface Android {+export interface APIRequest {/**- * This methods attaches Playwright to an existing Android device. Use- * [android.launchServer([options])](https://playwright.dev/docs/api/class-android#android-launch-server) to launch a- * new Android server instance.- * @param endpoint A browser websocket endpoint to connect to.+ * Creates new instances of [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext).* @param options*/- connect(endpoint: string, options?: {+ newContext(options?: {/**- * Additional HTTP headers to be sent with web socket connect request. Optional.+ * Methods like+ * [apiRequestContext.get(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-get)+ * take the base URL into consideration by using the+ * [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL.+ * Examples:+ * - baseURL: `http://localhost:3000` and sending request to `/bar.html` results in `http://localhost:3000/bar.html`+ * - baseURL: `http://localhost:3000/foo/` and sending request to `./bar.html` results in+ * `http://localhost:3000/foo/bar.html`+ * - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in+ * `http://localhost:3000/bar.html`*/- headers?: { [key: string]: string; };+ baseURL?: string;/**- * Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going- * on. Defaults to `0`.+ * TLS Client Authentication allows the server to request a client certificate and verify it.+ *+ * **Details**+ *+ * An array of client certificates to be used. Each certificate object must have either both `certPath` and `keyPath`,+ * a single `pfxPath`, or their corresponding direct value equivalents (`cert` and `key`, or `pfx`). Optionally,+ * `passphrase` property should be provided if the certificate is encrypted. The `origin` property should be provided+ * with an exact match to the request origin that the certificate is valid for.+ *+ * Client certificate authentication is only active when at least one client certificate is provided. If you want to+ * reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that+ * does not match any of the domains you plan to visit.+ *+ * **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it+ * work by replacing `localhost` with `local.playwright`.+ **/- slowMo?: number;+ clientCertificates?: Array<{+ /**+ * Exact origin that the certificate is valid for. Origin includes `https` protocol, a hostname and optionally a port.+ */+ origin: string;- /**- * Maximum time in milliseconds to wait for the connection to be established. Defaults to `30000` (30 seconds). Pass- * `0` to disable timeout.- */- timeout?: number;- }): Promise<AndroidDevice>;+ /**+ * Path to the file with the certificate in PEM format.+ */+ certPath?: string;- /**- * Returns the list of detected Android devices.- * @param options- */- devices(options?: {- /**- * Optional host to establish ADB server connection. Default to `127.0.0.1`.- */- host?: string;+ /**+ * Direct value of the certificate in PEM format.+ */+ cert?: Buffer;- /**- * Prevents automatic playwright driver installation on attach. Assumes that the drivers have been installed already.- */- omitDriverInstall?: boolean;+ /**+ * Path to the file with the private key in PEM format.+ */+ keyPath?: string;- /**- * Optional port to establish ADB server connection. Default to `5037`.- */- port?: number;- }): Promise<Array<AndroidDevice>>;+ /**+ * Direct value of the private key in PEM format.+ */+ key?: Buffer;- /**- * Launches Playwright Android server that clients can connect to. See the following example:- *- * **Usage**- *- * Server Side:- *- * ```js- * const { _android } = require('playwright');- *- * (async () => {- * const browserServer = await _android.launchServer({- * // If you have multiple devices connected and want to use a specific one.- * // deviceSerialNumber: '<deviceSerialNumber>',- * });- * const wsEndpoint = browserServer.wsEndpoint();- * console.log(wsEndpoint);- * })();- * ```- *- * Client Side:- *- * ```js- * const { _android } = require('playwright');- *- * (async () => {- * const device = await _android.connect('<wsEndpoint>');- *- * console.log(device.model());- * console.log(device.serial());- * await device.shell('am force-stop com.android.chrome');- * const context = await device.launchBrowser();- *- * const page = await context.newPage();- * await page.goto('https://webkit.org/');- * console.log(await page.evaluate(() => window.location.href));- * await page.screenshot({ path: 'page-chrome-1.png' });- *- * await context.close();- * })();- * ```- *- * @param options- */- launchServer(options?: {- /**- * Optional host to establish ADB server connection. Default to `127.0.0.1`.- */- adbHost?: string;+ /**+ * Path to the PFX or PKCS12 encoded private key and certificate chain.+ */+ pfxPath?: string;- /**- * Optional port to establish ADB server connection. Default to `5037`.- */- adbPort?: number;+ /**+ * Direct value of the PFX or PKCS12 encoded private key and certificate chain.+ */+ pfx?: Buffer;- /**- * Optional device serial number to launch the browser on. If not specified, it will throw if multiple devices are- * connected.- */- deviceSerialNumber?: string;+ /**+ * Passphrase for the private key (PEM or PFX).+ */+ passphrase?: string;+ }>;/**- * Host to use for the web socket. It is optional and defaults to `localhost`, accepting connections only from the- * loopback interface. Pass an explicit address (e.g. `0.0.0.0`) to accept connections from the network — be aware- * this exposes the device RPC to anything that can reach the listening port.+ * An object containing additional HTTP headers to be sent with every request. Defaults to none.*/- host?: string;+ extraHTTPHeaders?: { [key: string]: string; };/**- * Prevents automatic playwright driver installation on attach. Assumes that the drivers have been installed already.+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status+ * codes.*/- omitDriverInstall?: boolean;+ failOnStatusCode?: boolean;/**- * Port to use for the web socket. Defaults to 0 that picks any available port.+ * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no+ * origin is specified, the username and password are sent to any servers upon unauthorized responses.*/- port?: number;+ httpCredentials?: {+ username: string;- /**- * Path at which to serve the Android Server. For security, this defaults to an unguessable string.- *- * **NOTE** Any process or web page (including those running in Playwright) with knowledge of the `wsPath` can take- * control of the OS user. For this reason, you should use an unguessable token when using this option.- *+ password: string;++ /**+ * Restrain sending http credentials on specific origin (scheme://host:port).+ */+ origin?: string;++ /**+ * This option only applies to the requests sent from corresponding+ * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) and does not affect requests sent from+ * the browser. `'always'` - `Authorization` header with basic authentication credentials will be sent with the each+ * API request. `'unauthorized` - the credentials are only sent when 401 (Unauthorized) response with+ * `WWW-Authenticate` header is received. Defaults to `'unauthorized'`.+ */+ send?: "unauthorized"|"always";+ };++ /**+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.*/- wsPath?: string;- }): Promise<BrowserServer>;+ ignoreHTTPSErrors?: boolean;- /**- * This setting will change the default maximum time for all the methods accepting- * [`timeout`](https://playwright.dev/docs/api/class-android#android-set-default-timeout-option-timeout) option.- * @param timeout Maximum time in milliseconds- */- setDefaultTimeout(timeout: number): void;-}+ /**+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects. This can be overwritten for each request+ * individually.+ */+ maxRedirects?: number;-/**- * [AndroidDevice](https://playwright.dev/docs/api/class-androiddevice) represents a connected device, either real- * hardware or emulated. Devices can be obtained using- * [android.devices([options])](https://playwright.dev/docs/api/class-android#android-devices).- */-export interface AndroidDevice {- /**- * Emitted when the device connection gets closed.- */- on(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;+ /**+ * Network proxy settings.+ */+ proxy?: {+ /**+ * Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example `http://myproxy.com:3128` or+ * `socks5://myproxy.com:3128`. Short form `myproxy.com:3128` is considered an HTTP proxy.+ */+ server: string;- /**- * Emitted when a new WebView instance is detected.- */- on(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;+ /**+ * Optional comma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.+ */+ bypass?: string;- /**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.- */- once(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;+ /**+ * Optional username to use if HTTP proxy requires authentication.+ */+ username?: string;- /**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.- */- once(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;+ /**+ * Optional password to use if HTTP proxy requires authentication.+ */+ password?: string;+ };- /**- * Emitted when the device connection gets closed.- */- addListener(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;+ /**+ * Populates context with given storage state. This option can be used to initialize context with logged-in+ * information obtained via+ * [browserContext.storageState([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-storage-state)+ * or+ * [apiRequestContext.storageState([options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-storage-state).+ * Either a path to the file with saved storage, or the value returned by one of+ * [browserContext.storageState([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-storage-state)+ * or+ * [apiRequestContext.storageState([options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-storage-state)+ * methods.+ */+ storageState?: string|{+ cookies: Array<{+ name: string;- /**- * Emitted when a new WebView instance is detected.- */- addListener(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;+ value: string;- /**- * Removes an event listener added by `on` or `addListener`.- */- removeListener(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;+ domain: string;- /**- * Removes an event listener added by `on` or `addListener`.- */- removeListener(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;+ path: string;- /**- * Removes an event listener added by `on` or `addListener`.- */- off(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;+ /**+ * Unix time in seconds.+ */+ expires: number;- /**- * Removes an event listener added by `on` or `addListener`.- */- off(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;+ httpOnly: boolean;- /**- * Emitted when the device connection gets closed.- */- prependListener(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;+ secure: boolean;- /**- * Emitted when a new WebView instance is detected.- */- prependListener(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;+ sameSite: "Strict"|"Lax"|"None";+ }>;- /**- * Disconnects from the device.- */- close(): Promise<void>;+ origins: Array<{+ origin: string;- /**- * Drags the widget defined by- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-drag-option-selector) towards- * [`dest`](https://playwright.dev/docs/api/class-androiddevice#android-device-drag-option-dest) point.- * @param selector Selector to drag.- * @param dest Point to drag to.- * @param options- */- drag(selector: AndroidSelector, dest: {- x: number;+ localStorage: Array<{+ name: string;++ value: string;+ }>;+ }>;+ };- y: number;- }, options?: {/**- * Optional speed of the drag in pixels per second.+ * Maximum time in milliseconds to wait for the response. Defaults to `30000` (30 seconds). Pass `0` to disable+ * timeout.*/- speed?: number;+ timeout?: number;/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Specific user agent to use in this context.*/- timeout?: number;- }): Promise<void>;+ userAgent?: string;+ }): Promise<APIRequestContext>;+}+/**+ * This API is used for the Web API testing. You can use it to trigger API endpoints, configure micro-services,+ * prepare environment or the service to your e2e test.+ *+ * Each Playwright browser context has an associated+ * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext), accessible via+ * [browserContext.request](https://playwright.dev/docs/api/class-browsercontext#browser-context-request) or+ * [page.request](https://playwright.dev/docs/api/class-page#page-request) (these return the+ *+ * **same instance** — `page.request` is a shortcut for `page.context().request`). You can also create a standalone,+ * isolated instance with+ * [apiRequest.newContext([options])](https://playwright.dev/docs/api/class-apirequest#api-request-new-context).+ *+ * **Cookie management**+ *+ * The [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) returned by+ * [browserContext.request](https://playwright.dev/docs/api/class-browsercontext#browser-context-request) and+ *+ * [page.request](https://playwright.dev/docs/api/class-page#page-request) uses the same cookie jar as its+ * [BrowserContext](https://playwright.dev/docs/api/class-browsercontext):+ *+ * If you want API requests that do **not** share cookies with the browser, create an isolated context via+ * [apiRequest.newContext([options])](https://playwright.dev/docs/api/class-apirequest#api-request-new-context). Such+ * `APIRequestContext` object will have its own isolated cookie storage.+ */+export interface APIRequestContext {/**- * Fills the specific- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-fill-option-selector) input box- * with [`text`](https://playwright.dev/docs/api/class-androiddevice#android-device-fill-option-text).- * @param selector Selector to fill.- * @param text Text to be filled in the input box.+ * Sends HTTP(S) [DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE) request and returns its+ * response. The method will populate request cookies from the context and update context cookies from the response.+ * The method will automatically follow redirects.+ * @param url Target URL.* @param options*/- fill(selector: AndroidSelector, text: string, options?: {+ delete(url: string, options?: {/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string+ * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`+ * header will be set to `application/octet-stream` if not explicitly set.*/- timeout?: number;- }): Promise<void>;+ data?: string|Buffer|Serializable;- /**- * Flings the widget defined by- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-fling-option-selector) in the- * specified [`direction`](https://playwright.dev/docs/api/class-androiddevice#android-device-fling-option-direction).- * @param selector Selector to fling.- * @param direction Fling direction.- * @param options- */- fling(selector: AndroidSelector, direction: "down"|"up"|"left"|"right", options?: {/**- * Optional speed of the fling in pixels per second.+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status+ * codes.*/- speed?: number;+ failOnStatusCode?: boolean;/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent+ * as this request body. If this parameter is specified `content-type` header will be set to+ * `application/x-www-form-urlencoded` unless explicitly provided.*/- timeout?: number;- }): Promise<void>;-- /**- * Returns information about a widget defined by- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-info-option-selector).- * @param selector Selector to return information about.- */- info(selector: AndroidSelector): Promise<AndroidElementInfo>;-- /**- * Installs an apk on the device.- * @param file Either a path to the apk file, or apk file content.- * @param options- */- installApk(file: string|Buffer, options?: {- /**- * Optional arguments to pass to the `shell:cmd package install` call. Defaults to `-r -t -S`.- */- args?: Array<string>;- }): Promise<void>;-- /**- * Launches Chrome browser on the device, and returns its persistent context.- * @param options- */- launchBrowser(options?: {- /**- * Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.- */- acceptDownloads?: boolean;-- /**- * **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality.- *- * Additional arguments to pass to the browser instance. The list of Chromium flags can be found- * [here](https://peter.sh/experiments/chromium-command-line-switches/).- */- args?: Array<string>;-- /**- * When using [page.goto(url[, options])](https://playwright.dev/docs/api/class-page#page-goto),- * [page.route(url, handler[, options])](https://playwright.dev/docs/api/class-page#page-route),- * [page.waitForURL(url[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-url),- * [page.waitForRequest(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-request),- * or- * [page.waitForResponse(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-response)- * it takes the base URL in consideration by using the- * [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL.- * Unset by default. Examples:- * - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`- * - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in- * `http://localhost:3000/foo/bar.html`- * - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in- * `http://localhost:3000/bar.html`- */- baseURL?: string;-- /**- * Toggles bypassing page's Content-Security-Policy. Defaults to `false`.- */- bypassCSP?: boolean;+ form?: { [key: string]: string|number|boolean; }|FormData;/**- * Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)- * media feature, supported values are `'light'` and `'dark'`. See- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.- * Passing `null` resets emulation to system defaults. Defaults to `'light'`.+ * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by+ * it.*/- colorScheme?: null|"light"|"dark"|"no-preference";+ headers?: { [key: string]: string; };/**- * Emulates `'prefers-contrast'` media feature, supported values are `'no-preference'`, `'more'`. See- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.- * Passing `null` resets emulation to system defaults. Defaults to `'no-preference'`.+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.*/- contrast?: null|"no-preference"|"more";+ ignoreHTTPSErrors?: boolean;/**- * Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about- * [emulating devices with device scale factor](https://playwright.dev/docs/emulation#devices).+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.*/- deviceScaleFactor?: number;+ maxRedirects?: number;/**- * An object containing additional HTTP headers to be sent with every request. Defaults to none.+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.*/- extraHTTPHeaders?: { [key: string]: string; };+ maxRetries?: number;/**- * Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.- * Passing `null` resets emulation to system defaults. Defaults to `'none'`.+ * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this+ * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless+ * explicitly provided. File values can be passed either as+ * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file+ * name, mime-type and its content.*/- forcedColors?: null|"active"|"none";-- geolocation?: {+ multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{/**- * Latitude between -90 and 90.+ * File name*/- latitude: number;+ name: string;/**- * Longitude between -180 and 180.+ * File type*/- longitude: number;+ mimeType: string;/**- * Non-negative accuracy value. Defaults to `0`.+ * File content*/- accuracy?: number;- };+ buffer: Buffer;+ }; };/**- * Specifies if viewport supports touch events. Defaults to false. Learn more about- * [mobile emulation](https://playwright.dev/docs/emulation#devices).+ * Query parameters to be sent with the URL.*/- hasTouch?: boolean;+ params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;/**- * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no- * origin is specified, the username and password are sent to any servers upon unauthorized responses.+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.*/- httpCredentials?: {- username: string;-- password: string;-- /**- * Restrain sending http credentials on specific origin (scheme://host:port).- */- origin?: string;+ timeout?: number;+ }): Promise<APIResponse>;- /**- * This option only applies to the requests sent from corresponding- * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) and does not affect requests sent from- * the browser. `'always'` - `Authorization` header with basic authentication credentials will be sent with the each- * API request. `'unauthorized` - the credentials are only sent when 401 (Unauthorized) response with- * `WWW-Authenticate` header is received. Defaults to `'unauthorized'`.- */- send?: "unauthorized"|"always";- };+ /**+ * All responses returned by+ * [apiRequestContext.get(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-get)+ * and similar methods are stored in the memory, so that you can later call+ * [apiResponse.body()](https://playwright.dev/docs/api/class-apiresponse#api-response-body).This method discards all+ * its resources, calling any method on disposed+ * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) will throw an exception.+ * @param options+ */+ dispose(options?: {+ /**+ * The reason to be reported to the operations interrupted by the context disposal.+ */+ reason?: string;+ }): Promise<void>;+ /**+ * Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and+ * update context cookies from the response. The method will automatically follow redirects.+ *+ * **Usage**+ *+ * JSON objects can be passed directly to the request:+ *+ * ```js+ * await request.fetch('https://example.com/api/createBook', {+ * method: 'post',+ * data: {+ * title: 'Book Title',+ * author: 'John Doe',+ * }+ * });+ * ```+ *+ * The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data`+ * encoding, by specifiying the `multipart` parameter:+ *+ * ```js+ * const form = new FormData();+ * form.set('name', 'John');+ * form.append('name', 'Doe');+ * // Send two file fields with the same name.+ * form.append('file', new File(['console.log(2024);'], 'f1.js', { type: 'text/javascript' }));+ * form.append('file', new File(['hello'], 'f2.txt', { type: 'text/plain' }));+ * await request.fetch('https://example.com/api/uploadForm', {+ * multipart: form+ * });+ * ```+ *+ * @param urlOrRequest Target URL or Request to get all parameters from.+ * @param options+ */+ fetch(urlOrRequest: string|Request, options?: {/**- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.+ * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string+ * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`+ * header will be set to `application/octet-stream` if not explicitly set.*/- ignoreHTTPSErrors?: boolean;+ data?: string|Buffer|Serializable;/**- * Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,- * so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more- * about [mobile emulation](https://playwright.dev/docs/emulation#ismobile).+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status+ * codes.*/- isMobile?: boolean;+ failOnStatusCode?: boolean;/**- * Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about- * [disabling JavaScript](https://playwright.dev/docs/emulation#javascript-enabled).+ * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent+ * as this request body. If this parameter is specified `content-type` header will be set to+ * `application/x-www-form-urlencoded` unless explicitly provided.*/- javaScriptEnabled?: boolean;+ form?: { [key: string]: string|number|boolean; }|FormData;/**- * Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value,- * `Accept-Language` request header value as well as number and date formatting rules. Defaults to the system default- * locale. Learn more about emulation in our [emulation guide](https://playwright.dev/docs/emulation#locale--timezone).+ * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by+ * it.*/- locale?: string;+ headers?: { [key: string]: string; };/**- * Logger sink for Playwright logging.- * @deprecated The logs received by the logger are incomplete. Please use tracing instead.+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.*/- logger?: Logger;+ ignoreHTTPSErrors?: boolean;/**- * Whether to emulate network being offline. Defaults to `false`. Learn more about- * [network emulation](https://playwright.dev/docs/emulation#offline).+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.*/- offline?: boolean;+ maxRedirects?: number;/**- * A list of permissions to grant to all pages in this context. See- * [browserContext.grantPermissions(permissions[, options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-grant-permissions)- * for more details. Defaults to none.+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.*/- permissions?: Array<string>;+ maxRetries?: number;/**- * Optional package name to launch instead of default Chrome for Android.+ * If set changes the fetch method (e.g. [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) or+ * [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)). If not specified, GET method is used.*/- pkg?: string;+ method?: string;/**- * Network proxy settings.+ * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this+ * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless+ * explicitly provided. File values can be passed either as+ * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file+ * name, mime-type and its content.*/- proxy?: {+ multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{/**- * Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example `http://myproxy.com:3128` or- * `socks5://myproxy.com:3128`. Short form `myproxy.com:3128` is considered an HTTP proxy.+ * File name*/- server: string;+ name: string;/**- * Optional comma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.+ * File type*/- bypass?: string;+ mimeType: string;/**- * Optional username to use if HTTP proxy requires authentication.+ * File content*/- username?: string;+ buffer: Buffer;+ }; };- /**- * Optional password to use if HTTP proxy requires authentication.- */- password?: string;- };+ /**+ * Query parameters to be sent with the URL.+ */+ params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;/**- * Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into `recordHar.path` file.- * If not specified, the HAR is not recorded. Make sure to await- * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for- * the HAR to be saved.+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.*/- recordHar?: {- /**- * Optional setting to control whether to omit request content from the HAR. Defaults to `false`. Deprecated, use- * `content` policy instead.- */- omitContent?: boolean;+ timeout?: number;+ }): Promise<APIResponse>;- /**- * Optional setting to control resource content management. If `omit` is specified, content is not persisted. If- * `attach` is specified, resources are persisted as separate files or entries in the ZIP archive. If `embed` is- * specified, content is stored inline the HAR file as per HAR specification. Defaults to `attach` for `.zip` output- * files and to `embed` for all other file extensions.- */- content?: "omit"|"embed"|"attach";+ /**+ * Sends HTTP(S) [GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET) request and returns its+ * response. The method will populate request cookies from the context and update context cookies from the response.+ * The method will automatically follow redirects.+ *+ * **Usage**+ *+ * Request parameters can be configured with `params` option, they will be serialized into the URL search parameters:+ *+ * ```js+ * // Passing params as object+ * await request.get('https://example.com/api/getText', {+ * params: {+ * 'isbn': '1234',+ * 'page': 23,+ * }+ * });+ *+ * // Passing params as URLSearchParams+ * const searchParams = new URLSearchParams();+ * searchParams.set('isbn', '1234');+ * searchParams.append('page', 23);+ * searchParams.append('page', 24);+ * await request.get('https://example.com/api/getText', { params: searchParams });+ *+ * // Passing params as string+ * const queryString = 'isbn=1234&page=23&page=24';+ * await request.get('https://example.com/api/getText', { params: queryString });+ * ```+ *+ * @param url Target URL.+ * @param options+ */+ get(url: string, options?: {+ /**+ * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string+ * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`+ * header will be set to `application/octet-stream` if not explicitly set.+ */+ data?: string|Buffer|Serializable;- /**- * Path on the filesystem to write the HAR file to. If the file name ends with `.zip`, `content: 'attach'` is used by- * default.- */- path: string;+ /**+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status+ * codes.+ */+ failOnStatusCode?: boolean;- /**- * When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,- * cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.- */- mode?: "full"|"minimal";+ /**+ * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent+ * as this request body. If this parameter is specified `content-type` header will be set to+ * `application/x-www-form-urlencoded` unless explicitly provided.+ */+ form?: { [key: string]: string|number|boolean; }|FormData;- /**- * A glob or regex pattern to filter requests that are stored in the HAR. When a- * [`baseURL`](https://playwright.dev/docs/api/class-browser#browser-new-context-option-base-url) via the context- * options was provided and the passed URL is a path, it gets merged via the- * [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor. Defaults to none.- */- urlFilter?: string|RegExp;- };+ /**+ * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by+ * it.+ */+ headers?: { [key: string]: string; };/**- * Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded.- * Make sure to await- * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for- * videos to be saved.+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.*/- recordVideo?: {+ ignoreHTTPSErrors?: boolean;++ /**+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.+ */+ maxRedirects?: number;++ /**+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.+ */+ maxRetries?: number;++ /**+ * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this+ * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless+ * explicitly provided. File values can be passed either as+ * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file+ * name, mime-type and its content.+ */+ multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{/**- * Path to the directory to put videos into. If not specified, the videos will be stored in `artifactsDir` (see- * [browserType.launch([options])](https://playwright.dev/docs/api/class-browsertype#browser-type-launch) options).+ * File name*/- dir?: string;+ name: string;/**- * Optional dimensions of the recorded videos. If not specified the size will be equal to `viewport` scaled down to- * fit into 800x800. If `viewport` is not configured explicitly the video size defaults to 800x450. Actual picture of- * each page will be scaled down if necessary to fit the specified size.+ * File type*/- size?: {- /**- * Video frame width.- */- width: number;-- /**- * Video frame height.- */- height: number;- };+ mimeType: string;/**- * If specified, enables visual annotations on interacted elements during video recording.+ * File content*/- showActions?: {- /**- * How long each annotation is displayed in milliseconds. Defaults to `500`.- */- duration?: number;-- /**- * Position of the action title overlay. Defaults to `"top-right"`.- */- position?: "top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right";-- /**- * Font size of the action title in pixels. Defaults to `24`.- */- fontSize?: number;- };- };+ buffer: Buffer;+ }; };/**- * Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.- * Passing `null` resets emulation to system defaults. Defaults to `'no-preference'`.+ * Query parameters to be sent with the URL.*/- reducedMotion?: null|"reduce"|"no-preference";+ params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;/**- * Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the- * [`viewport`](https://playwright.dev/docs/api/class-androiddevice#android-device-launch-browser-option-viewport) is- * set.+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.*/- screen?: {- /**- * page width in pixels.- */- width: number;+ timeout?: number;+ }): Promise<APIResponse>;- /**- * page height in pixels.- */- height: number;- };+ /**+ * Sends HTTP(S) [HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD) request and returns its+ * response. The method will populate request cookies from the context and update context cookies from the response.+ * The method will automatically follow redirects.+ * @param url Target URL.+ * @param options+ */+ head(url: string, options?: {+ /**+ * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string+ * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`+ * header will be set to `application/octet-stream` if not explicitly set.+ */+ data?: string|Buffer|Serializable;/**- * Whether to allow sites to register Service workers. Defaults to `'allow'`.- * - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be- * registered.- * - `'block'`: Playwright will block all registration of Service Workers.+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status+ * codes.*/- serviceWorkers?: "allow"|"block";+ failOnStatusCode?: boolean;/**- * If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on- * selectors that imply single target DOM element will throw when more than one element matches the selector. This- * option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See- * [Locator](https://playwright.dev/docs/api/class-locator) to learn more about the strict mode.+ * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent+ * as this request body. If this parameter is specified `content-type` header will be set to+ * `application/x-www-form-urlencoded` unless explicitly provided.*/- strictSelectors?: boolean;+ form?: { [key: string]: string|number|boolean; }|FormData;/**- * Changes the timezone of the context. See- * [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)- * for a list of supported timezone IDs. Defaults to the system timezone.+ * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by+ * it.*/- timezoneId?: string;+ headers?: { [key: string]: string; };/**- * Specific user agent to use in this context.+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.*/- userAgent?: string;+ ignoreHTTPSErrors?: boolean;/**- * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use `null` to disable the consistent- * viewport emulation. Learn more about [viewport emulation](https://playwright.dev/docs/emulation#viewport).- *- * **NOTE** The `null` value opts out from the default presets, makes viewport depend on the host window size defined- * by the operating system. It makes the execution of the tests non-deterministic.- *+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.*/- viewport?: null|{- /**- * page width in pixels.- */- width: number;+ maxRedirects?: number;- /**- * page height in pixels.- */- height: number;- };- }): Promise<BrowserContext>;+ /**+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.+ */+ maxRetries?: number;- /**- * Performs a long tap on the widget defined by- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-long-tap-option-selector).- * @param selector Selector to tap on.- * @param options- */- longTap(selector: AndroidSelector, options?: {/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this+ * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless+ * explicitly provided. File values can be passed either as+ * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file+ * name, mime-type and its content.*/- timeout?: number;- }): Promise<void>;+ multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{+ /**+ * File name+ */+ name: string;- /**- * Device model.- */- model(): string;+ /**+ * File type+ */+ mimeType: string;- /**- * Launches a process in the shell on the device and returns a socket to communicate with the launched process.- * @param command Shell command to execute.- */- open(command: string): Promise<AndroidSocket>;+ /**+ * File content+ */+ buffer: Buffer;+ }; };- /**- * Pinches the widget defined by- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-pinch-close-option-selector) in the- * closing direction.- * @param selector Selector to pinch close.- * @param percent The size of the pinch as a percentage of the widget's size.- * @param options- */- pinchClose(selector: AndroidSelector, percent: number, options?: {/**- * Optional speed of the pinch in pixels per second.+ * Query parameters to be sent with the URL.*/- speed?: number;+ params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.*/timeout?: number;- }): Promise<void>;+ }): Promise<APIResponse>;/**- * Pinches the widget defined by- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-pinch-open-option-selector) in the- * open direction.- * @param selector Selector to pinch open.- * @param percent The size of the pinch as a percentage of the widget's size.+ * Sends HTTP(S) [PATCH](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) request and returns its+ * response. The method will populate request cookies from the context and update context cookies from the response.+ * The method will automatically follow redirects.+ * @param url Target URL.* @param options*/- pinchOpen(selector: AndroidSelector, percent: number, options?: {+ patch(url: string, options?: {/**- * Optional speed of the pinch in pixels per second.+ * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string+ * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`+ * header will be set to `application/octet-stream` if not explicitly set.*/- speed?: number;+ data?: string|Buffer|Serializable;/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status+ * codes.*/- timeout?: number;- }): Promise<void>;+ failOnStatusCode?: boolean;- /**- * Presses the specific [`key`](https://playwright.dev/docs/api/class-androiddevice#android-device-press-option-key)- * in the widget defined by- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-press-option-selector).- * @param selector Selector to press the key in.- * @param key The key to press.- * @param options- */- press(selector: AndroidSelector, key: AndroidKey, options?: {/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent+ * as this request body. If this parameter is specified `content-type` header will be set to+ * `application/x-www-form-urlencoded` unless explicitly provided.*/- timeout?: number;- }): Promise<void>;+ form?: { [key: string]: string|number|boolean; }|FormData;- /**- * Copies a file to the device.- * @param file Either a path to the file, or file content.- * @param path Path to the file on the device.- * @param options- */- push(file: string|Buffer, path: string, options?: {/**- * Optional file mode, defaults to `644` (`rw-r--r--`).+ * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by+ * it.*/- mode?: number;- }): Promise<void>;+ headers?: { [key: string]: string; };- /**- * Returns the buffer with the captured screenshot of the device.- * @param options- */- screenshot(options?: {/**- * The file path to save the image to. If- * [`path`](https://playwright.dev/docs/api/class-androiddevice#android-device-screenshot-option-path) is a relative- * path, then it is resolved relative to the current working directory. If no path is provided, the image won't be- * saved to the disk.+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.*/- path?: string;- }): Promise<Buffer>;+ ignoreHTTPSErrors?: boolean;- /**- * Scrolls the widget defined by- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-scroll-option-selector) in the- * specified- * [`direction`](https://playwright.dev/docs/api/class-androiddevice#android-device-scroll-option-direction).- * @param selector Selector to scroll.- * @param direction Scroll direction.- * @param percent Distance to scroll as a percentage of the widget's size.- * @param options- */- scroll(selector: AndroidSelector, direction: "down"|"up"|"left"|"right", percent: number, options?: {/**- * Optional speed of the scroll in pixels per second.+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.*/- speed?: number;+ maxRedirects?: number;/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.*/- timeout?: number;- }): Promise<void>;-- /**- * Device serial number.- */- serial(): string;-- /**- * This setting will change the default maximum time for all the methods accepting- * [`timeout`](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout-option-timeout)- * option.- * @param timeout Maximum time in milliseconds- */- setDefaultTimeout(timeout: number): void;-- /**- * Executes a shell command on the device and returns its output.- * @param command Shell command to execute.- */- shell(command: string): Promise<Buffer>;+ maxRetries?: number;- /**- * Swipes the widget defined by- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-swipe-option-selector) in the- * specified [`direction`](https://playwright.dev/docs/api/class-androiddevice#android-device-swipe-option-direction).- * @param selector Selector to swipe.- * @param direction Swipe direction.- * @param percent Distance to swipe as a percentage of the widget's size.- * @param options- */- swipe(selector: AndroidSelector, direction: "down"|"up"|"left"|"right", percent: number, options?: {/**- * Optional speed of the swipe in pixels per second.+ * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this+ * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless+ * explicitly provided. File values can be passed either as+ * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file+ * name, mime-type and its content.*/- speed?: number;+ multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{+ /**+ * File name+ */+ name: string;- /**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.- */- timeout?: number;- }): Promise<void>;+ /**+ * File type+ */+ mimeType: string;++ /**+ * File content+ */+ buffer: Buffer;+ }; };- /**- * Taps on the widget defined by- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-tap-option-selector).- * @param selector Selector to tap on.- * @param options- */- tap(selector: AndroidSelector, options?: {/**- * Optional duration of the tap in milliseconds.+ * Query parameters to be sent with the URL.*/- duration?: number;+ params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.*/timeout?: number;- }): Promise<void>;+ }): Promise<APIResponse>;/**- * Waits for the specific- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-wait-option-selector) to either- * appear or disappear, depending on the- * [`state`](https://playwright.dev/docs/api/class-androiddevice#android-device-wait-option-state).- * @param selector Selector to wait for.- * @param options- */- wait(selector: AndroidSelector, options?: {- /**- * Optional state. Can be either:- * - default - wait for element to be present.- * - `'gone'` - wait for element to not be present.- */- state?: "gone";+ * Sends HTTP(S) [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) request and returns its+ * response. The method will populate request cookies from the context and update context cookies from the response.+ * The method will automatically follow redirects.+ *+ * **Usage**+ *+ * JSON objects can be passed directly to the request:+ *+ * ```js+ * await request.post('https://example.com/api/createBook', {+ * data: {+ * title: 'Book Title',+ * author: 'John Doe',+ * }+ * });+ * ```+ *+ * To send form data to the server use `form` option. Its value will be encoded into the request body with+ * `application/x-www-form-urlencoded` encoding (see below how to use `multipart/form-data` form encoding to send+ * files):+ *+ * ```js+ * await request.post('https://example.com/api/findBook', {+ * form: {+ * title: 'Book Title',+ * author: 'John Doe',+ * }+ * });+ * ```+ *+ * The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data`+ * encoding. Use [FormData] to construct request body and pass it to the request as `multipart` parameter:+ *+ * ```js+ * const form = new FormData();+ * form.set('name', 'John');+ * form.append('name', 'Doe');+ * // Send two file fields with the same name.+ * form.append('file', new File(['console.log(2024);'], 'f1.js', { type: 'text/javascript' }));+ * form.append('file', new File(['hello'], 'f2.txt', { type: 'text/plain' }));+ * await request.post('https://example.com/api/uploadForm', {+ * multipart: form+ * });+ * ```+ *+ * @param url Target URL.+ * @param options+ */+ post(url: string, options?: {+ /**+ * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string+ * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`+ * header will be set to `application/octet-stream` if not explicitly set.+ */+ data?: string|Buffer|Serializable;/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status+ * codes.*/- timeout?: number;- }): Promise<void>;+ failOnStatusCode?: boolean;- /**- * Emitted when the device connection gets closed.- */- waitForEvent(event: 'close', optionsOrPredicate?: { predicate?: (androidDevice: AndroidDevice) => boolean | Promise<boolean>, timeout?: number } | ((androidDevice: AndroidDevice) => boolean | Promise<boolean>)): Promise<AndroidDevice>;+ /**+ * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent+ * as this request body. If this parameter is specified `content-type` header will be set to+ * `application/x-www-form-urlencoded` unless explicitly provided.+ */+ form?: { [key: string]: string|number|boolean; }|FormData;- /**- * Emitted when a new WebView instance is detected.- */- waitForEvent(event: 'webview', optionsOrPredicate?: { predicate?: (androidWebView: AndroidWebView) => boolean | Promise<boolean>, timeout?: number } | ((androidWebView: AndroidWebView) => boolean | Promise<boolean>)): Promise<AndroidWebView>;+ /**+ * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by+ * it.+ */+ headers?: { [key: string]: string; };+ /**+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.+ */+ ignoreHTTPSErrors?: boolean;- /**- * This method waits until [AndroidWebView](https://playwright.dev/docs/api/class-androidwebview) matching the- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-web-view-option-selector) is opened- * and returns it. If there is already an open [AndroidWebView](https://playwright.dev/docs/api/class-androidwebview)- * matching the- * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-web-view-option-selector), returns- * immediately.- * @param selector- * @param options- */- webView(selector: {/**- * Optional Package identifier.+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.*/- pkg?: string;+ maxRedirects?: number;/**- * Optional webview socket name.+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.*/- socketName?: string;- }, options?: {+ maxRetries?: number;+/**- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed- * by using the- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)- * method.+ * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this+ * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless+ * explicitly provided. File values can be passed either as+ * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file+ * name, mime-type and its content.*/- timeout?: number;- }): Promise<AndroidWebView>;+ multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{+ /**+ * File name+ */+ name: string;- /**- * Currently open WebViews.- */- webViews(): Array<AndroidWebView>;+ /**+ * File type+ */+ mimeType: string;- input: AndroidInput;+ /**+ * File content+ */+ buffer: Buffer;+ }; };- [Symbol.asyncDispose](): Promise<void>;-}+ /**+ * Query parameters to be sent with the URL.+ */+ params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;++ /**+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.+ */+ timeout?: number;+ }): Promise<APIResponse>;-export interface AndroidInput {/**- * Performs a drag between [`from`](https://playwright.dev/docs/api/class-androidinput#android-input-drag-option-from)- * and [`to`](https://playwright.dev/docs/api/class-androidinput#android-input-drag-option-to) points.- * @param from The start point of the drag.- * @param to The end point of the drag.- * @param steps The number of steps in the drag. Each step takes 5 milliseconds to complete.+ * Sends HTTP(S) [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) request and returns its+ * response. The method will populate request cookies from the context and update context cookies from the response.+ * The method will automatically follow redirects.+ * @param url Target URL.+ * @param options*/- drag(from: {- x: number;+ put(url: string, options?: {+ /**+ * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string+ * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`+ * header will be set to `application/octet-stream` if not explicitly set.+ */+ data?: string|Buffer|Serializable;- y: number;- }, to: {- x: number;+ /**+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status+ * codes.+ */+ failOnStatusCode?: boolean;- y: number;- }, steps: number): Promise<void>;+ /**+ * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent+ * as this request body. If this parameter is specified `content-type` header will be set to+ * `application/x-www-form-urlencoded` unless explicitly provided.+ */+ form?: { [key: string]: string|number|boolean; }|FormData;- /**- * Presses the [`key`](https://playwright.dev/docs/api/class-androidinput#android-input-press-option-key).- * @param key Key to press.- */- press(key: AndroidKey): Promise<void>;+ /**+ * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by+ * it.+ */+ headers?: { [key: string]: string; };- /**- * Swipes following the path defined by- * [`segments`](https://playwright.dev/docs/api/class-androidinput#android-input-swipe-option-segments).- * @param from The point to start swiping from.- * @param segments Points following the [`from`](https://playwright.dev/docs/api/class-androidinput#android-input-swipe-option-from)- * point in the swipe gesture.- * @param steps The number of steps for each segment. Each step takes 5 milliseconds to complete, so 100 steps means half a second- * per each segment.- */- swipe(from: {- x: number;+ /**+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.+ */+ ignoreHTTPSErrors?: boolean;- y: number;- }, segments: ReadonlyArray<{- x: number;+ /**+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.+ */+ maxRedirects?: number;- y: number;- }>, steps: number): Promise<void>;+ /**+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.+ */+ maxRetries?: number;- /**- * Taps at the specified [`point`](https://playwright.dev/docs/api/class-androidinput#android-input-tap-option-point).- * @param point The point to tap at.- */- tap(point: {- x: number;+ /**+ * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this+ * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless+ * explicitly provided. File values can be passed either as+ * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file+ * name, mime-type and its content.+ */+ multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{+ /**+ * File name+ */+ name: string;- y: number;- }): Promise<void>;+ /**+ * File type+ */+ mimeType: string;- /**- * Types [`text`](https://playwright.dev/docs/api/class-androidinput#android-input-type-option-text) into currently- * focused widget.- * @param text Text to type.- */- type(text: string): Promise<void>;-}+ /**+ * File content+ */+ buffer: Buffer;+ }; };-/**- * [AndroidSocket](https://playwright.dev/docs/api/class-androidsocket) is a way to communicate with a process- * launched on the [AndroidDevice](https://playwright.dev/docs/api/class-androiddevice). Use- * [androidDevice.open(command)](https://playwright.dev/docs/api/class-androiddevice#android-device-open) to open a- * socket.- */-export interface AndroidSocket {- /**- * Emitted when the socket is closed.- */- on(event: 'close', listener: () => any): this;+ /**+ * Query parameters to be sent with the URL.+ */+ params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;- /**- * Emitted when data is available to read from the socket.- */- on(event: 'data', listener: (buffer: Buffer) => any): this;+ /**+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.+ */+ timeout?: number;+ }): Promise<APIResponse>;/**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ * Returns storage state for this request context, contains current cookies and local storage snapshot if it was+ * passed to the constructor.+ * @param options*/- once(event: 'close', listener: () => any): this;+ storageState(options?: {+ /**+ * Set to `true` to include IndexedDB in the storage state snapshot.+ */+ indexedDB?: boolean;- /**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.- */- once(event: 'data', listener: (buffer: Buffer) => any): this;+ /**+ * The file path to save the storage state to. If+ * [`path`](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-storage-state-option-path) is+ * a relative path, then it is resolved relative to current working directory. If no path is provided, storage state+ * is still returned, but won't be saved to the disk.+ */+ path?: string;+ }): Promise<{+ cookies: Array<{+ name: string;++ value: string;++ domain: string;++ path: string;++ /**+ * Unix time in seconds.+ */+ expires: number;++ httpOnly: boolean;++ secure: boolean;++ sameSite: "Strict"|"Lax"|"None";+ }>;++ origins: Array<{+ origin: string;++ localStorage: Array<{+ name: string;++ value: string;+ }>;+ }>;+ }>;++ tracing: Tracing;+ [Symbol.asyncDispose](): Promise<void>;+}++/**+ * [APIResponse](https://playwright.dev/docs/api/class-apiresponse) class represents responses returned by+ * [apiRequestContext.get(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-get)+ * and similar methods.+ */+export interface APIResponse {/**- * Emitted when the socket is closed.+ * Returns the buffer with response body.*/- addListener(event: 'close', listener: () => any): this;+ body(): Promise<Buffer>;/**- * Emitted when data is available to read from the socket.+ * Disposes the body of this response. If not called then the body will stay in memory until the context closes.*/- addListener(event: 'data', listener: (buffer: Buffer) => any): this;+ dispose(): Promise<void>;/**- * Removes an event listener added by `on` or `addListener`.+ * An object with all the response HTTP headers associated with this response.*/- removeListener(event: 'close', listener: () => any): this;+ headers(): { [key: string]: string; };/**- * Removes an event listener added by `on` or `addListener`.+ * An array with all the response HTTP headers associated with this response. Header names are not lower-cased.+ * Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple times.*/- removeListener(event: 'data', listener: (buffer: Buffer) => any): this;+ headersArray(): Array<{+ /**+ * Name of the header.+ */+ name: string;++ /**+ * Value of the header.+ */+ value: string;+ }>;/**- * Removes an event listener added by `on` or `addListener`.+ * Returns the JSON representation of response body.+ *+ * This method will throw if the response body is not parsable via `JSON.parse`.*/- off(event: 'close', listener: () => any): this;+ json(): Promise<Serializable>;/**- * Removes an event listener added by `on` or `addListener`.+ * Contains a boolean stating whether the response was successful (status in the range 200-299) or not.*/- off(event: 'data', listener: (buffer: Buffer) => any): this;+ ok(): boolean;/**- * Emitted when the socket is closed.+ * Contains the status code of the response (e.g., 200 for a success).*/- prependListener(event: 'close', listener: () => any): this;+ status(): number;/**- * Emitted when data is available to read from the socket.+ * Contains the status text of the response (e.g. usually an "OK" for a success).*/- prependListener(event: 'data', listener: (buffer: Buffer) => any): this;+ statusText(): string;/**- * Closes the socket.+ * Returns the text representation of response body.*/- close(): Promise<void>;+ text(): Promise<string>;/**- * Writes some [`data`](https://playwright.dev/docs/api/class-androidsocket#android-socket-write-option-data) to the- * socket.- * @param data Data to write.+ * Contains the URL of the response.*/- write(data: Buffer): Promise<void>;+ url(): string;[Symbol.asyncDispose](): Promise<void>;}-/**- * [AndroidWebView](https://playwright.dev/docs/api/class-androidwebview) represents a WebView open on the- * [AndroidDevice](https://playwright.dev/docs/api/class-androiddevice). WebView is usually obtained using- * [androidDevice.webView(selector[, options])](https://playwright.dev/docs/api/class-androiddevice#android-device-web-view).- */-export interface AndroidWebView {+export interface BrowserServer {/**- * Emitted when the WebView is closed.+ * Emitted when the browser server closes.*/on(event: 'close', listener: () => any): this;@@ -18323,7 +18244,7 @@ export interface AndroidWebView {once(event: 'close', listener: () => any): this;/**- * Emitted when the WebView is closed.+ * Emitted when the browser server closes.*/addListener(event: 'close', listener: () => any): this;@@ -18338,4419 +18259,4498 @@ export interface AndroidWebView {off(event: 'close', listener: () => any): this;/**- * Emitted when the WebView is closed.+ * Emitted when the browser server closes.*/prependListener(event: 'close', listener: () => any): this;/**- * Connects to the WebView and returns a regular Playwright [Page](https://playwright.dev/docs/api/class-page) to- * interact with.+ * Closes the browser gracefully and makes sure the process is terminated.*/- page(): Promise<Page>;+ close(): Promise<void>;/**- * WebView process PID.+ * Kills the browser process and waits for the process to exit.*/- pid(): number;+ kill(): Promise<void>;/**- * WebView package identifier.+ * Spawned browser application process.*/- pkg(): string;+ process(): ChildProcess;++ /**+ * Browser websocket url.+ *+ * Browser websocket endpoint which can be used as an argument to+ * [browserType.connect(endpoint[, options])](https://playwright.dev/docs/api/class-browsertype#browser-type-connect)+ * to establish connection to the browser.+ */+ wsEndpoint(): string;++ [Symbol.asyncDispose](): Promise<void>;}/**- * Exposes API that can be used for the Web API testing. This class is used for creating- * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) instance which in turn can be used for- * sending web requests. An instance of this class can be obtained via- * [playwright.request](https://playwright.dev/docs/api/class-playwright#playwright-request). For more information see- * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext).+ * Accurately simulating time-dependent behavior is essential for verifying the correctness of applications. Learn+ * more about [clock emulation](https://playwright.dev/docs/clock).+ *+ * Note that clock is installed for the entire [BrowserContext](https://playwright.dev/docs/api/class-browsercontext),+ * so the time in all the pages and iframes is controlled by the same clock.*/-export interface APIRequest {+export interface Clock {/**- * Creates new instances of [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext).+ * Advance the clock by jumping forward in time. Only fires due timers at most once. This is equivalent to user+ * closing the laptop lid for a while and reopening it later, after given time.+ *+ * **Usage**+ *+ * ```js+ * await page.clock.fastForward(1000);+ * await page.clock.fastForward('30:00');+ * ```+ *+ * @param ticks Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are+ * "08" for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.+ */+ fastForward(ticks: number|string): Promise<void>;++ /**+ * Install fake implementations for the following time-related functions:+ * - `Date`+ * - `setTimeout`+ * - `clearTimeout`+ * - `setInterval`+ * - `clearInterval`+ * - `requestAnimationFrame`+ * - `cancelAnimationFrame`+ * - `requestIdleCallback`+ * - `cancelIdleCallback`+ * - `performance`+ *+ * Fake timers are used to manually control the flow of time in tests. They allow you to advance time, fire timers,+ * and control the behavior of time-dependent functions. See+ * [clock.runFor(ticks)](https://playwright.dev/docs/api/class-clock#clock-run-for) and+ * [clock.fastForward(ticks)](https://playwright.dev/docs/api/class-clock#clock-fast-forward) for more information.* @param options*/- newContext(options?: {+ install(options?: {/**- * Methods like- * [apiRequestContext.get(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-get)- * take the base URL into consideration by using the- * [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL.- * Examples:- * - baseURL: `http://localhost:3000` and sending request to `/bar.html` results in `http://localhost:3000/bar.html`- * - baseURL: `http://localhost:3000/foo/` and sending request to `./bar.html` results in- * `http://localhost:3000/foo/bar.html`- * - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in- * `http://localhost:3000/bar.html`+ * Time to initialize with, current system time by default.*/- baseURL?: string;+ time?: number|string|Date;+ }): Promise<void>;- /**- * TLS Client Authentication allows the server to request a client certificate and verify it.- *- * **Details**- *- * An array of client certificates to be used. Each certificate object must have either both `certPath` and `keyPath`,- * a single `pfxPath`, or their corresponding direct value equivalents (`cert` and `key`, or `pfx`). Optionally,- * `passphrase` property should be provided if the certificate is encrypted. The `origin` property should be provided- * with an exact match to the request origin that the certificate is valid for.- *- * Client certificate authentication is only active when at least one client certificate is provided. If you want to- * reject all client certificates sent by the server, you need to provide a client certificate with an `origin` that- * does not match any of the domains you plan to visit.- *- * **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it- * work by replacing `localhost` with `local.playwright`.- *- */- clientCertificates?: Array<{- /**- * Exact origin that the certificate is valid for. Origin includes `https` protocol, a hostname and optionally a port.- */- origin: string;-- /**- * Path to the file with the certificate in PEM format.- */- certPath?: string;-- /**- * Direct value of the certificate in PEM format.- */- cert?: Buffer;+ /**+ * Advance the clock by jumping forward in time and pause the time. Once this method is called, no timers are fired+ * unless [clock.runFor(ticks)](https://playwright.dev/docs/api/class-clock#clock-run-for),+ * [clock.fastForward(ticks)](https://playwright.dev/docs/api/class-clock#clock-fast-forward),+ * [clock.pauseAt(time)](https://playwright.dev/docs/api/class-clock#clock-pause-at) or+ * [clock.resume()](https://playwright.dev/docs/api/class-clock#clock-resume) is called.+ *+ * Only fires due timers at most once. This is equivalent to user closing the laptop lid for a while and reopening it+ * at the specified time and pausing.+ *+ * **Usage**+ *+ * ```js+ * await page.clock.pauseAt(new Date('2020-02-02'));+ * await page.clock.pauseAt('2020-02-02');+ * ```+ *+ * For best results, install the clock before navigating the page and set it to a time slightly before the intended+ * test time. This ensures that all timers run normally during page loading, preventing the page from getting stuck.+ * Once the page has fully loaded, you can safely use+ * [clock.pauseAt(time)](https://playwright.dev/docs/api/class-clock#clock-pause-at) to pause the clock.+ *+ * ```js+ * // Initialize clock with some time before the test time and let the page load+ * // naturally. `Date.now` will progress as the timers fire.+ * await page.clock.install({ time: new Date('2024-12-10T08:00:00') });+ * await page.goto('http://localhost:3333');+ * await page.clock.pauseAt(new Date('2024-12-10T10:00:00'));+ * ```+ *+ * @param time Time to pause at.+ */+ pauseAt(time: number|string|Date): Promise<void>;- /**- * Path to the file with the private key in PEM format.- */- keyPath?: string;+ /**+ * Resumes timers. Once this method is called, time resumes flowing, timers are fired as usual.+ */+ resume(): Promise<void>;- /**- * Direct value of the private key in PEM format.- */- key?: Buffer;+ /**+ * Advance the clock, firing all the time-related callbacks.+ *+ * **Usage**+ *+ * ```js+ * await page.clock.runFor(1000);+ * await page.clock.runFor('30:00');+ * ```+ *+ * @param ticks Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are+ * "08" for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.+ */+ runFor(ticks: number|string): Promise<void>;- /**- * Path to the PFX or PKCS12 encoded private key and certificate chain.- */- pfxPath?: string;+ /**+ * Makes `Date.now` and `new Date()` return fixed fake time at all times, keeps all the timers running.+ *+ * Use this method for simple scenarios where you only need to test with a predefined time. For more advanced+ * scenarios, use [clock.install([options])](https://playwright.dev/docs/api/class-clock#clock-install) instead. Read+ * docs on [clock emulation](https://playwright.dev/docs/clock) to learn more.+ *+ * **Usage**+ *+ * ```js+ * await page.clock.setFixedTime(Date.now());+ * await page.clock.setFixedTime(new Date('2020-02-02'));+ * await page.clock.setFixedTime('2020-02-02');+ * ```+ *+ * @param time Time to be set in milliseconds.+ */+ setFixedTime(time: number|string|Date): Promise<void>;- /**- * Direct value of the PFX or PKCS12 encoded private key and certificate chain.- */- pfx?: Buffer;+ /**+ * Sets system time, but does not trigger any timers. Use this to test how the web page reacts to a time shift, for+ * example switching from summer to winter time, or changing time zones.+ *+ * **Usage**+ *+ * ```js+ * await page.clock.setSystemTime(Date.now());+ * await page.clock.setSystemTime(new Date('2020-02-02'));+ * await page.clock.setSystemTime('2020-02-02');+ * ```+ *+ * @param time Time to be set in milliseconds.+ */+ setSystemTime(time: number|string|Date): Promise<void>;+}- /**- * Passphrase for the private key (PEM or PFX).- */- passphrase?: string;- }>;+/**+ * [ConsoleMessage](https://playwright.dev/docs/api/class-consolemessage) objects are dispatched by page via the+ * [page.on('console')](https://playwright.dev/docs/api/class-page#page-event-console) event. For each console message+ * logged in the page there will be corresponding event in the Playwright context.+ *+ * ```js+ * // Listen for all console logs+ * page.on('console', msg => console.log(msg.text()));+ *+ * // Listen for all console events and handle errors+ * page.on('console', msg => {+ * if (msg.type() === 'error')+ * console.log(`Error text: "${msg.text()}"`);+ * });+ *+ * // Get the next console log+ * const msgPromise = page.waitForEvent('console');+ * await page.evaluate(() => {+ * console.log('hello', 42, { foo: 'bar' }); // Issue console.log inside the page+ * });+ * const msg = await msgPromise;+ *+ * // Deconstruct console log arguments+ * await msg.args()[0].jsonValue(); // hello+ * await msg.args()[1].jsonValue(); // 42+ * ```+ *+ */+export interface ConsoleMessage {+ /**+ * List of arguments passed to a `console` function call. See also+ * [page.on('console')](https://playwright.dev/docs/api/class-page#page-event-console).+ */+ args(): Array<JSHandle>;+ location(): {/**- * An object containing additional HTTP headers to be sent with every request. Defaults to none.+ * URL of the resource.*/- extraHTTPHeaders?: { [key: string]: string; };+ url: string;/**- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status- * codes.+ * 0-based line number in the resource.*/- failOnStatusCode?: boolean;+ line: number;/**- * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no- * origin is specified, the username and password are sent to any servers upon unauthorized responses.+ * 0-based column number in the resource.*/- httpCredentials?: {- username: string;-- password: string;-- /**- * Restrain sending http credentials on specific origin (scheme://host:port).- */- origin?: string;-- /**- * This option only applies to the requests sent from corresponding- * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) and does not affect requests sent from- * the browser. `'always'` - `Authorization` header with basic authentication credentials will be sent with the each- * API request. `'unauthorized` - the credentials are only sent when 401 (Unauthorized) response with- * `WWW-Authenticate` header is received. Defaults to `'unauthorized'`.- */- send?: "unauthorized"|"always";- };+ column: number;/**- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.+ * 0-based line number in the resource. Deprecated, use `line` instead.*/- ignoreHTTPSErrors?: boolean;+ lineNumber: number;/**- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is- * exceeded. Defaults to `20`. Pass `0` to not follow redirects. This can be overwritten for each request- * individually.+ * 0-based column number in the resource. Deprecated, use `column` instead.*/- maxRedirects?: number;+ columnNumber: number;+ };- /**- * Network proxy settings.- */- proxy?: {- /**- * Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example `http://myproxy.com:3128` or- * `socks5://myproxy.com:3128`. Short form `myproxy.com:3128` is considered an HTTP proxy.- */- server: string;+ /**+ * The page that produced this console message, if any.+ */+ page(): null|Page;- /**- * Optional comma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.- */- bypass?: string;+ /**+ * The text of the console message.+ */+ text(): string;- /**- * Optional username to use if HTTP proxy requires authentication.- */- username?: string;+ /**+ * The timestamp of the console message in milliseconds since the Unix epoch.+ */+ timestamp(): number;- /**- * Optional password to use if HTTP proxy requires authentication.- */- password?: string;- };+ type(): "log"|"debug"|"info"|"error"|"warning"|"dir"|"dirxml"|"table"|"trace"|"clear"|"startGroup"|"startGroupCollapsed"|"endGroup"|"assert"|"profile"|"profileEnd"|"count"|"time"|"timeEnd";- /**- * Populates context with given storage state. This option can be used to initialize context with logged-in- * information obtained via- * [browserContext.storageState([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-storage-state)- * or- * [apiRequestContext.storageState([options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-storage-state).- * Either a path to the file with saved storage, or the value returned by one of- * [browserContext.storageState([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-storage-state)- * or- * [apiRequestContext.storageState([options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-storage-state)- * methods.- */- storageState?: string|{- cookies: Array<{- name: string;-- value: string;-- domain: string;-- path: string;-- /**- * Unix time in seconds.- */- expires: number;-- httpOnly: boolean;-- secure: boolean;-- sameSite: "Strict"|"Lax"|"None";- }>;-- origins: Array<{- origin: string;-- localStorage: Array<{- name: string;-- value: string;- }>;- }>;- };-- /**- * Maximum time in milliseconds to wait for the response. Defaults to `30000` (30 seconds). Pass `0` to disable- * timeout.- */- timeout?: number;-- /**- * Specific user agent to use in this context.- */- userAgent?: string;- }): Promise<APIRequestContext>;+ /**+ * The web worker or service worker that produced this console message, if any. Note that console messages from web+ * workers also have non-null+ * [consoleMessage.page()](https://playwright.dev/docs/api/class-consolemessage#console-message-page).+ */+ worker(): null|Worker;}/**- * This API is used for the Web API testing. You can use it to trigger API endpoints, configure micro-services,- * prepare environment or the service to your e2e test.- *- * Each Playwright browser context has an associated- * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext), accessible via- * [browserContext.request](https://playwright.dev/docs/api/class-browsercontext#browser-context-request) or- * [page.request](https://playwright.dev/docs/api/class-page#page-request) (these return the+ * Coverage gathers information about parts of JavaScript and CSS that were used by the page.*- * **same instance** — `page.request` is a shortcut for `page.context().request`). You can also create a standalone,- * isolated instance with- * [apiRequest.newContext([options])](https://playwright.dev/docs/api/class-apirequest#api-request-new-context).+ * An example of using JavaScript coverage to produce Istanbul report for page load:*- * **Cookie management**+ * **NOTE** Coverage APIs are only supported on Chromium-based browsers.*- * The [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) returned by- * [browserContext.request](https://playwright.dev/docs/api/class-browsercontext#browser-context-request) and+ * ```js+ * const { chromium } = require('playwright');+ * const v8toIstanbul = require('v8-to-istanbul');*- * [page.request](https://playwright.dev/docs/api/class-page#page-request) uses the same cookie jar as its- * [BrowserContext](https://playwright.dev/docs/api/class-browsercontext):+ * (async () => {+ * const browser = await chromium.launch();+ * const page = await browser.newPage();+ * await page.coverage.startJSCoverage();+ * await page.goto('https://chromium.org');+ * const coverage = await page.coverage.stopJSCoverage();+ * for (const entry of coverage) {+ * const converter = v8toIstanbul('', 0, { source: entry.source });+ * await converter.load();+ * converter.applyCoverage(entry.functions);+ * console.log(JSON.stringify(converter.toIstanbul()));+ * }+ * await browser.close();+ * })();+ * ```*- * If you want API requests that do **not** share cookies with the browser, create an isolated context via- * [apiRequest.newContext([options])](https://playwright.dev/docs/api/class-apirequest#api-request-new-context). Such- * `APIRequestContext` object will have its own isolated cookie storage.*/-export interface APIRequestContext {+export interface Coverage {/**- * Sends HTTP(S) [DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE) request and returns its- * response. The method will populate request cookies from the context and update context cookies from the response.- * The method will automatically follow redirects.- * @param url Target URL.+ * Returns coverage is started* @param options*/- delete(url: string, options?: {- /**- * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string- * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`- * header will be set to `application/octet-stream` if not explicitly set.- */- data?: string|Buffer|Serializable;-- /**- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status- * codes.- */- failOnStatusCode?: boolean;-+ startCSSCoverage(options?: {/**- * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent- * as this request body. If this parameter is specified `content-type` header will be set to- * `application/x-www-form-urlencoded` unless explicitly provided.+ * Whether to reset coverage on every navigation. Defaults to `true`.*/- form?: { [key: string]: string|number|boolean; }|FormData;+ resetOnNavigation?: boolean;+ }): Promise<void>;+ /**+ * Returns coverage is started+ *+ * **NOTE** Anonymous scripts are ones that don't have an associated url. These are scripts that are dynamically+ * created on the page using `eval` or `new Function`. If+ * [`reportAnonymousScripts`](https://playwright.dev/docs/api/class-coverage#coverage-start-js-coverage-option-report-anonymous-scripts)+ * is set to `true`, anonymous scripts will have `__playwright_evaluation_script__` as their URL.+ *+ * @param options+ */+ startJSCoverage(options?: {/**- * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by- * it.+ * Whether anonymous scripts generated by the page should be reported. Defaults to `false`.*/- headers?: { [key: string]: string; };+ reportAnonymousScripts?: boolean;/**- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.+ * Whether to reset coverage on every navigation. Defaults to `true`.*/- ignoreHTTPSErrors?: boolean;+ resetOnNavigation?: boolean;+ }): Promise<void>;+ /**+ * Returns the array of coverage reports for all stylesheets+ *+ * **NOTE** CSS Coverage doesn't include dynamically injected style tags without sourceURLs.+ *+ */+ stopCSSCoverage(): Promise<Array<{/**- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.+ * StyleSheet URL*/- maxRedirects?: number;+ url: string;/**- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.+ * StyleSheet content, if available.*/- maxRetries?: number;+ text?: string;/**- * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this- * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless- * explicitly provided. File values can be passed either as- * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file- * name, mime-type and its content.+ * StyleSheet ranges that were used. Ranges are sorted and non-overlapping.*/- multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{- /**- * File name- */- name: string;-+ ranges: Array<{/**- * File type+ * A start offset in text, inclusive*/- mimeType: string;+ start: number;/**- * File content+ * An end offset in text, exclusive*/- buffer: Buffer;- }; };+ end: number;+ }>;+ }>>;+ /**+ * Returns the array of coverage reports for all scripts+ *+ * **NOTE** JavaScript Coverage doesn't include anonymous scripts by default. However, scripts with sourceURLs are+ * reported.+ *+ */+ stopJSCoverage(): Promise<Array<{/**- * Query parameters to be sent with the URL.+ * Script URL*/- params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;+ url: string;/**- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.+ * Script ID*/- timeout?: number;- }): Promise<APIResponse>;+ scriptId: string;- /**- * All responses returned by- * [apiRequestContext.get(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-get)- * and similar methods are stored in the memory, so that you can later call- * [apiResponse.body()](https://playwright.dev/docs/api/class-apiresponse#api-response-body).This method discards all- * its resources, calling any method on disposed- * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) will throw an exception.- * @param options- */- dispose(options?: {/**- * The reason to be reported to the operations interrupted by the context disposal.+ * Script content, if applicable.*/- reason?: string;- }): Promise<void>;+ source?: string;- /**- * Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and- * update context cookies from the response. The method will automatically follow redirects.- *- * **Usage**- *- * JSON objects can be passed directly to the request:- *- * ```js- * await request.fetch('https://example.com/api/createBook', {- * method: 'post',- * data: {- * title: 'Book Title',- * author: 'John Doe',- * }- * });- * ```- *- * The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data`- * encoding, by specifiying the `multipart` parameter:- *- * ```js- * const form = new FormData();- * form.set('name', 'John');- * form.append('name', 'Doe');- * // Send two file fields with the same name.- * form.append('file', new File(['console.log(2024);'], 'f1.js', { type: 'text/javascript' }));- * form.append('file', new File(['hello'], 'f2.txt', { type: 'text/plain' }));- * await request.fetch('https://example.com/api/uploadForm', {- * multipart: form- * });- * ```- *- * @param urlOrRequest Target URL or Request to get all parameters from.- * @param options- */- fetch(urlOrRequest: string|Request, options?: {/**- * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string- * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`- * header will be set to `application/octet-stream` if not explicitly set.+ * V8-specific coverage format.*/- data?: string|Buffer|Serializable;+ functions: Array<{+ functionName: string;- /**- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status- * codes.- */- failOnStatusCode?: boolean;+ isBlockCoverage: boolean;- /**- * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent- * as this request body. If this parameter is specified `content-type` header will be set to- * `application/x-www-form-urlencoded` unless explicitly provided.- */- form?: { [key: string]: string|number|boolean; }|FormData;+ ranges: Array<{+ count: number;- /**- * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by- * it.- */- headers?: { [key: string]: string; };+ startOffset: number;- /**- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.- */- ignoreHTTPSErrors?: boolean;+ endOffset: number;+ }>;+ }>;+ }>>;+}- /**- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.- */- maxRedirects?: number;+/**+ * API for controlling the Playwright debugger. The debugger allows pausing script execution and inspecting the page.+ * Obtain the debugger instance via+ * [browserContext.debugger](https://playwright.dev/docs/api/class-browsercontext#browser-context-debugger).+ */+export interface Debugger {+ /**+ * Emitted when the debugger pauses or resumes.+ */+ on(event: 'pausedstatechanged', listener: () => any): this;- /**- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.- */- maxRetries?: number;+ /**+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ */+ once(event: 'pausedstatechanged', listener: () => any): this;- /**- * If set changes the fetch method (e.g. [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) or- * [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)). If not specified, GET method is used.- */- method?: string;+ /**+ * Emitted when the debugger pauses or resumes.+ */+ addListener(event: 'pausedstatechanged', listener: () => any): this;- /**- * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this- * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless- * explicitly provided. File values can be passed either as- * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file- * name, mime-type and its content.- */- multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{- /**- * File name- */- name: string;+ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ removeListener(event: 'pausedstatechanged', listener: () => any): this;- /**- * File type- */- mimeType: string;+ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ off(event: 'pausedstatechanged', listener: () => any): this;- /**- * File content- */- buffer: Buffer;- }; };+ /**+ * Emitted when the debugger pauses or resumes.+ */+ prependListener(event: 'pausedstatechanged', listener: () => any): this;- /**- * Query parameters to be sent with the URL.- */- params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;+ /**+ * Resumes script execution and pauses again before the next action. Throws if the debugger is not paused.+ */+ next(): Promise<void>;- /**- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.- */- timeout?: number;- }): Promise<APIResponse>;+ /**+ * Returns details about the currently paused call. Returns `null` if the debugger is not paused.+ */+ pausedDetails(): null|{+ location: {+ file: string;++ line?: number;++ column?: number;+ };++ title: string;+ };/**- * Sends HTTP(S) [GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET) request and returns its- * response. The method will populate request cookies from the context and update context cookies from the response.- * The method will automatically follow redirects.- *- * **Usage**- *- * Request parameters can be configured with `params` option, they will be serialized into the URL search parameters:- *- * ```js- * // Passing params as object- * await request.get('https://example.com/api/getText', {- * params: {- * 'isbn': '1234',- * 'page': 23,- * }- * });- *- * // Passing params as URLSearchParams- * const searchParams = new URLSearchParams();- * searchParams.set('isbn', '1234');- * searchParams.append('page', 23);- * searchParams.append('page', 24);- * await request.get('https://example.com/api/getText', { params: searchParams });+ * Configures the debugger to pause before the next action is executed.*- * // Passing params as string- * const queryString = 'isbn=1234&page=23&page=24';- * await request.get('https://example.com/api/getText', { params: queryString });- * ```+ * Throws if the debugger is already paused. Use+ * [debugger.next()](https://playwright.dev/docs/api/class-debugger#debugger-next) or+ * [debugger.runTo(location)](https://playwright.dev/docs/api/class-debugger#debugger-run-to) to step while paused.*- * @param url Target URL.- * @param options+ * Note that [page.pause()](https://playwright.dev/docs/api/class-page#page-pause) is equivalent to a "debugger"+ * statement — it pauses execution at the call site immediately. On the contrary,+ * [debugger.requestPause()](https://playwright.dev/docs/api/class-debugger#debugger-request-pause) is equivalent to+ * "pause on next statement" — it configures the debugger to pause before the next action is executed.*/- get(url: string, options?: {- /**- * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string- * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`- * header will be set to `application/octet-stream` if not explicitly set.- */- data?: string|Buffer|Serializable;+ requestPause(): Promise<void>;- /**- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status- * codes.- */- failOnStatusCode?: boolean;+ /**+ * Resumes script execution. Throws if the debugger is not paused.+ */+ resume(): Promise<void>;- /**- * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent- * as this request body. If this parameter is specified `content-type` header will be set to- * `application/x-www-form-urlencoded` unless explicitly provided.- */- form?: { [key: string]: string|number|boolean; }|FormData;+ /**+ * Resumes script execution and pauses when an action originates from the given source location. Throws if the+ * debugger is not paused.+ * @param location The source location to pause at.+ */+ runTo(location: {+ file: string;- /**- * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by- * it.- */- headers?: { [key: string]: string; };+ line?: number;- /**- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.- */- ignoreHTTPSErrors?: boolean;+ column?: number;+ }): Promise<void>;+}- /**- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.- */- maxRedirects?: number;+/**+ * [Dialog](https://playwright.dev/docs/api/class-dialog) objects are dispatched by page via the+ * [page.on('dialog')](https://playwright.dev/docs/api/class-page#page-event-dialog) event.+ *+ * An example of using `Dialog` class:+ *+ * ```js+ * const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.+ *+ * (async () => {+ * const browser = await chromium.launch();+ * const page = await browser.newPage();+ * page.on('dialog', async dialog => {+ * console.log(dialog.message());+ * await dialog.dismiss();+ * });+ * await page.evaluate(() => alert('1'));+ * await browser.close();+ * })();+ * ```+ *+ * **NOTE** Dialogs are dismissed automatically, unless there is a+ * [page.on('dialog')](https://playwright.dev/docs/api/class-page#page-event-dialog) listener. When listener is+ * present, it **must** either+ * [dialog.accept([promptText])](https://playwright.dev/docs/api/class-dialog#dialog-accept) or+ * [dialog.dismiss()](https://playwright.dev/docs/api/class-dialog#dialog-dismiss) the dialog - otherwise the page+ * will [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the+ * dialog, and actions like click will never finish.+ *+ */+export interface Dialog {+ /**+ * Returns when the dialog has been accepted.+ * @param promptText A text to enter in prompt. Does not cause any effects if the dialog's `type` is not prompt. Optional.+ */+ accept(promptText?: string): Promise<void>;- /**- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.- */- maxRetries?: number;+ /**+ * If dialog is prompt, returns default prompt value. Otherwise, returns empty string.+ */+ defaultValue(): string;- /**- * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this- * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless- * explicitly provided. File values can be passed either as- * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file- * name, mime-type and its content.- */- multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{- /**- * File name- */- name: string;+ /**+ * Returns when the dialog has been dismissed.+ */+ dismiss(): Promise<void>;- /**- * File type- */- mimeType: string;+ /**+ * A message displayed in the dialog.+ */+ message(): string;- /**- * File content- */- buffer: Buffer;- }; };+ /**+ * The page that initiated this dialog, if available.+ */+ page(): null|Page;- /**- * Query parameters to be sent with the URL.- */- params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;+ /**+ * Returns dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`.+ */+ type(): string;+}- /**- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.- */- timeout?: number;- }): Promise<APIResponse>;+/**+ * [Disposable](https://playwright.dev/docs/api/class-disposable) is returned from various methods to allow undoing+ * the corresponding action. For example,+ * [page.addInitScript(script[, arg])](https://playwright.dev/docs/api/class-page#page-add-init-script) returns a+ * [Disposable](https://playwright.dev/docs/api/class-disposable) that can be used to remove the init script.+ */+export interface Disposable {+ /**+ * Removes the associated resource. For example, removes the init script installed via+ * [page.addInitScript(script[, arg])](https://playwright.dev/docs/api/class-page#page-add-init-script) or+ * [browserContext.addInitScript(script[, arg])](https://playwright.dev/docs/api/class-browsercontext#browser-context-add-init-script).+ */+ dispose(): Promise<void>;++ [Symbol.asyncDispose](): Promise<void>;+}++/**+ * [Download](https://playwright.dev/docs/api/class-download) objects are dispatched by page via the+ * [page.on('download')](https://playwright.dev/docs/api/class-page#page-event-download) event.+ *+ * All the downloaded files belonging to the browser context are deleted when the browser context is closed.+ *+ * Download event is emitted once the download starts. Download path becomes available once download completes.+ *+ * ```js+ * // Start waiting for download before clicking. Note no await.+ * const downloadPromise = page.waitForEvent('download');+ * await page.getByText('Download file').click();+ * const download = await downloadPromise;+ *+ * // Wait for the download process to complete and save the downloaded file somewhere.+ * await download.saveAs('/path/to/save/at/' + download.suggestedFilename());+ * ```+ *+ */+export interface Download {+ /**+ * Cancels a download. Will not fail if the download is already finished or canceled. Upon successful cancellations,+ * `download.failure()` would resolve to `'canceled'`.+ */+ cancel(): Promise<void>;/**- * Sends HTTP(S) [HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD) request and returns its- * response. The method will populate request cookies from the context and update context cookies from the response.- * The method will automatically follow redirects.- * @param url Target URL.+ * Returns a readable stream for a successful download, or throws for a failed/canceled download.+ *+ * **NOTE** If you don't need a readable stream, it's usually simpler to read the file from disk after the download+ * completed. See [download.path()](https://playwright.dev/docs/api/class-download#download-path).+ *+ */+ createReadStream(): Promise<Readable>;++ /**+ * Deletes the downloaded file. Will wait for the download to finish if necessary.+ */+ delete(): Promise<void>;++ /**+ * Returns download error if any. Will wait for the download to finish if necessary.+ */+ failure(): Promise<null|string>;++ /**+ * Get the page that the download belongs to.+ */+ page(): Page;++ /**+ * Returns path to the downloaded file for a successful download, or throws for a failed/canceled download. The method+ * will wait for the download to finish if necessary. The method throws when connected remotely.+ *+ * Note that the download's file name is a random GUID, use+ * [download.suggestedFilename()](https://playwright.dev/docs/api/class-download#download-suggested-filename) to get+ * suggested file name.+ */+ path(): Promise<string>;++ /**+ * Copy the download to a user-specified path. It is safe to call this method while the download is still in progress.+ * Will wait for the download to finish if necessary.+ *+ * **Usage**+ *+ * ```js+ * await download.saveAs('/path/to/save/at/' + download.suggestedFilename());+ * ```+ *+ * @param path Path where the download should be copied.+ */+ saveAs(path: string): Promise<void>;++ /**+ * Returns suggested filename for this download. It is typically computed by the browser from the+ * [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) response+ * header or the `download` attribute. See the spec on [whatwg](https://html.spec.whatwg.org/#downloading-resources).+ * Different browsers can use different logic for computing it.+ */+ suggestedFilename(): string;++ /**+ * Returns downloaded url.+ */+ url(): string;+}++/**+ * [FileChooser](https://playwright.dev/docs/api/class-filechooser) objects are dispatched by the page in the+ * [page.on('filechooser')](https://playwright.dev/docs/api/class-page#page-event-file-chooser) event.+ *+ * ```js+ * // Start waiting for file chooser before clicking. Note no await.+ * const fileChooserPromise = page.waitForEvent('filechooser');+ * await page.getByText('Upload file').click();+ * const fileChooser = await fileChooserPromise;+ * await fileChooser.setFiles(path.join(__dirname, 'myfile.pdf'));+ * ```+ *+ */+export interface FileChooser {+ /**+ * Returns input element associated with this file chooser.+ */+ element(): ElementHandle;++ /**+ * Returns whether this file chooser accepts multiple files.+ */+ isMultiple(): boolean;++ /**+ * Returns page this file chooser belongs to.+ */+ page(): Page;++ /**+ * Sets the value of the file input this chooser is associated with. If some of the `filePaths` are relative paths,+ * then they are resolved relative to the current working directory. For empty array, clears the selected files.+ * @param files* @param options*/- head(url: string, options?: {+ setFiles(files: string|ReadonlyArray<string>|{/**- * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string- * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`- * header will be set to `application/octet-stream` if not explicitly set.+ * File name*/- data?: string|Buffer|Serializable;+ name: string;/**- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status- * codes.+ * File type*/- failOnStatusCode?: boolean;+ mimeType: string;/**- * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent- * as this request body. If this parameter is specified `content-type` header will be set to- * `application/x-www-form-urlencoded` unless explicitly provided.+ * File content*/- form?: { [key: string]: string|number|boolean; }|FormData;-+ buffer: Buffer;+ }|ReadonlyArray<{/**- * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by- * it.+ * File name*/- headers?: { [key: string]: string; };+ name: string;/**- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.+ * File type*/- ignoreHTTPSErrors?: boolean;+ mimeType: string;/**- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.+ * File content*/- maxRedirects?: number;-+ buffer: Buffer;+ }>, options?: {/**- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.+ * This option has no effect.+ * @deprecated This option has no effect.*/- maxRetries?: number;+ noWaitAfter?: boolean;/**- * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this- * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless- * explicitly provided. File values can be passed either as- * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file- * name, mime-type and its content.+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`+ * option in the config, or by using the+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.*/- multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{- /**- * File name- */- name: string;-- /**- * File type- */- mimeType: string;-- /**- * File content- */- buffer: Buffer;- }; };+ timeout?: number;+ }): Promise<void>;+}+/**+ * FrameLocator represents a view to the `iframe` on the page. It captures the logic sufficient to retrieve the+ * `iframe` and locate elements in that iframe. FrameLocator can be created with either+ * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame),+ * [page.frameLocator(selector)](https://playwright.dev/docs/api/class-page#page-frame-locator) or+ * [locator.frameLocator(selector)](https://playwright.dev/docs/api/class-locator#locator-frame-locator) method.+ *+ * ```js+ * const locator = page.locator('#my-frame').contentFrame().getByText('Submit');+ * await locator.click();+ * ```+ *+ * **Strictness**+ *+ * Frame locators are strict. This means that all operations on frame locators will throw if more than one element+ * matches a given selector.+ *+ * ```js+ * // Throws if there are several frames in DOM:+ * await page.locator('.result-frame').contentFrame().getByRole('button').click();+ *+ * // Works because we explicitly tell locator to pick the first frame:+ * await page.locator('.result-frame').contentFrame().first().getByRole('button').click();+ * ```+ *+ * **Converting Locator to FrameLocator**+ *+ * If you have a [Locator](https://playwright.dev/docs/api/class-locator) object pointing to an `iframe` it can be+ * converted to [FrameLocator](https://playwright.dev/docs/api/class-framelocator) using+ * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame).+ *+ * **Converting FrameLocator to Locator**+ *+ * If you have a [FrameLocator](https://playwright.dev/docs/api/class-framelocator) object it can be converted to+ * [Locator](https://playwright.dev/docs/api/class-locator) pointing to the same `iframe` using+ * [frameLocator.owner()](https://playwright.dev/docs/api/class-framelocator#frame-locator-owner).+ */+export interface FrameLocator {+ /**+ * Returns locator to the first matching frame.+ * @deprecated Use [locator.first()](https://playwright.dev/docs/api/class-locator#locator-first) followed by+ * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame) instead.+ */+ first(): FrameLocator;++ /**+ * When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements+ * in that iframe.+ * @param selector A selector to use when resolving DOM element.+ */+ frameLocator(selector: string): FrameLocator;++ /**+ * Allows locating elements by their alt text.+ *+ * **Usage**+ *+ * For example, this method will find the image by alt text "Playwright logo":+ *+ * ```html+ * <img alt='Playwright logo'>+ * ```+ *+ * ```js+ * await page.getByAltText('Playwright logo').click();+ * ```+ *+ * @param text Text to locate the element for.+ * @param options+ */+ getByAltText(text: string|RegExp, options?: {/**- * Query parameters to be sent with the URL.+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a+ * regular expression. Note that exact match still trims whitespace.*/- params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;+ exact?: boolean;+ }): Locator;+ /**+ * Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the+ * `aria-label` attribute.+ *+ * **Usage**+ *+ * For example, this method will find inputs by label "Username" and "Password" in the following DOM:+ *+ * ```html+ * <input aria-label="Username">+ * <label for="password-input">Password:</label>+ * <input id="password-input">+ * ```+ *+ * ```js+ * await page.getByLabel('Username').fill('john');+ * await page.getByLabel('Password').fill('secret');+ * ```+ *+ * @param text Text to locate the element for.+ * @param options+ */+ getByLabel(text: string|RegExp, options?: {/**- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a+ * regular expression. Note that exact match still trims whitespace.*/- timeout?: number;- }): Promise<APIResponse>;+ exact?: boolean;+ }): Locator;/**- * Sends HTTP(S) [PATCH](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) request and returns its- * response. The method will populate request cookies from the context and update context cookies from the response.- * The method will automatically follow redirects.- * @param url Target URL.+ * Allows locating input elements by the placeholder text.+ *+ * **Usage**+ *+ * For example, consider the following DOM structure.+ *+ * ```html+ * <input type="email" placeholder="[email protected]" />+ * ```+ *+ * You can fill the input after locating it by the placeholder text:+ *+ * ```js+ * await page+ * .getByPlaceholder('[email protected]')+ * .fill('[email protected]');+ * ```+ *+ * @param text Text to locate the element for.* @param options*/- patch(url: string, options?: {+ getByPlaceholder(text: string|RegExp, options?: {/**- * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string- * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`- * header will be set to `application/octet-stream` if not explicitly set.+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a+ * regular expression. Note that exact match still trims whitespace.*/- data?: string|Buffer|Serializable;+ exact?: boolean;+ }): Locator;+ /**+ * Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),+ * [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and+ * [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).+ *+ * **Usage**+ *+ * Consider the following DOM structure.+ *+ * ```html+ * <h3>Sign up</h3>+ * <label>+ * <input type="checkbox" /> Subscribe+ * </label>+ * <br/>+ * <button>Submit</button>+ * ```+ *+ * You can locate each element by its implicit role:+ *+ * ```js+ * await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible();+ *+ * await page.getByRole('checkbox', { name: 'Subscribe' }).check();+ *+ * await page.getByRole('button', { name: /submit/i }).click();+ * ```+ *+ * **Details**+ *+ * Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback+ * about the ARIA guidelines.+ *+ * Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)+ * that is recognized by the role selector. You can find all the+ * [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**+ * duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.+ * @param role Required aria role.+ * @param options+ */+ getByRole(role: "alert"|"alertdialog"|"application"|"article"|"banner"|"blockquote"|"button"|"caption"|"cell"|"checkbox"|"code"|"columnheader"|"combobox"|"complementary"|"contentinfo"|"definition"|"deletion"|"dialog"|"directory"|"document"|"emphasis"|"feed"|"figure"|"form"|"generic"|"grid"|"gridcell"|"group"|"heading"|"img"|"insertion"|"link"|"list"|"listbox"|"listitem"|"log"|"main"|"marquee"|"math"|"meter"|"menu"|"menubar"|"menuitem"|"menuitemcheckbox"|"menuitemradio"|"navigation"|"none"|"note"|"option"|"paragraph"|"presentation"|"progressbar"|"radio"|"radiogroup"|"region"|"row"|"rowgroup"|"rowheader"|"scrollbar"|"search"|"searchbox"|"separator"|"slider"|"spinbutton"|"status"|"strong"|"subscript"|"superscript"|"switch"|"tab"|"table"|"tablist"|"tabpanel"|"term"|"textbox"|"time"|"timer"|"toolbar"|"tooltip"|"tree"|"treegrid"|"treeitem", options?: {/**- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status- * codes.+ * An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.+ *+ * Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).*/- failOnStatusCode?: boolean;+ checked?: boolean;/**- * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent- * as this request body. If this parameter is specified `content-type` header will be set to- * `application/x-www-form-urlencoded` unless explicitly provided.+ * Option to match the [accessible description](https://w3c.github.io/accname/#dfn-accessible-description). By+ * default, matching is case-insensitive and searches for a substring, use+ * [`exact`](https://playwright.dev/docs/api/class-framelocator#frame-locator-get-by-role-option-exact) to control+ * this behavior.+ *+ * Learn more about [accessible description](https://w3c.github.io/accname/#dfn-accessible-description).*/- form?: { [key: string]: string|number|boolean; }|FormData;+ description?: string|RegExp;/**- * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by- * it.+ * An attribute that is usually set by `aria-disabled` or `disabled`.+ *+ * **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about+ * [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).+ **/- headers?: { [key: string]: string; };+ disabled?: boolean;/**- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.+ * Whether [`name`](https://playwright.dev/docs/api/class-framelocator#frame-locator-get-by-role-option-name) and+ * [`description`](https://playwright.dev/docs/api/class-framelocator#frame-locator-get-by-role-option-description)+ * are matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when the value is a regular+ * expression. Note that exact match still trims whitespace.*/- ignoreHTTPSErrors?: boolean;+ exact?: boolean;/**- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.+ * An attribute that is usually set by `aria-expanded`.+ *+ * Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).*/- maxRedirects?: number;+ expanded?: boolean;/**- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.+ * Option that controls whether hidden elements are matched. By default, only non-hidden elements, as+ * [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.+ *+ * Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).*/- maxRetries?: number;+ includeHidden?: boolean;/**- * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this- * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless- * explicitly provided. File values can be passed either as- * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file- * name, mime-type and its content.+ * A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values+ * for `<h1>-<h6>` elements.+ *+ * Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).*/- multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{- /**- * File name- */- name: string;-- /**- * File type- */- mimeType: string;-- /**- * File content- */- buffer: Buffer;- }; };+ level?: number;/**- * Query parameters to be sent with the URL.+ * Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is+ * case-insensitive and searches for a substring, use+ * [`exact`](https://playwright.dev/docs/api/class-framelocator#frame-locator-get-by-role-option-exact) to control+ * this behavior.+ *+ * Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).*/- params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;+ name?: string|RegExp;/**- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.+ * An attribute that is usually set by `aria-pressed`.+ *+ * Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).*/- timeout?: number;- }): Promise<APIResponse>;+ pressed?: boolean;++ /**+ * An attribute that is usually set by `aria-selected`.+ *+ * Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).+ */+ selected?: boolean;+ }): Locator;/**- * Sends HTTP(S) [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) request and returns its- * response. The method will populate request cookies from the context and update context cookies from the response.- * The method will automatically follow redirects.+ * Locate element by the test id.** **Usage***- * JSON objects can be passed directly to the request:+ * Consider the following DOM structure.+ *+ * ```html+ * <button data-testid="directions">Itinéraire</button>+ * ```+ *+ * You can locate the element by its test id:** ```js- * await request.post('https://example.com/api/createBook', {- * data: {- * title: 'Book Title',- * author: 'John Doe',- * }- * });+ * await page.getByTestId('directions').click();* ```*- * To send form data to the server use `form` option. Its value will be encoded into the request body with- * `application/x-www-form-urlencoded` encoding (see below how to use `multipart/form-data` form encoding to send- * files):+ * **Details**+ *+ * By default, the `data-testid` attribute is used as a test id. Use+ * [selectors.setTestIdAttribute(attributeName)](https://playwright.dev/docs/api/class-selectors#selectors-set-test-id-attribute)+ * to configure a different test id attribute if necessary.** ```js- * await request.post('https://example.com/api/findBook', {- * form: {- * title: 'Book Title',- * author: 'John Doe',- * }+ * // Set custom test id attribute from @playwright/test config:+ * import { defineConfig } from '@playwright/test';+ *+ * export default defineConfig({+ * use: {+ * testIdAttribute: 'data-pw'+ * },* });* ```*- * The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data`- * encoding. Use [FormData] to construct request body and pass it to the request as `multipart` parameter:+ * @param testId Id to locate the element by.+ */+ getByTestId(testId: string|RegExp): Locator;++ /**+ * Allows locating elements that contain given text.+ *+ * See also [locator.filter([options])](https://playwright.dev/docs/api/class-locator#locator-filter) that allows to+ * match by another criteria, like an accessible role, and then filter by the text content.+ *+ * **Usage**+ *+ * Consider the following DOM structure:+ *+ * ```html+ * <div>Hello <span>world</span></div>+ * <div>Hello</div>+ * ```+ *+ * You can locate by text substring, exact string, or a regular expression:** ```js- * const form = new FormData();- * form.set('name', 'John');- * form.append('name', 'Doe');- * // Send two file fields with the same name.- * form.append('file', new File(['console.log(2024);'], 'f1.js', { type: 'text/javascript' }));- * form.append('file', new File(['hello'], 'f2.txt', { type: 'text/plain' }));- * await request.post('https://example.com/api/uploadForm', {- * multipart: form- * });+ * // Matches <span>+ * page.getByText('world');+ *+ * // Matches first <div>+ * page.getByText('Hello world');+ *+ * // Matches second <div>+ * page.getByText('Hello', { exact: true });+ *+ * // Matches both <div>s+ * page.getByText(/Hello/);+ *+ * // Matches second <div>+ * page.getByText(/^hello$/i);* ```*- * @param url Target URL.+ * **Details**+ *+ * Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into+ * one, turns line breaks into spaces and ignores leading and trailing whitespace.+ *+ * Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For+ * example, locating by text `"Log in"` matches `<input type=button value="Log in">`.+ * @param text Text to locate the element for.* @param options*/- post(url: string, options?: {- /**- * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string- * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`- * header will be set to `application/octet-stream` if not explicitly set.- */- data?: string|Buffer|Serializable;-- /**- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status- * codes.- */- failOnStatusCode?: boolean;-+ getByText(text: string|RegExp, options?: {/**- * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent- * as this request body. If this parameter is specified `content-type` header will be set to- * `application/x-www-form-urlencoded` unless explicitly provided.+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a+ * regular expression. Note that exact match still trims whitespace.*/- form?: { [key: string]: string|number|boolean; }|FormData;+ exact?: boolean;+ }): Locator;+ /**+ * Allows locating elements by their title attribute.+ *+ * **Usage**+ *+ * Consider the following DOM structure.+ *+ * ```html+ * <span title='Issues count'>25 issues</span>+ * ```+ *+ * You can check the issues count after locating it by the title text:+ *+ * ```js+ * await expect(page.getByTitle('Issues count')).toHaveText('25 issues');+ * ```+ *+ * @param text Text to locate the element for.+ * @param options+ */+ getByTitle(text: string|RegExp, options?: {/**- * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by- * it.+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a+ * regular expression. Note that exact match still trims whitespace.*/- headers?: { [key: string]: string; };+ exact?: boolean;+ }): Locator;- /**- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.- */- ignoreHTTPSErrors?: boolean;+ /**+ * Returns locator to the last matching frame.+ * @deprecated Use [locator.last()](https://playwright.dev/docs/api/class-locator#locator-last) followed by+ * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame) instead.+ */+ last(): FrameLocator;+ /**+ * The method finds an element matching the specified selector in the locator's subtree. It also accepts filter+ * options, similar to [locator.filter([options])](https://playwright.dev/docs/api/class-locator#locator-filter)+ * method.+ *+ * [Learn more about locators](https://playwright.dev/docs/locators).+ * @param selectorOrLocator A selector or locator to use when resolving DOM element.+ * @param options+ */+ locator(selectorOrLocator: string|Locator, options?: {/**- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.+ * Narrows down the results of the method to those which contain elements matching this relative locator. For example,+ * `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.+ *+ * Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not+ * the document root. For example, you can find `content` that has `div` in+ * `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article+ * div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.+ *+ * Note that outer and inner locators must belong to the same frame. Inner locator must not contain+ * [FrameLocator](https://playwright.dev/docs/api/class-framelocator)s.*/- maxRedirects?: number;+ has?: Locator;/**- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.+ * Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the+ * outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.+ *+ * Note that outer and inner locators must belong to the same frame. Inner locator must not contain+ * [FrameLocator](https://playwright.dev/docs/api/class-framelocator)s.*/- maxRetries?: number;+ hasNot?: Locator;/**- * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this- * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless- * explicitly provided. File values can be passed either as- * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file- * name, mime-type and its content.+ * Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.+ * When passed a [string], matching is case-insensitive and searches for a substring.*/- multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{- /**- * File name- */- name: string;-- /**- * File type- */- mimeType: string;-- /**- * File content- */- buffer: Buffer;- }; };+ hasNotText?: string|RegExp;/**- * Query parameters to be sent with the URL.+ * Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When+ * passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches+ * `<article><div>Playwright</div></article>`.*/- params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;+ hasText?: string|RegExp;+ }): Locator;- /**- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.- */- timeout?: number;- }): Promise<APIResponse>;+ /**+ * Returns locator to the n-th matching frame. It's zero based, `nth(0)` selects the first frame.+ * @deprecated Use [locator.nth(index)](https://playwright.dev/docs/api/class-locator#locator-nth) followed by+ * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame) instead.+ * @param index+ */+ nth(index: number): FrameLocator;/**- * Sends HTTP(S) [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) request and returns its- * response. The method will populate request cookies from the context and update context cookies from the response.- * The method will automatically follow redirects.- * @param url Target URL.- * @param options- */- put(url: string, options?: {- /**- * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string- * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`- * header will be set to `application/octet-stream` if not explicitly set.- */- data?: string|Buffer|Serializable;-- /**- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status- * codes.- */- failOnStatusCode?: boolean;-- /**- * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent- * as this request body. If this parameter is specified `content-type` header will be set to- * `application/x-www-form-urlencoded` unless explicitly provided.- */- form?: { [key: string]: string|number|boolean; }|FormData;-- /**- * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by- * it.- */- headers?: { [key: string]: string; };-- /**- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.- */- ignoreHTTPSErrors?: boolean;-- /**- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.- */- maxRedirects?: number;-- /**- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.- */- maxRetries?: number;-- /**- * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this- * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless- * explicitly provided. File values can be passed either as- * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file- * name, mime-type and its content.- */- multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{- /**- * File name- */- name: string;-- /**- * File type- */- mimeType: string;-- /**- * File content- */- buffer: Buffer;- }; };-- /**- * Query parameters to be sent with the URL.- */- params?: { [key: string]: string|number|boolean; }|URLSearchParams|string;-- /**- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.- */- timeout?: number;- }): Promise<APIResponse>;-- /**- * Returns storage state for this request context, contains current cookies and local storage snapshot if it was- * passed to the constructor.- * @param options+ * Returns a [Locator](https://playwright.dev/docs/api/class-locator) object pointing to the same `iframe` as this+ * frame locator.+ *+ * Useful when you have a [FrameLocator](https://playwright.dev/docs/api/class-framelocator) object obtained+ * somewhere, and later on would like to interact with the `iframe` element.+ *+ * For a reverse operation, use+ * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame).+ *+ * **Usage**+ *+ * ```js+ * const frameLocator = page.locator('iframe[name="embedded"]').contentFrame();+ * // ...+ * const locator = frameLocator.owner();+ * await expect(locator).toBeVisible();+ * ```+ **/- storageState(options?: {- /**- * Set to `true` to include IndexedDB in the storage state snapshot.- */- indexedDB?: boolean;-- /**- * The file path to save the storage state to. If- * [`path`](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-storage-state-option-path) is- * a relative path, then it is resolved relative to current working directory. If no path is provided, storage state- * is still returned, but won't be saved to the disk.- */- path?: string;- }): Promise<{- cookies: Array<{- name: string;-- value: string;-- domain: string;-- path: string;-- /**- * Unix time in seconds.- */- expires: number;-- httpOnly: boolean;-- secure: boolean;-- sameSite: "Strict"|"Lax"|"None";- }>;-- origins: Array<{- origin: string;-- localStorage: Array<{- name: string;-- value: string;- }>;- }>;- }>;-- tracing: Tracing;-- [Symbol.asyncDispose](): Promise<void>;+ owner(): Locator;}/**- * [APIResponse](https://playwright.dev/docs/api/class-apiresponse) class represents responses returned by- * [apiRequestContext.get(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-get)- * and similar methods.+ * Keyboard provides an api for managing a virtual keyboard. The high level api is+ * [keyboard.type(text[, options])](https://playwright.dev/docs/api/class-keyboard#keyboard-type), which takes raw+ * characters and generates proper `keydown`, `keypress`/`input`, and `keyup` events on your page.+ *+ * For finer control, you can use [keyboard.down(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-down),+ * [keyboard.up(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-up), and+ * [keyboard.insertText(text)](https://playwright.dev/docs/api/class-keyboard#keyboard-insert-text) to manually fire+ * events as if they were generated from a real keyboard.+ *+ * An example of holding down `Shift` in order to select and delete some text:+ *+ * ```js+ * await page.keyboard.type('Hello World!');+ * await page.keyboard.press('ArrowLeft');+ *+ * await page.keyboard.down('Shift');+ * for (let i = 0; i < ' World'.length; i++)+ * await page.keyboard.press('ArrowLeft');+ * await page.keyboard.up('Shift');+ *+ * await page.keyboard.press('Backspace');+ * // Result text will end up saying 'Hello!'+ * ```+ *+ * An example of pressing uppercase `A`+ *+ * ```js+ * await page.keyboard.press('Shift+KeyA');+ * // or+ * await page.keyboard.press('Shift+A');+ * ```+ *+ * An example to trigger select-all with the keyboard+ *+ * ```js+ * await page.keyboard.press('ControlOrMeta+A');+ * ```+ **/-export interface APIResponse {+export interface Keyboard {/**- * Returns the buffer with response body.+ * Dispatches a `keydown` event.+ *+ * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-down-option-key) can specify the intended+ * [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character+ * to generate the text for. A superset of the+ * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-down-option-key) values can be found+ * [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:+ *+ * `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,+ * `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,+ * etc.+ *+ * Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,+ * `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.+ *+ * Holding down `Shift` will type the text that corresponds to the+ * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-down-option-key) in the upper case.+ *+ * If [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-down-option-key) is a single character, it is+ * case-sensitive, so the values `a` and `A` will generate different respective texts.+ *+ * If [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-down-option-key) is a modifier key, `Shift`,+ * `Meta`, `Control`, or `Alt`, subsequent key presses will be sent with that modifier active. To release the modifier+ * key, use [keyboard.up(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-up).+ *+ * After the key is pressed once, subsequent calls to+ * [keyboard.down(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-down) will have+ * [repeat](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat) set to true. To release the key,+ * use [keyboard.up(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-up).+ *+ * **NOTE** Modifier keys DO influence `keyboard.down`. Holding down `Shift` will type the text in upper case.+ *+ * @param key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.*/- body(): Promise<Buffer>;+ down(key: string): Promise<void>;/**- * Disposes the body of this response. If not called then the body will stay in memory until the context closes.+ * Dispatches only `input` event, does not emit the `keydown`, `keyup` or `keypress` events.+ *+ * **Usage**+ *+ * ```js+ * page.keyboard.insertText('嗨');+ * ```+ *+ * **NOTE** Modifier keys DO NOT effect `keyboard.insertText`. Holding down `Shift` will not type the text in upper+ * case.+ *+ * @param text Sets input to the specified text value.*/- dispose(): Promise<void>;+ insertText(text: string): Promise<void>;/**- * An object with all the response HTTP headers associated with this response.+ * **NOTE** In most cases, you should use+ * [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press) instead.+ *+ * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-press-option-key) can specify the intended+ * [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character+ * to generate the text for. A superset of the+ * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-press-option-key) values can be found+ * [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:+ *+ * `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,+ * `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,+ * etc.+ *+ * Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,+ * `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.+ *+ * Holding down `Shift` will type the text that corresponds to the+ * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-press-option-key) in the upper case.+ *+ * If [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-press-option-key) is a single character, it is+ * case-sensitive, so the values `a` and `A` will generate different respective texts.+ *+ * Shortcuts such as `key: "Control+o"`, `key: "Control++` or `key: "Control+Shift+T"` are supported as well. When+ * specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.+ *+ * **Usage**+ *+ * ```js+ * const page = await browser.newPage();+ * await page.goto('https://keycode.info');+ * await page.keyboard.press('A');+ * await page.screenshot({ path: 'A.png' });+ * await page.keyboard.press('ArrowLeft');+ * await page.screenshot({ path: 'ArrowLeft.png' });+ * await page.keyboard.press('Shift+O');+ * await page.screenshot({ path: 'O.png' });+ * await browser.close();+ * ```+ *+ * Shortcut for [keyboard.down(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-down) and+ * [keyboard.up(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-up).+ * @param key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.+ * @param options*/- headers(): { [key: string]: string; };+ press(key: string, options?: {+ /**+ * Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.+ */+ delay?: number;+ }): Promise<void>;/**- * An array with all the response HTTP headers associated with this response. Header names are not lower-cased.- * Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple times.+ * **NOTE** In most cases, you should use+ * [locator.fill(value[, options])](https://playwright.dev/docs/api/class-locator#locator-fill) instead. You only need+ * to press keys one by one if there is special keyboard handling on the page - in this case use+ * [locator.pressSequentially(text[, options])](https://playwright.dev/docs/api/class-locator#locator-press-sequentially).+ *+ * Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text.+ *+ * To press a special key, like `Control` or `ArrowDown`, use+ * [keyboard.press(key[, options])](https://playwright.dev/docs/api/class-keyboard#keyboard-press).+ *+ * **Usage**+ *+ * ```js+ * await page.keyboard.type('Hello'); // Types instantly+ * await page.keyboard.type('World', { delay: 100 }); // Types slower, like a user+ * ```+ *+ * **NOTE** Modifier keys DO NOT effect `keyboard.type`. Holding down `Shift` will not type the text in upper case.+ *+ * **NOTE** For characters that are not on a US keyboard, only an `input` event will be sent.+ *+ * @param text A text to type into a focused element.+ * @param options*/- headersArray(): Array<{+ type(text: string, options?: {/**- * Name of the header.+ * Time to wait between key presses in milliseconds. Defaults to 0.*/- name: string;+ delay?: number;+ }): Promise<void>;- /**- * Value of the header.- */- value: string;- }>;+ /**+ * Dispatches a `keyup` event.+ * @param key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.+ */+ up(key: string): Promise<void>;+}+/**+ * Playwright generates a lot of logs and they are accessible via the pluggable logger sink.+ *+ * ```js+ * const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.+ *+ * (async () => {+ * const browser = await chromium.launch({+ * logger: {+ * isEnabled: (name, severity) => name === 'api',+ * log: (name, severity, message, args) => console.log(`${name} ${message}`)+ * }+ * });+ * // ...+ * })();+ * ```+ *+ */+export interface Logger {/**- * Returns the JSON representation of response body.- *- * This method will throw if the response body is not parsable via `JSON.parse`.+ * Determines whether sink is interested in the logger with the given name and severity.+ * @param name logger name+ * @param severity*/- json(): Promise<Serializable>;+ isEnabled(name: string, severity: "verbose"|"info"|"warning"|"error"): boolean;/**- * Contains a boolean stating whether the response was successful (status in the range 200-299) or not.+ * @param name logger name+ * @param severity+ * @param message log message format+ * @param args message arguments+ * @param hints optional formatting hints*/- ok(): boolean;+ log(name: string, severity: "verbose"|"info"|"warning"|"error", message: string|Error, args: ReadonlyArray<Object>, hints: {+ /**+ * Optional preferred logger color.+ */+ color?: string;+ }): void;+}+/**+ * The Mouse class operates in main-frame CSS pixels relative to the top-left corner of the viewport.+ *+ * **NOTE** If you want to debug where the mouse moved, you can use the [Trace viewer](https://playwright.dev/docs/trace-viewer-intro) or+ * [Playwright Inspector](https://playwright.dev/docs/running-tests). A red dot showing the location of the mouse will be shown for every+ * mouse action.+ *+ * Every `page` object has its own Mouse, accessible with+ * [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse).+ *+ * ```js+ * // Using ‘page.mouse’ to trace a 100x100 square.+ * await page.mouse.move(0, 0);+ * await page.mouse.down();+ * await page.mouse.move(0, 100);+ * await page.mouse.move(100, 100);+ * await page.mouse.move(100, 0);+ * await page.mouse.move(0, 0);+ * await page.mouse.up();+ * ```+ *+ */+export interface Mouse {/**- * Contains the status code of the response (e.g., 200 for a success).+ * Shortcut for [mouse.move(x, y[, options])](https://playwright.dev/docs/api/class-mouse#mouse-move),+ * [mouse.down([options])](https://playwright.dev/docs/api/class-mouse#mouse-down),+ * [mouse.up([options])](https://playwright.dev/docs/api/class-mouse#mouse-up).+ * @param x X coordinate relative to the main frame's viewport in CSS pixels.+ * @param y Y coordinate relative to the main frame's viewport in CSS pixels.+ * @param options*/- status(): number;+ click(x: number, y: number, options?: {+ /**+ * Defaults to `left`.+ */+ button?: "left"|"right"|"middle";- /**- * Contains the status text of the response (e.g. usually an "OK" for a success).- */- statusText(): string;+ /**+ * defaults to 1. See [UIEvent.detail].+ */+ clickCount?: number;- /**- * Returns the text representation of response body.- */- text(): Promise<string>;+ /**+ * Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.+ */+ delay?: number;+ }): Promise<void>;/**- * Contains the URL of the response.+ * Shortcut for [mouse.move(x, y[, options])](https://playwright.dev/docs/api/class-mouse#mouse-move),+ * [mouse.down([options])](https://playwright.dev/docs/api/class-mouse#mouse-down),+ * [mouse.up([options])](https://playwright.dev/docs/api/class-mouse#mouse-up),+ * [mouse.down([options])](https://playwright.dev/docs/api/class-mouse#mouse-down) and+ * [mouse.up([options])](https://playwright.dev/docs/api/class-mouse#mouse-up).+ * @param x X coordinate relative to the main frame's viewport in CSS pixels.+ * @param y Y coordinate relative to the main frame's viewport in CSS pixels.+ * @param options*/- url(): string;+ dblclick(x: number, y: number, options?: {+ /**+ * Defaults to `left`.+ */+ button?: "left"|"right"|"middle";- [Symbol.asyncDispose](): Promise<void>;-}+ /**+ * Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.+ */+ delay?: number;+ }): Promise<void>;-export interface BrowserServer {/**- * Emitted when the browser server closes.+ * Dispatches a `mousedown` event.+ * @param options*/- on(event: 'close', listener: () => any): this;+ down(options?: {+ /**+ * Defaults to `left`.+ */+ button?: "left"|"right"|"middle";- /**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.- */- once(event: 'close', listener: () => any): this;+ /**+ * defaults to 1. See [UIEvent.detail].+ */+ clickCount?: number;+ }): Promise<void>;/**- * Emitted when the browser server closes.+ * Dispatches a `mousemove` event.+ * @param x X coordinate relative to the main frame's viewport in CSS pixels.+ * @param y Y coordinate relative to the main frame's viewport in CSS pixels.+ * @param options*/- addListener(event: 'close', listener: () => any): this;+ move(x: number, y: number, options?: {+ /**+ * Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor+ * position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.+ */+ steps?: number;+ }): Promise<void>;/**- * Removes an event listener added by `on` or `addListener`.+ * Dispatches a `mouseup` event.+ * @param options*/- removeListener(event: 'close', listener: () => any): this;+ up(options?: {+ /**+ * Defaults to `left`.+ */+ button?: "left"|"right"|"middle";- /**- * Removes an event listener added by `on` or `addListener`.- */- off(event: 'close', listener: () => any): this;+ /**+ * defaults to 1. See [UIEvent.detail].+ */+ clickCount?: number;+ }): Promise<void>;/**- * Emitted when the browser server closes.+ * Dispatches a `wheel` event. This method is usually used to manually scroll the page. See+ * [scrolling](https://playwright.dev/docs/input#scrolling) for alternative ways to scroll.+ *+ * **NOTE** Wheel events may cause scrolling if they are not handled, and this method does not wait for the scrolling+ * to finish before returning.+ *+ * @param deltaX Pixels to scroll horizontally.+ * @param deltaY Pixels to scroll vertically.*/- prependListener(event: 'close', listener: () => any): this;+ wheel(deltaX: number, deltaY: number): Promise<void>;+}- /**- * Closes the browser gracefully and makes sure the process is terminated.- */- close(): Promise<void>;+/**+ * This object can be used to launch or connect to Chromium, returning instances of+ * [Browser](https://playwright.dev/docs/api/class-browser).+ */+export const chromium: BrowserType;- /**- * Kills the browser process and waits for the process to exit.- */- kill(): Promise<void>;+/**+ * This object can be used to launch or connect to Firefox, returning instances of+ * [Browser](https://playwright.dev/docs/api/class-browser).+ */+export const firefox: BrowserType;- /**- * Spawned browser application process.- */- process(): ChildProcess;+/**+ * Exposes API that can be used for the Web API testing.+ */+export const request: APIRequest;- /**- * Browser websocket url.- *- * Browser websocket endpoint which can be used as an argument to- * [browserType.connect(endpoint[, options])](https://playwright.dev/docs/api/class-browsertype#browser-type-connect)- * to establish connection to the browser.- */- wsEndpoint(): string;+/**+ * Selectors can be used to install custom selector engines. See [extensibility](https://playwright.dev/docs/extensibility) for more+ * information.+ */+export const selectors: Selectors;- [Symbol.asyncDispose](): Promise<void>;-}+/**+ * This object can be used to launch or connect to WebKit, returning instances of+ * [Browser](https://playwright.dev/docs/api/class-browser).+ */+export const webkit: BrowserType;/**- * Accurately simulating time-dependent behavior is essential for verifying the correctness of applications. Learn- * more about [clock emulation](https://playwright.dev/docs/clock).+ * Whenever the page sends a request for a network resource the following sequence of events are emitted by+ * [Page](https://playwright.dev/docs/api/class-page):+ * - [page.on('request')](https://playwright.dev/docs/api/class-page#page-event-request) emitted when the request is+ * issued by the page.+ * - [page.on('response')](https://playwright.dev/docs/api/class-page#page-event-response) emitted when/if the+ * response status and headers are received for the request.+ * - [page.on('requestfinished')](https://playwright.dev/docs/api/class-page#page-event-request-finished) emitted+ * when the response body is downloaded and the request is complete.*- * Note that clock is installed for the entire [BrowserContext](https://playwright.dev/docs/api/class-browsercontext),- * so the time in all the pages and iframes is controlled by the same clock.+ * If request fails at some point, then instead of `'requestfinished'` event (and possibly instead of 'response'+ * event), the [page.on('requestfailed')](https://playwright.dev/docs/api/class-page#page-event-request-failed) event+ * is emitted.+ *+ * **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request+ * will complete with `'requestfinished'` event.+ *+ * If request gets a 'redirect' response, the request is successfully finished with the `requestfinished` event, and a+ * new request is issued to a redirected url.*/-export interface Clock {- /**- * Advance the clock by jumping forward in time. Only fires due timers at most once. This is equivalent to user- * closing the laptop lid for a while and reopening it later, after given time.- *- * **Usage**- *- * ```js- * await page.clock.fastForward(1000);- * await page.clock.fastForward('30:00');- * ```- *- * @param ticks Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are- * "08" for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.- */- fastForward(ticks: number|string): Promise<void>;-- /**- * Install fake implementations for the following time-related functions:- * - `Date`- * - `setTimeout`- * - `clearTimeout`- * - `setInterval`- * - `clearInterval`- * - `requestAnimationFrame`- * - `cancelAnimationFrame`- * - `requestIdleCallback`- * - `cancelIdleCallback`- * - `performance`- *- * Fake timers are used to manually control the flow of time in tests. They allow you to advance time, fire timers,- * and control the behavior of time-dependent functions. See- * [clock.runFor(ticks)](https://playwright.dev/docs/api/class-clock#clock-run-for) and- * [clock.fastForward(ticks)](https://playwright.dev/docs/api/class-clock#clock-fast-forward) for more information.- * @param options- */- install(options?: {- /**- * Time to initialize with, current system time by default.- */- time?: number|string|Date;- }): Promise<void>;-- /**- * Advance the clock by jumping forward in time and pause the time. Once this method is called, no timers are fired- * unless [clock.runFor(ticks)](https://playwright.dev/docs/api/class-clock#clock-run-for),- * [clock.fastForward(ticks)](https://playwright.dev/docs/api/class-clock#clock-fast-forward),- * [clock.pauseAt(time)](https://playwright.dev/docs/api/class-clock#clock-pause-at) or- * [clock.resume()](https://playwright.dev/docs/api/class-clock#clock-resume) is called.- *- * Only fires due timers at most once. This is equivalent to user closing the laptop lid for a while and reopening it- * at the specified time and pausing.- *- * **Usage**- *- * ```js- * await page.clock.pauseAt(new Date('2020-02-02'));- * await page.clock.pauseAt('2020-02-02');- * ```- *- * For best results, install the clock before navigating the page and set it to a time slightly before the intended- * test time. This ensures that all timers run normally during page loading, preventing the page from getting stuck.- * Once the page has fully loaded, you can safely use- * [clock.pauseAt(time)](https://playwright.dev/docs/api/class-clock#clock-pause-at) to pause the clock.- *- * ```js- * // Initialize clock with some time before the test time and let the page load- * // naturally. `Date.now` will progress as the timers fire.- * await page.clock.install({ time: new Date('2024-12-10T08:00:00') });- * await page.goto('http://localhost:3333');- * await page.clock.pauseAt(new Date('2024-12-10T10:00:00'));- * ```- *- * @param time Time to pause at.+export interface Request {+ /**+ * An object with all the request HTTP headers associated with this request. The header names are lower-cased.*/- pauseAt(time: number|string|Date): Promise<void>;+ allHeaders(): Promise<{ [key: string]: string; }>;/**- * Resumes timers. Once this method is called, time resumes flowing, timers are fired as usual.+ * Returns the [Response](https://playwright.dev/docs/api/class-response) object if the response has already been+ * received, `null` otherwise.+ *+ * Unlike [request.response()](https://playwright.dev/docs/api/class-request#request-response), this method does not+ * wait for the response to arrive. It returns immediately with the response object if the response has been received,+ * or `null` if the response has not been received yet.*/- resume(): Promise<void>;+ existingResponse(): null|Response;/**- * Advance the clock, firing all the time-related callbacks.+ * The method returns `null` unless this request has failed, as reported by `requestfailed` event.** **Usage***+ * Example of logging of all the failed requests:+ ** ```js- * await page.clock.runFor(1000);- * await page.clock.runFor('30:00');+ * page.on('requestfailed', request => {+ * console.log(request.url() + ' ' + request.failure().errorText);+ * });* ```*- * @param ticks Time may be the number of milliseconds to advance the clock by or a human-readable string. Valid string formats are- * "08" for eight seconds, "01:00" for one minute and "02:34:10" for two hours, 34 minutes and ten seconds.*/- runFor(ticks: number|string): Promise<void>;+ failure(): null|{+ /**+ * Human-readable error message, e.g. `'net::ERR_FAILED'`.+ */+ errorText: string;+ };/**- * Makes `Date.now` and `new Date()` return fixed fake time at all times, keeps all the timers running.- *- * Use this method for simple scenarios where you only need to test with a predefined time. For more advanced- * scenarios, use [clock.install([options])](https://playwright.dev/docs/api/class-clock#clock-install) instead. Read- * docs on [clock emulation](https://playwright.dev/docs/clock) to learn more.+ * Returns the [Frame](https://playwright.dev/docs/api/class-frame) that initiated this request.** **Usage**** ```js- * await page.clock.setFixedTime(Date.now());- * await page.clock.setFixedTime(new Date('2020-02-02'));- * await page.clock.setFixedTime('2020-02-02');+ * const frameUrl = request.frame().url();* ```*- * @param time Time to be set in milliseconds.- */- setFixedTime(time: number|string|Date): Promise<void>;-- /**- * Sets system time, but does not trigger any timers. Use this to test how the web page reacts to a time shift, for- * example switching from summer to winter time, or changing time zones.+ * **Details***- * **Usage**+ * Note that in some cases the frame is not available, and this method will throw.+ * - When request originates in the Service Worker. You can use `request.serviceWorker()` to check that.+ * - When navigation request is issued before the corresponding frame is created. You can use+ * [request.isNavigationRequest()](https://playwright.dev/docs/api/class-request#request-is-navigation-request) to+ * check that.+ *+ * Here is an example that handles all the cases:** ```js- * await page.clock.setSystemTime(Date.now());- * await page.clock.setSystemTime(new Date('2020-02-02'));- * await page.clock.setSystemTime('2020-02-02');+ * if (request.serviceWorker())+ * console.log(`request ${request.url()} from a service worker`);+ * else if (request.isNavigationRequest())+ * console.log(`request ${request.url()} is a navigation request`);+ * else+ * console.log(`request ${request.url()} from a frame ${request.frame().url()}`);* ```*- * @param time Time to be set in milliseconds.*/- setSystemTime(time: number|string|Date): Promise<void>;-}+ frame(): Frame;-/**- * [ConsoleMessage](https://playwright.dev/docs/api/class-consolemessage) objects are dispatched by page via the- * [page.on('console')](https://playwright.dev/docs/api/class-page#page-event-console) event. For each console message- * logged in the page there will be corresponding event in the Playwright context.- *- * ```js- * // Listen for all console logs- * page.on('console', msg => console.log(msg.text()));- *- * // Listen for all console events and handle errors- * page.on('console', msg => {- * if (msg.type() === 'error')- * console.log(`Error text: "${msg.text()}"`);- * });- *- * // Get the next console log- * const msgPromise = page.waitForEvent('console');- * await page.evaluate(() => {- * console.log('hello', 42, { foo: 'bar' }); // Issue console.log inside the page- * });- * const msg = await msgPromise;- *- * // Deconstruct console log arguments- * await msg.args()[0].jsonValue(); // hello- * await msg.args()[1].jsonValue(); // 42- * ```- *- */-export interface ConsoleMessage {/**- * List of arguments passed to a `console` function call. See also- * [page.on('console')](https://playwright.dev/docs/api/class-page#page-event-console).+ * An object with the request HTTP headers. The header names are lower-cased. Note that this method does not return+ * security-related headers, including cookie-related ones. You can use+ * [request.allHeaders()](https://playwright.dev/docs/api/class-request#request-all-headers) for complete list of+ * headers that include `cookie` information.*/- args(): Array<JSHandle>;+ headers(): { [key: string]: string; };- location(): {+ /**+ * An array with all the request HTTP headers associated with this request. Unlike+ * [request.allHeaders()](https://playwright.dev/docs/api/class-request#request-all-headers), header names are NOT+ * lower-cased. Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple times.+ */+ headersArray(): Promise<Array<{/**- * URL of the resource.+ * Name of the header.*/- url: string;+ name: string;/**- * 0-based line number in the resource.+ * Value of the header.*/- line: number;+ value: string;+ }>>;- /**- * 0-based column number in the resource.- */- column: number;+ /**+ * Returns the value of the header matching the name. The name is case-insensitive.+ * @param name Name of the header.+ */+ headerValue(name: string): Promise<null|string>;- /**- * 0-based line number in the resource. Deprecated, use `line` instead.- */- lineNumber: number;+ /**+ * Whether this request is driving frame's navigation.+ *+ * Some navigation requests are issued before the corresponding frame is created, and therefore do not have+ * [request.frame()](https://playwright.dev/docs/api/class-request#request-frame) available.+ */+ isNavigationRequest(): boolean;- /**- * 0-based column number in the resource. Deprecated, use `column` instead.- */- columnNumber: number;- };+ /**+ * Request's method (GET, POST, etc.)+ */+ method(): string;/**- * The page that produced this console message, if any.+ * Request's post body, if any.*/- page(): null|Page;+ postData(): null|string;/**- * The text of the console message.+ * Request's post body in a binary form, if any.*/- text(): string;+ postDataBuffer(): null|Buffer;/**- * The timestamp of the console message in milliseconds since the Unix epoch.+ * Returns parsed request's body for `form-urlencoded` and JSON as a fallback if any.+ *+ * When the response is `application/x-www-form-urlencoded` then a key/value object of the values will be returned.+ * Otherwise it will be parsed as JSON.*/- timestamp(): number;+ postDataJSON(): null|Serializable;- type(): "log"|"debug"|"info"|"error"|"warning"|"dir"|"dirxml"|"table"|"trace"|"clear"|"startGroup"|"startGroupCollapsed"|"endGroup"|"assert"|"profile"|"profileEnd"|"count"|"time"|"timeEnd";+ /**+ * Request that was redirected by the server to this one, if any.+ *+ * When the server responds with a redirect, Playwright creates a new+ * [Request](https://playwright.dev/docs/api/class-request) object. The two requests are connected by+ * `redirectedFrom()` and `redirectedTo()` methods. When multiple server redirects has happened, it is possible to+ * construct the whole redirect chain by repeatedly calling `redirectedFrom()`.+ *+ * **Usage**+ *+ * For example, if the website `http://example.com` redirects to `https://example.com`:+ *+ * ```js+ * const response = await page.goto('http://example.com');+ * console.log(response.request().redirectedFrom().url()); // 'http://example.com'+ * ```+ *+ * If the website `https://google.com` has no redirects:+ *+ * ```js+ * const response = await page.goto('https://google.com');+ * console.log(response.request().redirectedFrom()); // null+ * ```+ *+ */+ redirectedFrom(): null|Request;/**- * The web worker or service worker that produced this console message, if any. Note that console messages from web- * workers also have non-null- * [consoleMessage.page()](https://playwright.dev/docs/api/class-consolemessage#console-message-page).+ * New request issued by the browser if the server responded with redirect.+ *+ * **Usage**+ *+ * This method is the opposite of+ * [request.redirectedFrom()](https://playwright.dev/docs/api/class-request#request-redirected-from):+ *+ * ```js+ * console.log(request.redirectedFrom().redirectedTo() === request); // true+ * ```+ **/- worker(): null|Worker;-}+ redirectedTo(): null|Request;-/**- * Coverage gathers information about parts of JavaScript and CSS that were used by the page.- *- * An example of using JavaScript coverage to produce Istanbul report for page load:- *- * **NOTE** Coverage APIs are only supported on Chromium-based browsers.- *- * ```js- * const { chromium } = require('playwright');- * const v8toIstanbul = require('v8-to-istanbul');- *- * (async () => {- * const browser = await chromium.launch();- * const page = await browser.newPage();- * await page.coverage.startJSCoverage();- * await page.goto('https://chromium.org');- * const coverage = await page.coverage.stopJSCoverage();- * for (const entry of coverage) {- * const converter = v8toIstanbul('', 0, { source: entry.source });- * await converter.load();- * converter.applyCoverage(entry.functions);- * console.log(JSON.stringify(converter.toIstanbul()));- * }- * await browser.close();- * })();- * ```- *- */-export interface Coverage {/**- * Returns coverage is started- * @param options+ * Contains the request's resource type as it was perceived by the rendering engine. ResourceType will be one of the+ * following: `document`, `stylesheet`, `image`, `media`, `font`, `script`, `texttrack`, `xhr`, `fetch`,+ * `eventsource`, `websocket`, `manifest`, `other`.*/- startCSSCoverage(options?: {- /**- * Whether to reset coverage on every navigation. Defaults to `true`.- */- resetOnNavigation?: boolean;- }): Promise<void>;+ resourceType(): string;++ /**+ * Returns the matching [Response](https://playwright.dev/docs/api/class-response) object, or `null` if the response+ * was not received due to error.+ */+ response(): Promise<null|Response>;/**- * Returns coverage is started+ * The Service [Worker](https://playwright.dev/docs/api/class-worker) that is performing the request.*- * **NOTE** Anonymous scripts are ones that don't have an associated url. These are scripts that are dynamically- * created on the page using `eval` or `new Function`. If- * [`reportAnonymousScripts`](https://playwright.dev/docs/api/class-coverage#coverage-start-js-coverage-option-report-anonymous-scripts)- * is set to `true`, anonymous scripts will have `__playwright_evaluation_script__` as their URL.+ * **Details***- * @param options+ * This method is Chromium only. It's safe to call when using other browsers, but it will always be `null`.+ *+ * Requests originated in a Service Worker do not have a+ * [request.frame()](https://playwright.dev/docs/api/class-request#request-frame) available.*/- startJSCoverage(options?: {+ serviceWorker(): null|Worker;++ /**+ * Returns resource size information for given request.+ */+ sizes(): Promise<{/**- * Whether anonymous scripts generated by the page should be reported. Defaults to `false`.+ * Size of the request body (POST data payload) in bytes. Set to 0 if there was no body.*/- reportAnonymousScripts?: boolean;+ requestBodySize: number;/**- * Whether to reset coverage on every navigation. Defaults to `true`.+ * Total number of bytes from the start of the HTTP request message until (and including) the double CRLF before the+ * body.*/- resetOnNavigation?: boolean;- }): Promise<void>;+ requestHeadersSize: number;++ /**+ * Size of the received response body (encoded) in bytes.+ */+ responseBodySize: number;++ /**+ * Total number of bytes from the start of the HTTP response message until (and including) the double CRLF before the+ * body.+ */+ responseHeadersSize: number;+ }>;/**- * Returns the array of coverage reports for all stylesheets+ * Returns resource timing information for given request. Most of the timing values become available upon the+ * response, `responseEnd` becomes available when request finishes. Find more information at+ * [Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming).*- * **NOTE** CSS Coverage doesn't include dynamically injected style tags without sourceURLs.+ * **Usage**+ *+ * ```js+ * const requestFinishedPromise = page.waitForEvent('requestfinished');+ * await page.goto('http://example.com');+ * const request = await requestFinishedPromise;+ * console.log(request.timing());+ * ```**/- stopCSSCoverage(): Promise<Array<{+ timing(): {/**- * StyleSheet URL+ * Request start time in milliseconds elapsed since January 1, 1970 00:00:00 UTC*/- url: string;+ startTime: number;/**- * StyleSheet content, if available.+ * Time immediately before the browser starts the domain name lookup for the resource. The value is given in+ * milliseconds relative to `startTime`, -1 if not available.*/- text?: string;+ domainLookupStart: number;/**- * StyleSheet ranges that were used. Ranges are sorted and non-overlapping.+ * Time immediately after the browser starts the domain name lookup for the resource. The value is given in+ * milliseconds relative to `startTime`, -1 if not available.*/- ranges: Array<{- /**- * A start offset in text, inclusive- */- start: number;-- /**- * An end offset in text, exclusive- */- end: number;- }>;- }>>;+ domainLookupEnd: number;- /**- * Returns the array of coverage reports for all scripts- *- * **NOTE** JavaScript Coverage doesn't include anonymous scripts by default. However, scripts with sourceURLs are- * reported.- *- */- stopJSCoverage(): Promise<Array<{/**- * Script URL+ * Time immediately before the user agent starts establishing the connection to the server to retrieve the resource.+ * The value is given in milliseconds relative to `startTime`, -1 if not available.*/- url: string;+ connectStart: number;/**- * Script ID+ * Time immediately before the browser starts the handshake process to secure the current connection. The value is+ * given in milliseconds relative to `startTime`, -1 if not available.*/- scriptId: string;+ secureConnectionStart: number;/**- * Script content, if applicable.+ * Time immediately before the user agent starts establishing the connection to the server to retrieve the resource.+ * The value is given in milliseconds relative to `startTime`, -1 if not available.*/- source?: string;+ connectEnd: number;/**- * V8-specific coverage format.+ * Time immediately before the browser starts requesting the resource from the server, cache, or local resource. The+ * value is given in milliseconds relative to `startTime`, -1 if not available.*/- functions: Array<{- functionName: string;-- isBlockCoverage: boolean;+ requestStart: number;- ranges: Array<{- count: number;+ /**+ * Time immediately after the browser receives the first byte of the response from the server, cache, or local+ * resource. The value is given in milliseconds relative to `startTime`, -1 if not available.+ */+ responseStart: number;- startOffset: number;+ /**+ * Time immediately after the browser receives the last byte of the resource or immediately before the transport+ * connection is closed, whichever comes first. The value is given in milliseconds relative to `startTime`, -1 if not+ * available.+ */+ responseEnd: number;+ };- endOffset: number;- }>;- }>;- }>>;+ /**+ * URL of the request.+ */+ url(): string;}/**- * API for controlling the Playwright debugger. The debugger allows pausing script execution and inspecting the page.- * Obtain the debugger instance via- * [browserContext.debugger](https://playwright.dev/docs/api/class-browsercontext#browser-context-debugger).+ * [Response](https://playwright.dev/docs/api/class-response) class represents responses which are received by page.*/-export interface Debugger {+export interface Response {/**- * Emitted when the debugger pauses or resumes.+ * An object with all the response HTTP headers associated with this response.*/- on(event: 'pausedstatechanged', listener: () => any): this;+ allHeaders(): Promise<{ [key: string]: string; }>;/**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ * Returns the buffer with response body.*/- once(event: 'pausedstatechanged', listener: () => any): this;+ body(): Promise<Buffer>;/**- * Emitted when the debugger pauses or resumes.+ * Waits for this response to finish, returns always `null`.*/- addListener(event: 'pausedstatechanged', listener: () => any): this;+ finished(): Promise<null|Error>;/**- * Removes an event listener added by `on` or `addListener`.+ * Returns the [Frame](https://playwright.dev/docs/api/class-frame) that initiated this response.*/- removeListener(event: 'pausedstatechanged', listener: () => any): this;+ frame(): Frame;/**- * Removes an event listener added by `on` or `addListener`.+ * Indicates whether this Response was fulfilled by a Service Worker's Fetch Handler (i.e. via+ * [FetchEvent.respondWith](https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent/respondWith)).*/- off(event: 'pausedstatechanged', listener: () => any): this;+ fromServiceWorker(): boolean;/**- * Emitted when the debugger pauses or resumes.+ * An object with the response HTTP headers. The header names are lower-cased. Note that this method does not return+ * security-related headers, including cookie-related ones. You can use+ * [response.allHeaders()](https://playwright.dev/docs/api/class-response#response-all-headers) for complete list of+ * headers that include `cookie` information.*/- prependListener(event: 'pausedstatechanged', listener: () => any): this;+ headers(): { [key: string]: string; };/**- * Resumes script execution and pauses again before the next action. Throws if the debugger is not paused.+ * An array with all the request HTTP headers associated with this response. Unlike+ * [response.allHeaders()](https://playwright.dev/docs/api/class-response#response-all-headers), header names are NOT+ * lower-cased. Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple times.*/- next(): Promise<void>;+ headersArray(): Promise<Array<{+ /**+ * Name of the header.+ */+ name: string;++ /**+ * Value of the header.+ */+ value: string;+ }>>;/**- * Returns details about the currently paused call. Returns `null` if the debugger is not paused.+ * Returns the value of the header matching the name. The name is case-insensitive. If multiple headers have the same+ * name (except `set-cookie`), they are returned as a list separated by `, `. For `set-cookie`, the `\n` separator is+ * used. If no headers are found, `null` is returned.+ * @param name Name of the header.*/- pausedDetails(): null|{- location: {- file: string;+ headerValue(name: string): Promise<null|string>;- line?: number;+ /**+ * Returns all values of the headers matching the name, for example `set-cookie`. The name is case-insensitive.+ * @param name Name of the header.+ */+ headerValues(name: string): Promise<Array<string>>;++ /**+ * Returns the http version used by the response.+ */+ httpVersion(): Promise<string>;++ /**+ * Returns the JSON representation of response body.+ *+ * This method will throw if the response body is not parsable via `JSON.parse`.+ */+ json(): Promise<Serializable>;++ /**+ * Contains a boolean stating whether the response was successful (status in the range 200-299) or not.+ */+ ok(): boolean;++ /**+ * Returns the matching [Request](https://playwright.dev/docs/api/class-request) object.+ */+ request(): Request;++ /**+ * Returns SSL and other security information.+ */+ securityDetails(): Promise<null|{+ /**+ * Common Name component of the Issuer field. from the certificate. This should only be used for informational+ * purposes. Optional.+ */+ issuer?: string;++ /**+ * The specific TLS protocol used. (e.g. `TLS 1.3`). Optional.+ */+ protocol?: string;++ /**+ * Common Name component of the Subject field from the certificate. This should only be used for informational+ * purposes. Optional.+ */+ subjectName?: string;++ /**+ * Unix timestamp (in seconds) specifying when this cert becomes valid. Optional.+ */+ validFrom?: number;++ /**+ * Unix timestamp (in seconds) specifying when this cert becomes invalid. Optional.+ */+ validTo?: number;+ }>;- column?: number;- };+ /**+ * Returns the IP address and port of the server.+ */+ serverAddr(): Promise<null|{+ /**+ * IPv4 or IPV6 address of the server.+ */+ ipAddress: string;- title: string;- };+ port: number;+ }>;/**- * Configures the debugger to pause before the next action is executed.- *- * Throws if the debugger is already paused. Use- * [debugger.next()](https://playwright.dev/docs/api/class-debugger#debugger-next) or- * [debugger.runTo(location)](https://playwright.dev/docs/api/class-debugger#debugger-run-to) to step while paused.- *- * Note that [page.pause()](https://playwright.dev/docs/api/class-page#page-pause) is equivalent to a "debugger"- * statement — it pauses execution at the call site immediately. On the contrary,- * [debugger.requestPause()](https://playwright.dev/docs/api/class-debugger#debugger-request-pause) is equivalent to- * "pause on next statement" — it configures the debugger to pause before the next action is executed.+ * Contains the status code of the response (e.g., 200 for a success).*/- requestPause(): Promise<void>;+ status(): number;/**- * Resumes script execution. Throws if the debugger is not paused.+ * Contains the status text of the response (e.g. usually an "OK" for a success).*/- resume(): Promise<void>;+ statusText(): string;/**- * Resumes script execution and pauses when an action originates from the given source location. Throws if the- * debugger is not paused.- * @param location The source location to pause at.+ * Returns the text representation of response body.*/- runTo(location: {- file: string;-- line?: number;+ text(): Promise<string>;- column?: number;- }): Promise<void>;+ /**+ * Contains the URL of the response.+ */+ url(): string;}/**- * [Dialog](https://playwright.dev/docs/api/class-dialog) objects are dispatched by page via the- * [page.on('dialog')](https://playwright.dev/docs/api/class-page#page-event-dialog) event.- *- * An example of using `Dialog` class:- *- * ```js- * const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.- *- * (async () => {- * const browser = await chromium.launch();- * const page = await browser.newPage();- * page.on('dialog', async dialog => {- * console.log(dialog.message());- * await dialog.dismiss();- * });- * await page.evaluate(() => alert('1'));- * await browser.close();- * })();- * ```- *- * **NOTE** Dialogs are dismissed automatically, unless there is a- * [page.on('dialog')](https://playwright.dev/docs/api/class-page#page-event-dialog) listener. When listener is- * present, it **must** either- * [dialog.accept([promptText])](https://playwright.dev/docs/api/class-dialog#dialog-accept) or- * [dialog.dismiss()](https://playwright.dev/docs/api/class-dialog#dialog-dismiss) the dialog - otherwise the page- * will [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the- * dialog, and actions like click will never finish.+ * Whenever a network route is set up with+ * [page.route(url, handler[, options])](https://playwright.dev/docs/api/class-page#page-route) or+ * [browserContext.route(url, handler[, options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-route),+ * the `Route` object allows to handle the route.*+ * Learn more about [networking](https://playwright.dev/docs/network).*/-export interface Dialog {+export interface Route {/**- * Returns when the dialog has been accepted.- * @param promptText A text to enter in prompt. Does not cause any effects if the dialog's `type` is not prompt. Optional.+ * Aborts the route's request.+ * @param errorCode Optional error code. Defaults to `failed`, could be one of the following:+ * - `'aborted'` - An operation was aborted (due to user action)+ * - `'accessdenied'` - Permission to access a resource, other than the network, was denied+ * - `'addressunreachable'` - The IP address is unreachable. This usually means that there is no route to the+ * specified host or network.+ * - `'blockedbyclient'` - The client chose to block the request.+ * - `'blockedbyresponse'` - The request failed because the response was delivered along with requirements which are+ * not met ('X-Frame-Options' and 'Content-Security-Policy' ancestor checks, for instance).+ * - `'connectionaborted'` - A connection timed out as a result of not receiving an ACK for data sent.+ * - `'connectionclosed'` - A connection was closed (corresponding to a TCP FIN).+ * - `'connectionfailed'` - A connection attempt failed.+ * - `'connectionrefused'` - A connection attempt was refused.+ * - `'connectionreset'` - A connection was reset (corresponding to a TCP RST).+ * - `'internetdisconnected'` - The Internet connection has been lost.+ * - `'namenotresolved'` - The host name could not be resolved.+ * - `'timedout'` - An operation timed out.+ * - `'failed'` - A generic failure occurred.*/- accept(promptText?: string): Promise<void>;+ abort(errorCode?: string): Promise<void>;/**- * If dialog is prompt, returns default prompt value. Otherwise, returns empty string.+ * Sends route's request to the network with optional overrides.+ *+ * **Usage**+ *+ * ```js+ * await page.route('**\/*', async (route, request) => {+ * // Override headers+ * const headers = {+ * ...request.headers(),+ * foo: 'foo-value', // set "foo" header+ * bar: undefined, // remove "bar" header+ * };+ * await route.continue({ headers });+ * });+ * ```+ *+ * **Details**+ *+ * The [`headers`](https://playwright.dev/docs/api/class-route#route-continue-option-headers) option applies to both+ * the routed request and any redirects it initiates. However,+ * [`url`](https://playwright.dev/docs/api/class-route#route-continue-option-url),+ * [`method`](https://playwright.dev/docs/api/class-route#route-continue-option-method), and+ * [`postData`](https://playwright.dev/docs/api/class-route#route-continue-option-post-data) only apply to the+ * original request and are not carried over to redirected requests.+ *+ * [route.continue([options])](https://playwright.dev/docs/api/class-route#route-continue) will immediately send the+ * request to the network, other matching handlers won't be invoked. Use+ * [route.fallback([options])](https://playwright.dev/docs/api/class-route#route-fallback) If you want next matching+ * handler in the chain to be invoked.+ *+ * **NOTE** Some request headers are **forbidden** and cannot be overridden (for example, `Cookie`, `Host`,+ * `Content-Length` and others, see+ * [this MDN page](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_request_header) for full list). If an+ * override is provided for a forbidden header, it will be ignored and the original request header will be used.+ *+ * To set custom cookies, use+ * [browserContext.addCookies(cookies)](https://playwright.dev/docs/api/class-browsercontext#browser-context-add-cookies).+ *+ * @param options*/- defaultValue(): string;+ continue(options?: {+ /**+ * If set changes the request HTTP headers. Header values will be converted to a string.+ */+ headers?: { [key: string]: string; };++ /**+ * If set changes the request method (e.g. GET or POST).+ */+ method?: string;++ /**+ * If set changes the post data of request.+ */+ postData?: string|Buffer|Serializable;++ /**+ * If set changes the request URL. New URL must have same protocol as original one.+ */+ url?: string;+ }): Promise<void>;/**- * Returns when the dialog has been dismissed.+ * Continues route's request with optional overrides. The method is similar to+ * [route.continue([options])](https://playwright.dev/docs/api/class-route#route-continue) with the difference that+ * other matching handlers will be invoked before sending the request.+ *+ * **Usage**+ *+ * When several routes match the given pattern, they run in the order opposite to their registration. That way the+ * last registered route can always override all the previous ones. In the example below, request will be handled by+ * the bottom-most handler first, then it'll fall back to the previous one and in the end will be aborted by the first+ * registered route.+ *+ * ```js+ * await page.route('**\/*', async route => {+ * // Runs last.+ * await route.abort();+ * });+ * await page.route('**\/*', async route => {+ * // Runs second.+ * await route.fallback();+ * });+ * await page.route('**\/*', async route => {+ * // Runs first.+ * await route.fallback();+ * });+ * ```+ *+ * Registering multiple routes is useful when you want separate handlers to handle different kinds of requests, for+ * example API calls vs page resources or GET requests vs POST requests as in the example below.+ *+ * ```js+ * // Handle GET requests.+ * await page.route('**\/*', async route => {+ * if (route.request().method() !== 'GET') {+ * await route.fallback();+ * return;+ * }+ * // Handling GET only.+ * // ...+ * });+ *+ * // Handle POST requests.+ * await page.route('**\/*', async route => {+ * if (route.request().method() !== 'POST') {+ * await route.fallback();+ * return;+ * }+ * // Handling POST only.+ * // ...+ * });+ * ```+ *+ * One can also modify request while falling back to the subsequent handler, that way intermediate route handler can+ * modify url, method, headers and postData of the request.+ *+ * ```js+ * await page.route('**\/*', async (route, request) => {+ * // Override headers+ * const headers = {+ * ...request.headers(),+ * foo: 'foo-value', // set "foo" header+ * bar: undefined, // remove "bar" header+ * };+ * await route.fallback({ headers });+ * });+ * ```+ *+ * Use [route.continue([options])](https://playwright.dev/docs/api/class-route#route-continue) to immediately send the+ * request to the network, other matching handlers won't be invoked in that case.+ * @param options*/- dismiss(): Promise<void>;+ fallback(options?: {+ /**+ * If set changes the request HTTP headers. Header values will be converted to a string.+ */+ headers?: { [key: string]: string; };++ /**+ * If set changes the request method (e.g. GET or POST).+ */+ method?: string;++ /**+ * If set changes the post data of request.+ */+ postData?: string|Buffer|Serializable;++ /**+ * If set changes the request URL. New URL must have same protocol as original one. Changing the URL won't affect the+ * route matching, all the routes are matched using the original request URL.+ */+ url?: string;+ }): Promise<void>;/**- * A message displayed in the dialog.+ * Performs the request and fetches result without fulfilling it, so that the response could be modified and then+ * fulfilled.+ *+ * **Usage**+ *+ * ```js+ * await page.route('https://dog.ceo/api/breeds/list/all', async route => {+ * const response = await route.fetch();+ * const json = await response.json();+ * json.message['big_red_dog'] = [];+ * await route.fulfill({ response, json });+ * });+ * ```+ *+ * **Details**+ *+ * Note that [`headers`](https://playwright.dev/docs/api/class-route#route-fetch-option-headers) option will apply to+ * the fetched request as well as any redirects initiated by it. If you want to only apply+ * [`headers`](https://playwright.dev/docs/api/class-route#route-fetch-option-headers) to the original request, but+ * not to redirects, look into [route.continue([options])](https://playwright.dev/docs/api/class-route#route-continue)+ * instead.+ * @param options*/- message(): string;+ fetch(options?: {+ /**+ * If set changes the request HTTP headers. Header values will be converted to a string.+ */+ headers?: { [key: string]: string; };- /**- * The page that initiated this dialog, if available.- */- page(): null|Page;+ /**+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.+ */+ maxRedirects?: number;- /**- * Returns dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`.- */- type(): string;-}+ /**+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.+ */+ maxRetries?: number;-/**- * [Disposable](https://playwright.dev/docs/api/class-disposable) is returned from various methods to allow undoing- * the corresponding action. For example,- * [page.addInitScript(script[, arg])](https://playwright.dev/docs/api/class-page#page-add-init-script) returns a- * [Disposable](https://playwright.dev/docs/api/class-disposable) that can be used to remove the init script.- */-export interface Disposable {- /**- * Removes the associated resource. For example, removes the init script installed via- * [page.addInitScript(script[, arg])](https://playwright.dev/docs/api/class-page#page-add-init-script) or- * [browserContext.addInitScript(script[, arg])](https://playwright.dev/docs/api/class-browsercontext#browser-context-add-init-script).- */- dispose(): Promise<void>;+ /**+ * If set changes the request method (e.g. GET or POST).+ */+ method?: string;- [Symbol.asyncDispose](): Promise<void>;-}+ /**+ * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string+ * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`+ * header will be set to `application/octet-stream` if not explicitly set.+ */+ postData?: string|Buffer|Serializable;-/**- * [Download](https://playwright.dev/docs/api/class-download) objects are dispatched by page via the- * [page.on('download')](https://playwright.dev/docs/api/class-page#page-event-download) event.- *- * All the downloaded files belonging to the browser context are deleted when the browser context is closed.- *- * Download event is emitted once the download starts. Download path becomes available once download completes.- *- * ```js- * // Start waiting for download before clicking. Note no await.- * const downloadPromise = page.waitForEvent('download');- * await page.getByText('Download file').click();- * const download = await downloadPromise;- *- * // Wait for the download process to complete and save the downloaded file somewhere.- * await download.saveAs('/path/to/save/at/' + download.suggestedFilename());- * ```- *- */-export interface Download {- /**- * Cancels a download. Will not fail if the download is already finished or canceled. Upon successful cancellations,- * `download.failure()` would resolve to `'canceled'`.- */- cancel(): Promise<void>;+ /**+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.+ */+ timeout?: number;++ /**+ * If set changes the request URL. New URL must have same protocol as original one.+ */+ url?: string;+ }): Promise<APIResponse>;/**- * Returns a readable stream for a successful download, or throws for a failed/canceled download.+ * Fulfills route's request with given response.*- * **NOTE** If you don't need a readable stream, it's usually simpler to read the file from disk after the download- * completed. See [download.path()](https://playwright.dev/docs/api/class-download#download-path).+ * **Usage**+ *+ * An example of fulfilling all requests with 404 responses:+ *+ * ```js+ * await page.route('**\/*', async route => {+ * await route.fulfill({+ * status: 404,+ * contentType: 'text/plain',+ * body: 'Not Found!'+ * });+ * });+ * ```+ *+ * An example of serving static file:+ *+ * ```js+ * await page.route('**\/xhr_endpoint', route => route.fulfill({ path: 'mock_data.json' }));+ * ```*+ * @param options*/- createReadStream(): Promise<Readable>;+ fulfill(options?: {+ /**+ * Response body.+ */+ body?: string|Buffer;- /**- * Deletes the downloaded file. Will wait for the download to finish if necessary.- */- delete(): Promise<void>;+ /**+ * If set, equals to setting `Content-Type` response header.+ */+ contentType?: string;- /**- * Returns download error if any. Will wait for the download to finish if necessary.- */- failure(): Promise<null|string>;+ /**+ * Response headers. Header values will be converted to a string.+ */+ headers?: { [key: string]: string; };- /**- * Get the page that the download belongs to.- */- page(): Page;+ /**+ * JSON response. This method will set the content type to `application/json` if not set.+ */+ json?: Serializable;++ /**+ * File path to respond with. The content type will be inferred from file extension. If `path` is a relative path,+ * then it is resolved relative to the current working directory.+ */+ path?: string;++ /**+ * [APIResponse](https://playwright.dev/docs/api/class-apiresponse) to fulfill route's request with. Individual fields+ * of the response (such as headers) can be overridden using fulfill options.+ */+ response?: APIResponse;++ /**+ * Response status code, defaults to `200`.+ */+ status?: number;+ }): Promise<void>;/**- * Returns path to the downloaded file for a successful download, or throws for a failed/canceled download. The method- * will wait for the download to finish if necessary. The method throws when connected remotely.- *- * Note that the download's file name is a random GUID, use- * [download.suggestedFilename()](https://playwright.dev/docs/api/class-download#download-suggested-filename) to get- * suggested file name.+ * A request to be routed.*/- path(): Promise<string>;+ request(): Request;+}+/**+ * Selectors can be used to install custom selector engines. See [extensibility](https://playwright.dev/docs/extensibility) for more+ * information.+ */+export interface Selectors {/**- * Copy the download to a user-specified path. It is safe to call this method while the download is still in progress.- * Will wait for the download to finish if necessary.+ * Selectors must be registered before creating the page.** **Usage***+ * An example of registering selector engine that queries elements based on a tag name:+ ** ```js- * await download.saveAs('/path/to/save/at/' + download.suggestedFilename());+ * const { selectors, firefox } = require('@playwright/test'); // Or 'chromium' or 'webkit'.+ *+ * (async () => {+ * // Must be a function that evaluates to a selector engine instance.+ * const createTagNameEngine = () => ({+ * // Returns the first element matching given selector in the root's subtree.+ * query(root, selector) {+ * return root.querySelector(selector);+ * },+ *+ * // Returns all elements matching given selector in the root's subtree.+ * queryAll(root, selector) {+ * return Array.from(root.querySelectorAll(selector));+ * }+ * });+ *+ * // Register the engine. Selectors will be prefixed with "tag=".+ * await selectors.register('tag', createTagNameEngine);+ *+ * const browser = await firefox.launch();+ * const page = await browser.newPage();+ * await page.setContent(`<div><button>Click me</button></div>`);+ *+ * // Use the selector prefixed with its name.+ * const button = page.locator('tag=button');+ * // We can combine it with built-in locators.+ * await page.locator('tag=div').getByText('Click me').click();+ * // Can use it in any methods supporting selectors.+ * const buttonCount = await page.locator('tag=button').count();+ *+ * await browser.close();+ * })();* ```*- * @param path Path where the download should be copied.+ * @param name Name that is used in selectors as a prefix, e.g. `{name: 'foo'}` enables `foo=myselectorbody` selectors. May only+ * contain `[a-zA-Z0-9_]` characters.+ * @param script Script that evaluates to a selector engine instance. The script is evaluated in the page context.+ * @param options*/- saveAs(path: string): Promise<void>;+ register(name: string, script: Function|string|{+ /**+ * Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working+ * directory. Optional.+ */+ path?: string;++ /**+ * Raw script content. Optional.+ */+ content?: string;+ }, options?: {+ /**+ * Whether to run this selector engine in isolated JavaScript environment. This environment has access to the same+ * DOM, but not any JavaScript objects from the frame's scripts. Defaults to `false`. Note that running as a content+ * script is not guaranteed when this engine is used together with other registered engines.+ */+ contentScript?: boolean;+ }): Promise<void>;/**- * Returns suggested filename for this download. It is typically computed by the browser from the- * [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) response- * header or the `download` attribute. See the spec on [whatwg](https://html.spec.whatwg.org/#downloading-resources).- * Different browsers can use different logic for computing it.+ * Defines custom attribute name to be used in+ * [page.getByTestId(testId)](https://playwright.dev/docs/api/class-page#page-get-by-test-id). `data-testid` is used+ * by default.+ * @param attributeName Test id attribute name.*/- suggestedFilename(): string;+ setTestIdAttribute(attributeName: string): void;+}+/**+ * The Touchscreen class operates in main-frame CSS pixels relative to the top-left corner of the viewport. Methods on+ * the touchscreen can only be used in browser contexts that have been initialized with `hasTouch` set to true.+ *+ * This class is limited to emulating tap gestures. For examples of other gestures simulated by manually dispatching+ * touch events, see the [emulating legacy touch events](https://playwright.dev/docs/touch-events) page.+ */+export interface Touchscreen {/**- * Returns downloaded url.+ * Dispatches a `touchstart` and `touchend` event with a single touch at the position+ * ([`x`](https://playwright.dev/docs/api/class-touchscreen#touchscreen-tap-option-x),[`y`](https://playwright.dev/docs/api/class-touchscreen#touchscreen-tap-option-y)).+ *+ * **NOTE** [page.tap(selector[, options])](https://playwright.dev/docs/api/class-page#page-tap) the method will throw+ * if [`hasTouch`](https://playwright.dev/docs/api/class-browser#browser-new-context-option-has-touch) option of the+ * browser context is false.+ *+ * @param x X coordinate relative to the main frame's viewport in CSS pixels.+ * @param y Y coordinate relative to the main frame's viewport in CSS pixels.*/- url(): string;+ tap(x: number, y: number): Promise<void>;}/**- * [FileChooser](https://playwright.dev/docs/api/class-filechooser) objects are dispatched by the page in the- * [page.on('filechooser')](https://playwright.dev/docs/api/class-page#page-event-file-chooser) event.+ * API for collecting and saving Playwright traces. Playwright traces can be opened in+ * [Trace Viewer](https://playwright.dev/docs/trace-viewer) after Playwright script runs.+ *+ * **NOTE** You probably want to+ * [enable tracing in your config file](https://playwright.dev/docs/api/class-testoptions#test-options-trace) instead+ * of using `context.tracing`.+ *+ * The `context.tracing` API captures browser operations and network activity, but it doesn't record test assertions+ * (like `expect` calls). We recommend+ * [enabling tracing through Playwright Test configuration](https://playwright.dev/docs/api/class-testoptions#test-options-trace),+ * which includes those assertions and provides a more complete trace for debugging test failures.+ *+ * Start recording a trace before performing actions. At the end, stop tracing and save it to a file.** ```js- * // Start waiting for file chooser before clicking. Note no await.- * const fileChooserPromise = page.waitForEvent('filechooser');- * await page.getByText('Upload file').click();- * const fileChooser = await fileChooserPromise;- * await fileChooser.setFiles(path.join(__dirname, 'myfile.pdf'));+ * const browser = await chromium.launch();+ * const context = await browser.newContext();+ * await context.tracing.start({ screenshots: true, snapshots: true });+ * const page = await context.newPage();+ * await page.goto('https://playwright.dev');+ * expect(page.url()).toBe('https://playwright.dev');+ * await context.tracing.stop({ path: 'trace.zip' });* ```**/-export interface FileChooser {+export interface Tracing {/**- * Returns input element associated with this file chooser.+ * **NOTE** Use `test.step` instead when available.+ *+ * Creates a new group within the trace, assigning any subsequent API calls to this group, until+ * [tracing.groupEnd()](https://playwright.dev/docs/api/class-tracing#tracing-group-end) is called. Groups can be+ * nested and will be visible in the trace viewer.+ *+ * **Usage**+ *+ * ```js+ * // use test.step instead+ * await test.step('Log in', async () => {+ * // ...+ * });+ * ```+ *+ * @param name Group name shown in the trace viewer.+ * @param options*/- element(): ElementHandle;+ group(name: string, options?: {+ /**+ * Specifies a custom location for the group to be shown in the trace viewer. Defaults to the location of the+ * [tracing.group(name[, options])](https://playwright.dev/docs/api/class-tracing#tracing-group) call.+ */+ location?: {+ file: string;- /**- * Returns whether this file chooser accepts multiple files.- */- isMultiple(): boolean;+ line?: number;++ column?: number;+ };+ }): Promise<Disposable>;/**- * Returns page this file chooser belongs to.+ * Closes the last group created by+ * [tracing.group(name[, options])](https://playwright.dev/docs/api/class-tracing#tracing-group).*/- page(): Page;+ groupEnd(): Promise<void>;/**- * Sets the value of the file input this chooser is associated with. If some of the `filePaths` are relative paths,- * then they are resolved relative to the current working directory. For empty array, clears the selected files.- * @param files+ * Start tracing.+ *+ * **NOTE** You probably want to+ * [enable tracing in your config file](https://playwright.dev/docs/api/class-testoptions#test-options-trace) instead+ * of using `Tracing.start`.+ *+ * The `context.tracing` API captures browser operations and network activity, but it doesn't record test assertions+ * (like `expect` calls). We recommend+ * [enabling tracing through Playwright Test configuration](https://playwright.dev/docs/api/class-testoptions#test-options-trace),+ * which includes those assertions and provides a more complete trace for debugging test failures.+ *+ * **Usage**+ *+ * ```js+ * await context.tracing.start({ screenshots: true, snapshots: true });+ * const page = await context.newPage();+ * await page.goto('https://playwright.dev');+ * expect(page.url()).toBe('https://playwright.dev');+ * await context.tracing.stop({ path: 'trace.zip' });+ * ```+ ** @param options*/- setFiles(files: string|ReadonlyArray<string>|{+ start(options?: {/**- * File name+ * When enabled, the trace is written to an unarchived file that is updated in real time as actions occur, instead of+ * caching changes and archiving them into a zip file at the end. This is useful for live trace viewing during test+ * execution.*/- name: string;+ live?: boolean;/**- * File type+ * If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the+ * [`tracesDir`](https://playwright.dev/docs/api/class-browsertype#browser-type-launch-option-traces-dir) directory+ * specified in+ * [browserType.launch([options])](https://playwright.dev/docs/api/class-browsertype#browser-type-launch). To specify+ * the final trace zip file name, you need to pass `path` option to+ * [tracing.stop([options])](https://playwright.dev/docs/api/class-tracing#tracing-stop) instead.*/- mimeType: string;+ name?: string;/**- * File content- */- buffer: Buffer;- }|ReadonlyArray<{- /**- * File name+ * Whether to capture screenshots during tracing. Screenshots are used to build a timeline preview.*/- name: string;+ screenshots?: boolean;/**- * File type+ * If this option is true tracing will+ * - capture DOM snapshot on every action+ * - record network activity*/- mimeType: string;+ snapshots?: boolean;/**- * File content- */- buffer: Buffer;- }>, options?: {- /**- * This option has no effect.- * @deprecated This option has no effect.+ * Whether to include source files for trace actions.*/- noWaitAfter?: boolean;+ sources?: boolean;/**- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`- * option in the config, or by using the- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.+ * Trace name to be shown in the Trace Viewer.*/- timeout?: number;+ title?: string;}): Promise<void>;-}--/**- * FrameLocator represents a view to the `iframe` on the page. It captures the logic sufficient to retrieve the- * `iframe` and locate elements in that iframe. FrameLocator can be created with either- * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame),- * [page.frameLocator(selector)](https://playwright.dev/docs/api/class-page#page-frame-locator) or- * [locator.frameLocator(selector)](https://playwright.dev/docs/api/class-locator#locator-frame-locator) method.- *- * ```js- * const locator = page.locator('#my-frame').contentFrame().getByText('Submit');- * await locator.click();- * ```- *- * **Strictness**- *- * Frame locators are strict. This means that all operations on frame locators will throw if more than one element- * matches a given selector.- *- * ```js- * // Throws if there are several frames in DOM:- * await page.locator('.result-frame').contentFrame().getByRole('button').click();- *- * // Works because we explicitly tell locator to pick the first frame:- * await page.locator('.result-frame').contentFrame().first().getByRole('button').click();- * ```- *- * **Converting Locator to FrameLocator**- *- * If you have a [Locator](https://playwright.dev/docs/api/class-locator) object pointing to an `iframe` it can be- * converted to [FrameLocator](https://playwright.dev/docs/api/class-framelocator) using- * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame).- *- * **Converting FrameLocator to Locator**- *- * If you have a [FrameLocator](https://playwright.dev/docs/api/class-framelocator) object it can be converted to- * [Locator](https://playwright.dev/docs/api/class-locator) pointing to the same `iframe` using- * [frameLocator.owner()](https://playwright.dev/docs/api/class-framelocator#frame-locator-owner).- */-export interface FrameLocator {- /**- * Returns locator to the first matching frame.- * @deprecated Use [locator.first()](https://playwright.dev/docs/api/class-locator#locator-first) followed by- * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame) instead.- */- first(): FrameLocator;-- /**- * When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements- * in that iframe.- * @param selector A selector to use when resolving DOM element.- */- frameLocator(selector: string): FrameLocator;-- /**- * Allows locating elements by their alt text.- *- * **Usage**- *- * For example, this method will find the image by alt text "Playwright logo":- *- * ```html- * <img alt='Playwright logo'>- * ```- *- * ```js- * await page.getByAltText('Playwright logo').click();- * ```- *- * @param text Text to locate the element for.- * @param options- */- getByAltText(text: string|RegExp, options?: {- /**- * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a- * regular expression. Note that exact match still trims whitespace.- */- exact?: boolean;- }): Locator;/**- * Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the- * `aria-label` attribute.+ * Start a new trace chunk. If you'd like to record multiple traces on the same+ * [BrowserContext](https://playwright.dev/docs/api/class-browsercontext), use+ * [tracing.start([options])](https://playwright.dev/docs/api/class-tracing#tracing-start) once, and then create+ * multiple trace chunks with+ * [tracing.startChunk([options])](https://playwright.dev/docs/api/class-tracing#tracing-start-chunk) and+ * [tracing.stopChunk([options])](https://playwright.dev/docs/api/class-tracing#tracing-stop-chunk).** **Usage***- * For example, this method will find inputs by label "Username" and "Password" in the following DOM:+ * ```js+ * await context.tracing.start({ screenshots: true, snapshots: true });+ * const page = await context.newPage();+ * await page.goto('https://playwright.dev');*- * ```html- * <input aria-label="Username">- * <label for="password-input">Password:</label>- * <input id="password-input">- * ```+ * await context.tracing.startChunk();+ * await page.getByText('Get Started').click();+ * // Everything between startChunk and stopChunk will be recorded in the trace.+ * await context.tracing.stopChunk({ path: 'trace1.zip' });*- * ```js- * await page.getByLabel('Username').fill('john');- * await page.getByLabel('Password').fill('secret');+ * await context.tracing.startChunk();+ * await page.goto('http://example.com');+ * // Save a second trace file with different actions.+ * await context.tracing.stopChunk({ path: 'trace2.zip' });* ```*- * @param text Text to locate the element for.* @param options*/- getByLabel(text: string|RegExp, options?: {+ startChunk(options?: {/**- * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a- * regular expression. Note that exact match still trims whitespace.+ * If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the+ * [`tracesDir`](https://playwright.dev/docs/api/class-browsertype#browser-type-launch-option-traces-dir) directory+ * specified in+ * [browserType.launch([options])](https://playwright.dev/docs/api/class-browsertype#browser-type-launch). To specify+ * the final trace zip file name, you need to pass `path` option to+ * [tracing.stopChunk([options])](https://playwright.dev/docs/api/class-tracing#tracing-stop-chunk) instead.*/- exact?: boolean;- }): Locator;+ name?: string;++ /**+ * Trace name to be shown in the Trace Viewer.+ */+ title?: string;+ }): Promise<void>;/**- * Allows locating input elements by the placeholder text.- *- * **Usage**- *- * For example, consider the following DOM structure.+ * Start recording a HAR (HTTP Archive) of network activity in this context. The HAR file is written to disk when+ * [tracing.stopHar()](https://playwright.dev/docs/api/class-tracing#tracing-stop-har) is called, or when the returned+ * [Disposable](https://playwright.dev/docs/api/class-disposable) is disposed.*- * ```html- * <input type="email" placeholder="[email protected]" />- * ```+ * Only one HAR recording can be active at a time per+ * [BrowserContext](https://playwright.dev/docs/api/class-browsercontext).*- * You can fill the input after locating it by the placeholder text:+ * **Usage**** ```js- * await page- * .getByPlaceholder('[email protected]')- * .fill('[email protected]');+ * await context.tracing.startHar('trace.har');+ * const page = await context.newPage();+ * await page.goto('https://playwright.dev');+ * await context.tracing.stopHar();* ```*- * @param text Text to locate the element for.+ * @param path Path on the filesystem to write the HAR file to. If the file name ends with `.zip`, the HAR is saved as a zip+ * archive with response bodies attached as separate files.* @param options*/- getByPlaceholder(text: string|RegExp, options?: {+ startHar(path: string, options?: {/**- * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a- * regular expression. Note that exact match still trims whitespace.+ * Optional setting to control resource content management. If `omit` is specified, content is not persisted. If+ * `attach` is specified, resources are persisted as separate files or entries in the ZIP archive. If `embed` is+ * specified, content is stored inline the HAR file as per HAR specification. Defaults to `attach` for `.zip` output+ * files and to `embed` for all other file extensions.*/- exact?: boolean;- }): Locator;+ content?: "omit"|"embed"|"attach";++ /**+ * When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,+ * cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.+ */+ mode?: "full"|"minimal";++ /**+ * Only used together with `content: 'attach'`. When set, response bodies are placed in this directory instead of next+ * to the HAR file. Not compatible with a `.zip` HAR file.+ */+ resourcesDir?: string;++ /**+ * A glob or regex pattern to filter requests that are stored in the HAR. Defaults to none.+ */+ urlFilter?: string|RegExp;+ }): Promise<Disposable>;/**- * Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),- * [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and- * [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).- *- * **Usage**- *- * Consider the following DOM structure.- *- * ```html- * <h3>Sign up</h3>- * <label>- * <input type="checkbox" /> Subscribe- * </label>- * <br/>- * <button>Submit</button>- * ```- *- * You can locate each element by its implicit role:- *- * ```js- * await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible();- *- * await page.getByRole('checkbox', { name: 'Subscribe' }).check();- *- * await page.getByRole('button', { name: /submit/i }).click();- * ```- *- * **Details**- *- * Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback- * about the ARIA guidelines.- *- * Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)- * that is recognized by the role selector. You can find all the- * [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**- * duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.- * @param role Required aria role.+ * Stop tracing.* @param options*/- getByRole(role: "alert"|"alertdialog"|"application"|"article"|"banner"|"blockquote"|"button"|"caption"|"cell"|"checkbox"|"code"|"columnheader"|"combobox"|"complementary"|"contentinfo"|"definition"|"deletion"|"dialog"|"directory"|"document"|"emphasis"|"feed"|"figure"|"form"|"generic"|"grid"|"gridcell"|"group"|"heading"|"img"|"insertion"|"link"|"list"|"listbox"|"listitem"|"log"|"main"|"marquee"|"math"|"meter"|"menu"|"menubar"|"menuitem"|"menuitemcheckbox"|"menuitemradio"|"navigation"|"none"|"note"|"option"|"paragraph"|"presentation"|"progressbar"|"radio"|"radiogroup"|"region"|"row"|"rowgroup"|"rowheader"|"scrollbar"|"search"|"searchbox"|"separator"|"slider"|"spinbutton"|"status"|"strong"|"subscript"|"superscript"|"switch"|"tab"|"table"|"tablist"|"tabpanel"|"term"|"textbox"|"time"|"timer"|"toolbar"|"tooltip"|"tree"|"treegrid"|"treeitem", options?: {+ stop(options?: {/**- * An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.- *- * Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).+ * Export trace into the file with the given path.*/- checked?: boolean;+ path?: string;+ }): Promise<void>;+ /**+ * Stop the trace chunk. See+ * [tracing.startChunk([options])](https://playwright.dev/docs/api/class-tracing#tracing-start-chunk) for more details+ * about multiple trace chunks.+ * @param options+ */+ stopChunk(options?: {/**- * Option to match the [accessible description](https://w3c.github.io/accname/#dfn-accessible-description). By- * default, matching is case-insensitive and searches for a substring, use- * [`exact`](https://playwright.dev/docs/api/class-framelocator#frame-locator-get-by-role-option-exact) to control- * this behavior.- *- * Learn more about [accessible description](https://w3c.github.io/accname/#dfn-accessible-description).+ * Export trace collected since the last+ * [tracing.startChunk([options])](https://playwright.dev/docs/api/class-tracing#tracing-start-chunk) call into the+ * file with the given path.*/- description?: string|RegExp;+ path?: string;+ }): Promise<void>;++ /**+ * Stop HAR recording and save the HAR file to the path given to+ * [tracing.startHar(path[, options])](https://playwright.dev/docs/api/class-tracing#tracing-start-har).+ */+ stopHar(): Promise<void>;+}++/**+ * When browser context is created with the `recordVideo` option, each page has a video object associated with it.+ *+ * ```js+ * console.log(await page.video().path());+ * ```+ *+ */+export interface Video {+ /**+ * Deletes the video file. Will wait for the video to finish if necessary.+ */+ delete(): Promise<void>;++ /**+ * Returns the file system path this video will be recorded to. The video is guaranteed to be written to the+ * filesystem upon closing the browser context. This method throws when connected remotely.+ */+ path(): Promise<string>;++ /**+ * Saves the video to a user-specified path. It is safe to call this method while the video is still in progress, or+ * after the page has closed. This method waits until the page is closed and the video is fully saved.+ * @param path Path where the video should be saved.+ */+ saveAs(path: string): Promise<void>;+}++/**+ * [WebError](https://playwright.dev/docs/api/class-weberror) class represents an unhandled exception thrown in the+ * page. It is dispatched via the+ * [browserContext.on('weberror')](https://playwright.dev/docs/api/class-browsercontext#browser-context-event-web-error)+ * event.+ *+ * ```js+ * // Log all uncaught errors to the terminal+ * context.on('weberror', webError => {+ * console.log(`Uncaught exception: "${webError.error()}"`);+ * });+ *+ * // Navigate to a page with an exception.+ * await page.goto('data:text/html,<script>throw new Error("Test")</script>');+ * ```+ *+ */+export interface WebError {+ /**+ * Unhandled error that was thrown.+ */+ error(): Error;++ location(): {+ /**+ * URL of the resource.+ */+ url: string;++ /**+ * 0-based line number in the resource.+ */+ line: number;++ /**+ * 0-based column number in the resource.+ */+ column: number;+ };++ /**+ * The page that produced this unhandled exception, if any.+ */+ page(): null|Page;+}++/**+ * The [WebSocket](https://playwright.dev/docs/api/class-websocket) class represents WebSocket connections within a+ * page. It provides the ability to inspect and manipulate the data being transmitted and received.+ *+ * If you want to intercept or modify WebSocket frames, consider using+ * [WebSocketRoute](https://playwright.dev/docs/api/class-websocketroute).+ */+export interface WebSocket {+ /**+ * Fired when the websocket closes.+ */+ on(event: 'close', listener: (webSocket: WebSocket) => any): this;+ /**+ * Fired when the websocket receives a frame.+ */+ on(event: 'framereceived', listener: (data: {/**- * An attribute that is usually set by `aria-disabled` or `disabled`.- *- * **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about- * [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).- *+ * frame payload*/- disabled?: boolean;+ payload: string|Buffer;+ }) => any): this;+ /**+ * Fired when the websocket sends a frame.+ */+ on(event: 'framesent', listener: (data: {/**- * Whether [`name`](https://playwright.dev/docs/api/class-framelocator#frame-locator-get-by-role-option-name) and- * [`description`](https://playwright.dev/docs/api/class-framelocator#frame-locator-get-by-role-option-description)- * are matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when the value is a regular- * expression. Note that exact match still trims whitespace.+ * frame payload*/- exact?: boolean;+ payload: string|Buffer;+ }) => any): this;+ /**+ * Fired when the websocket has an error.+ */+ on(event: 'socketerror', listener: (string: string) => any): this;++ /**+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ */+ once(event: 'close', listener: (webSocket: WebSocket) => any): this;++ /**+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ */+ once(event: 'framereceived', listener: (data: {/**- * An attribute that is usually set by `aria-expanded`.- *- * Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).+ * frame payload*/- expanded?: boolean;+ payload: string|Buffer;+ }) => any): this;+ /**+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ */+ once(event: 'framesent', listener: (data: {/**- * Option that controls whether hidden elements are matched. By default, only non-hidden elements, as- * [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.- *- * Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).+ * frame payload*/- includeHidden?: boolean;+ payload: string|Buffer;+ }) => any): this;++ /**+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ */+ once(event: 'socketerror', listener: (string: string) => any): this;++ /**+ * Fired when the websocket closes.+ */+ addListener(event: 'close', listener: (webSocket: WebSocket) => any): this;+ /**+ * Fired when the websocket receives a frame.+ */+ addListener(event: 'framereceived', listener: (data: {/**- * A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values- * for `<h1>-<h6>` elements.- *- * Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).+ * frame payload*/- level?: number;+ payload: string|Buffer;+ }) => any): this;+ /**+ * Fired when the websocket sends a frame.+ */+ addListener(event: 'framesent', listener: (data: {/**- * Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is- * case-insensitive and searches for a substring, use- * [`exact`](https://playwright.dev/docs/api/class-framelocator#frame-locator-get-by-role-option-exact) to control- * this behavior.- *- * Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).+ * frame payload*/- name?: string|RegExp;+ payload: string|Buffer;+ }) => any): this;++ /**+ * Fired when the websocket has an error.+ */+ addListener(event: 'socketerror', listener: (string: string) => any): this;++ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ removeListener(event: 'close', listener: (webSocket: WebSocket) => any): this;+ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ removeListener(event: 'framereceived', listener: (data: {/**- * An attribute that is usually set by `aria-pressed`.- *- * Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).+ * frame payload*/- pressed?: boolean;+ payload: string|Buffer;+ }) => any): this;+ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ removeListener(event: 'framesent', listener: (data: {/**- * An attribute that is usually set by `aria-selected`.- *- * Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).+ * frame payload*/- selected?: boolean;- }): Locator;+ payload: string|Buffer;+ }) => any): this;/**- * Locate element by the test id.- *- * **Usage**- *- * Consider the following DOM structure.- *- * ```html- * <button data-testid="directions">Itinéraire</button>- * ```- *- * You can locate the element by its test id:- *- * ```js- * await page.getByTestId('directions').click();- * ```- *- * **Details**- *- * By default, the `data-testid` attribute is used as a test id. Use- * [selectors.setTestIdAttribute(attributeName)](https://playwright.dev/docs/api/class-selectors#selectors-set-test-id-attribute)- * to configure a different test id attribute if necessary.- *- * ```js- * // Set custom test id attribute from @playwright/test config:- * import { defineConfig } from '@playwright/test';- *- * export default defineConfig({- * use: {- * testIdAttribute: 'data-pw'- * },- * });- * ```- *- * @param testId Id to locate the element by.+ * Removes an event listener added by `on` or `addListener`.*/- getByTestId(testId: string|RegExp): Locator;+ removeListener(event: 'socketerror', listener: (string: string) => any): this;/**- * Allows locating elements that contain given text.- *- * See also [locator.filter([options])](https://playwright.dev/docs/api/class-locator#locator-filter) that allows to- * match by another criteria, like an accessible role, and then filter by the text content.- *- * **Usage**- *- * Consider the following DOM structure:- *- * ```html- * <div>Hello <span>world</span></div>- * <div>Hello</div>- * ```- *- * You can locate by text substring, exact string, or a regular expression:- *- * ```js- * // Matches <span>- * page.getByText('world');- *- * // Matches first <div>- * page.getByText('Hello world');- *- * // Matches second <div>- * page.getByText('Hello', { exact: true });- *- * // Matches both <div>s- * page.getByText(/Hello/);- *- * // Matches second <div>- * page.getByText(/^hello$/i);- * ```- *- * **Details**- *- * Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into- * one, turns line breaks into spaces and ignores leading and trailing whitespace.- *- * Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For- * example, locating by text `"Log in"` matches `<input type=button value="Log in">`.- * @param text Text to locate the element for.- * @param options+ * Removes an event listener added by `on` or `addListener`.*/- getByText(text: string|RegExp, options?: {+ off(event: 'close', listener: (webSocket: WebSocket) => any): this;++ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ off(event: 'framereceived', listener: (data: {/**- * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a- * regular expression. Note that exact match still trims whitespace.+ * frame payload*/- exact?: boolean;- }): Locator;+ payload: string|Buffer;+ }) => any): this;/**- * Allows locating elements by their title attribute.- *- * **Usage**- *- * Consider the following DOM structure.- *- * ```html- * <span title='Issues count'>25 issues</span>- * ```- *- * You can check the issues count after locating it by the title text:- *- * ```js- * await expect(page.getByTitle('Issues count')).toHaveText('25 issues');- * ```- *- * @param text Text to locate the element for.- * @param options+ * Removes an event listener added by `on` or `addListener`.*/- getByTitle(text: string|RegExp, options?: {+ off(event: 'framesent', listener: (data: {/**- * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a- * regular expression. Note that exact match still trims whitespace.+ * frame payload*/- exact?: boolean;- }): Locator;+ payload: string|Buffer;+ }) => any): this;/**- * Returns locator to the last matching frame.- * @deprecated Use [locator.last()](https://playwright.dev/docs/api/class-locator#locator-last) followed by- * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame) instead.+ * Removes an event listener added by `on` or `addListener`.*/- last(): FrameLocator;+ off(event: 'socketerror', listener: (string: string) => any): this;/**- * The method finds an element matching the specified selector in the locator's subtree. It also accepts filter- * options, similar to [locator.filter([options])](https://playwright.dev/docs/api/class-locator#locator-filter)- * method.- *- * [Learn more about locators](https://playwright.dev/docs/locators).- * @param selectorOrLocator A selector or locator to use when resolving DOM element.- * @param options+ * Fired when the websocket closes.*/- locator(selectorOrLocator: string|Locator, options?: {- /**- * Narrows down the results of the method to those which contain elements matching this relative locator. For example,- * `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.- *- * Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not- * the document root. For example, you can find `content` that has `div` in- * `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article- * div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.- *- * Note that outer and inner locators must belong to the same frame. Inner locator must not contain- * [FrameLocator](https://playwright.dev/docs/api/class-framelocator)s.- */- has?: Locator;-- /**- * Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the- * outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.- *- * Note that outer and inner locators must belong to the same frame. Inner locator must not contain- * [FrameLocator](https://playwright.dev/docs/api/class-framelocator)s.- */- hasNot?: Locator;+ prependListener(event: 'close', listener: (webSocket: WebSocket) => any): this;+ /**+ * Fired when the websocket receives a frame.+ */+ prependListener(event: 'framereceived', listener: (data: {/**- * Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.- * When passed a [string], matching is case-insensitive and searches for a substring.+ * frame payload*/- hasNotText?: string|RegExp;+ payload: string|Buffer;+ }) => any): this;+ /**+ * Fired when the websocket sends a frame.+ */+ prependListener(event: 'framesent', listener: (data: {/**- * Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When- * passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches- * `<article><div>Playwright</div></article>`.+ * frame payload*/- hasText?: string|RegExp;- }): Locator;+ payload: string|Buffer;+ }) => any): this;/**- * Returns locator to the n-th matching frame. It's zero based, `nth(0)` selects the first frame.- * @deprecated Use [locator.nth(index)](https://playwright.dev/docs/api/class-locator#locator-nth) followed by- * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame) instead.- * @param index+ * Fired when the websocket has an error.*/- nth(index: number): FrameLocator;+ prependListener(event: 'socketerror', listener: (string: string) => any): this;/**- * Returns a [Locator](https://playwright.dev/docs/api/class-locator) object pointing to the same `iframe` as this- * frame locator.- *- * Useful when you have a [FrameLocator](https://playwright.dev/docs/api/class-framelocator) object obtained- * somewhere, and later on would like to interact with the `iframe` element.- *- * For a reverse operation, use- * [locator.contentFrame()](https://playwright.dev/docs/api/class-locator#locator-content-frame).- *- * **Usage**- *- * ```js- * const frameLocator = page.locator('iframe[name="embedded"]').contentFrame();- * // ...- * const locator = frameLocator.owner();- * await expect(locator).toBeVisible();- * ```- *+ * Indicates that the web socket has been closed.*/- owner(): Locator;-}+ isClosed(): boolean;-/**- * Keyboard provides an api for managing a virtual keyboard. The high level api is- * [keyboard.type(text[, options])](https://playwright.dev/docs/api/class-keyboard#keyboard-type), which takes raw- * characters and generates proper `keydown`, `keypress`/`input`, and `keyup` events on your page.- *- * For finer control, you can use [keyboard.down(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-down),- * [keyboard.up(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-up), and- * [keyboard.insertText(text)](https://playwright.dev/docs/api/class-keyboard#keyboard-insert-text) to manually fire- * events as if they were generated from a real keyboard.- *- * An example of holding down `Shift` in order to select and delete some text:- *- * ```js- * await page.keyboard.type('Hello World!');- * await page.keyboard.press('ArrowLeft');- *- * await page.keyboard.down('Shift');- * for (let i = 0; i < ' World'.length; i++)- * await page.keyboard.press('ArrowLeft');- * await page.keyboard.up('Shift');- *- * await page.keyboard.press('Backspace');- * // Result text will end up saying 'Hello!'- * ```- *- * An example of pressing uppercase `A`- *- * ```js- * await page.keyboard.press('Shift+KeyA');- * // or- * await page.keyboard.press('Shift+A');- * ```- *- * An example to trigger select-all with the keyboard- *- * ```js- * await page.keyboard.press('ControlOrMeta+A');- * ```- *- */-export interface Keyboard {/**- * Dispatches a `keydown` event.- *- * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-down-option-key) can specify the intended- * [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character- * to generate the text for. A superset of the- * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-down-option-key) values can be found- * [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:- *- * `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,- * `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,- * etc.- *- * Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,- * `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.- *- * Holding down `Shift` will type the text that corresponds to the- * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-down-option-key) in the upper case.- *- * If [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-down-option-key) is a single character, it is- * case-sensitive, so the values `a` and `A` will generate different respective texts.- *- * If [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-down-option-key) is a modifier key, `Shift`,- * `Meta`, `Control`, or `Alt`, subsequent key presses will be sent with that modifier active. To release the modifier- * key, use [keyboard.up(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-up).- *- * After the key is pressed once, subsequent calls to- * [keyboard.down(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-down) will have- * [repeat](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat) set to true. To release the key,- * use [keyboard.up(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-up).- *- * **NOTE** Modifier keys DO influence `keyboard.down`. Holding down `Shift` will type the text in upper case.- *- * @param key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.+ * Contains the URL of the WebSocket.*/- down(key: string): Promise<void>;+ url(): string;/**- * Dispatches only `input` event, does not emit the `keydown`, `keyup` or `keypress` events.- *- * **Usage**- *- * ```js- * page.keyboard.insertText('嗨');- * ```- *- * **NOTE** Modifier keys DO NOT effect `keyboard.insertText`. Holding down `Shift` will not type the text in upper- * case.- *- * @param text Sets input to the specified text value.+ * Fired when the websocket closes.*/- insertText(text: string): Promise<void>;+ waitForEvent(event: 'close', optionsOrPredicate?: { predicate?: (webSocket: WebSocket) => boolean | Promise<boolean>, timeout?: number } | ((webSocket: WebSocket) => boolean | Promise<boolean>)): Promise<WebSocket>;/**- * **NOTE** In most cases, you should use- * [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press) instead.- *- * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-press-option-key) can specify the intended- * [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character- * to generate the text for. A superset of the- * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-press-option-key) values can be found- * [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:- *- * `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,- * `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,- * etc.- *- * Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,- * `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.- *- * Holding down `Shift` will type the text that corresponds to the- * [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-press-option-key) in the upper case.- *- * If [`key`](https://playwright.dev/docs/api/class-keyboard#keyboard-press-option-key) is a single character, it is- * case-sensitive, so the values `a` and `A` will generate different respective texts.- *- * Shortcuts such as `key: "Control+o"`, `key: "Control++` or `key: "Control+Shift+T"` are supported as well. When- * specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.- *- * **Usage**- *- * ```js- * const page = await browser.newPage();- * await page.goto('https://keycode.info');- * await page.keyboard.press('A');- * await page.screenshot({ path: 'A.png' });- * await page.keyboard.press('ArrowLeft');- * await page.screenshot({ path: 'ArrowLeft.png' });- * await page.keyboard.press('Shift+O');- * await page.screenshot({ path: 'O.png' });- * await browser.close();- * ```- *- * Shortcut for [keyboard.down(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-down) and- * [keyboard.up(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-up).- * @param key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.- * @param options+ * Fired when the websocket receives a frame.*/- press(key: string, options?: {+ waitForEvent(event: 'framereceived', optionsOrPredicate?: { predicate?: (data: {/**- * Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.- */- delay?: number;- }): Promise<void>;-- /**- * **NOTE** In most cases, you should use- * [locator.fill(value[, options])](https://playwright.dev/docs/api/class-locator#locator-fill) instead. You only need- * to press keys one by one if there is special keyboard handling on the page - in this case use- * [locator.pressSequentially(text[, options])](https://playwright.dev/docs/api/class-locator#locator-press-sequentially).- *- * Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text.- *- * To press a special key, like `Control` or `ArrowDown`, use- * [keyboard.press(key[, options])](https://playwright.dev/docs/api/class-keyboard#keyboard-press).- *- * **Usage**- *- * ```js- * await page.keyboard.type('Hello'); // Types instantly- * await page.keyboard.type('World', { delay: 100 }); // Types slower, like a user- * ```- *- * **NOTE** Modifier keys DO NOT effect `keyboard.type`. Holding down `Shift` will not type the text in upper case.- *- * **NOTE** For characters that are not on a US keyboard, only an `input` event will be sent.- *- * @param text A text to type into a focused element.- * @param options+ * frame payload+ */+ payload: string|Buffer;+ }) => boolean | Promise<boolean>, timeout?: number } | ((data: {+ /**+ * frame payload+ */+ payload: string|Buffer;+ }) => boolean | Promise<boolean>)): Promise<{+ /**+ * frame payload+ */+ payload: string|Buffer;+ }>;++ /**+ * Fired when the websocket sends a frame.*/- type(text: string, options?: {+ waitForEvent(event: 'framesent', optionsOrPredicate?: { predicate?: (data: {/**- * Time to wait between key presses in milliseconds. Defaults to 0.+ * frame payload*/- delay?: number;- }): Promise<void>;+ payload: string|Buffer;+ }) => boolean | Promise<boolean>, timeout?: number } | ((data: {+ /**+ * frame payload+ */+ payload: string|Buffer;+ }) => boolean | Promise<boolean>)): Promise<{+ /**+ * frame payload+ */+ payload: string|Buffer;+ }>;/**- * Dispatches a `keyup` event.- * @param key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.+ * Fired when the websocket has an error.*/- up(key: string): Promise<void>;+ waitForEvent(event: 'socketerror', optionsOrPredicate?: { predicate?: (string: string) => boolean | Promise<boolean>, timeout?: number } | ((string: string) => boolean | Promise<boolean>)): Promise<string>;+}/**- * Playwright generates a lot of logs and they are accessible via the pluggable logger sink.+ * Playwright has **experimental** support for Electron automation, exposed as `_electron`. An example of the Electron+ * automation script would be:** ```js- * const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.+ * import { _electron as electron } from 'playwright';** (async () => {- * const browser = await chromium.launch({- * logger: {- * isEnabled: (name, severity) => name === 'api',- * log: (name, severity, message, args) => console.log(`${name} ${message}`)- * }+ * // Launch Electron app.+ * const electronApp = await electron.launch({ args: ['main.js'] });+ *+ * // Evaluation expression in the Electron context.+ * const appPath = await electronApp.evaluate(async ({ app }) => {+ * // This runs in the main Electron process, parameter here is always+ * // the result of the require('electron') in the main app script.+ * return app.getAppPath();* });- * // ...+ * console.log(appPath);+ *+ * // Get the first window that the app opens, wait if necessary.+ * const window = await electronApp.firstWindow();+ * // Print the title.+ * console.log(await window.title());+ * // Capture a screenshot.+ * await window.screenshot({ path: 'intro.png' });+ * // Direct Electron console to Node terminal.+ * window.on('console', console.log);+ * // Click button.+ * await window.click('text=Click me');+ * // Exit app.+ * await electronApp.close();* })();* ```*- */-export interface Logger {- /**- * Determines whether sink is interested in the logger with the given name and severity.- * @param name logger name- * @param severity- */- isEnabled(name: string, severity: "verbose"|"info"|"warning"|"error"): boolean;-- /**- * @param name logger name- * @param severity- * @param message log message format- * @param args message arguments- * @param hints optional formatting hints- */- log(name: string, severity: "verbose"|"info"|"warning"|"error", message: string|Error, args: ReadonlyArray<Object>, hints: {- /**- * Optional preferred logger color.- */- color?: string;- }): void;-}--/**- * The Mouse class operates in main-frame CSS pixels relative to the top-left corner of the viewport.+ * **Supported Electron versions are:**+ * - v12.2.0++ * - v13.4.0++ * - v14+*- * **NOTE** If you want to debug where the mouse moved, you can use the [Trace viewer](https://playwright.dev/docs/trace-viewer-intro) or- * [Playwright Inspector](https://playwright.dev/docs/running-tests). A red dot showing the location of the mouse will be shown for every- * mouse action.+ * **Known issues:***- * Every `page` object has its own Mouse, accessible with- * [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse).+ * If you are not able to launch Electron and it will end up in timeouts during launch, try the following:+ * - Ensure that `nodeCliInspect`+ * ([FuseV1Options.EnableNodeCliInspectArguments](https://www.electronjs.org/docs/latest/tutorial/fuses#nodecliinspect))+ * fuse is **not** set to `false`.*- * ```js- * // Using ‘page.mouse’ to trace a 100x100 square.- * await page.mouse.move(0, 0);- * await page.mouse.down();- * await page.mouse.move(0, 100);- * await page.mouse.move(100, 100);- * await page.mouse.move(100, 0);- * await page.mouse.move(0, 0);- * await page.mouse.up();- * ```+ * **Migrating from v1.59***- */-export interface Mouse {- /**- * Shortcut for [mouse.move(x, y[, options])](https://playwright.dev/docs/api/class-mouse#mouse-move),- * [mouse.down([options])](https://playwright.dev/docs/api/class-mouse#mouse-down),- * [mouse.up([options])](https://playwright.dev/docs/api/class-mouse#mouse-up).- * @param x X coordinate relative to the main frame's viewport in CSS pixels.- * @param y Y coordinate relative to the main frame's viewport in CSS pixels.- * @param options- */- click(x: number, y: number, options?: {- /**- * Defaults to `left`.- */- button?: "left"|"right"|"middle";-- /**- * defaults to 1. See [UIEvent.detail].- */- clickCount?: number;-- /**- * Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.- */- delay?: number;- }): Promise<void>;-+ * A number of launch options have been removed after v1.59. See below for alternatives.+ * - `recordHar` - use+ * [tracing.startHar(path[, options])](https://playwright.dev/docs/api/class-tracing#tracing-start-har).+ *+ * ```js+ * const electronApp = await electron.launch({ args: ['main.js'] });+ * await electronApp.context().tracing.startHar('network.har');+ * // ... drive the app ...+ * await electronApp.context().tracing.stopHar();+ * await electronApp.close();+ * ```+ *+ * - `recordVideo` - use+ * [screencast.start([options])](https://playwright.dev/docs/api/class-screencast#screencast-start) on each+ * window.+ *+ * ```js+ * const electronApp = await electron.launch({ args: ['main.js'] });+ * const window = await electronApp.firstWindow();+ * await window.screencast.start({ path: 'video.webm' });+ * // ... drive the window ...+ * await window.screencast.stop();+ * await electronApp.close();+ * ```+ *+ * - `colorScheme` - use+ * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) on each window.+ *+ * ```js+ * const window = await electronApp.firstWindow();+ * await window.emulateMedia({ colorScheme: 'dark' });+ * ```+ *+ * - `extraHTTPHeaders` - use+ * [browserContext.setExtraHTTPHeaders(headers)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-extra-http-headers).+ *+ * ```js+ * await electronApp.context().setExtraHTTPHeaders({ 'X-My-Header': 'value' });+ * ```+ *+ * - `geolocation` - use+ * [browserContext.setGeolocation(geolocation)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-geolocation).+ *+ * ```js+ * await electronApp.context().setGeolocation({ latitude: 48.858455, longitude: 2.294474 });+ * ```+ *+ * - `httpCredentials` - use+ * [browserContext.setHTTPCredentials(httpCredentials)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-http-credentials).+ *+ * ```js+ * await electronApp.context().setHTTPCredentials({ username: 'user', password: 'pass' });+ * ```+ *+ * - `offline` - use+ * [browserContext.setOffline(offline)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-offline).+ *+ * ```js+ * await electronApp.context().setOffline(true);+ * ```+ *+ * - `bypassCSP` - disable CSP at the `BrowserWindow` level via Electron's+ * [web preferences](https://www.electronjs.org/docs/latest/api/structures/web-preferences). Note that+ * `webSecurity: false` also disables CORS and the Same-Origin Policy.+ *+ * ```js+ * const win = new BrowserWindow({+ * webPreferences: {+ * webSecurity: false,+ * },+ * });+ * ```+ *+ * - `ignoreHTTPSErrors`+ *+ * There are several ways to relax HTTPS checks in Electron. Pick the one that matches the scope you need.+ *+ * Per-window, allow mixed content through+ * [web preferences](https://www.electronjs.org/docs/latest/api/structures/web-preferences):+ *+ * ```js+ * const win = new BrowserWindow({+ * webPreferences: {+ * allowRunningInsecureContent: true,+ * },+ * });+ * ```+ *+ * Process-wide, ignore certificate errors via Chromium command-line switches (must run before the `ready` event):+ *+ * ```js+ * const { app } = require('electron');+ * app.commandLine.appendSwitch('ignore-certificate-errors');+ * // Optional: also ignore localhost certificate errors when testing on an IP.+ * app.commandLine.appendSwitch('allow-insecure-localhost', 'true');+ * ```+ *+ * Per-request, accept the certificate manually via the+ * [`certificate-error`](https://www.electronjs.org/docs/latest/api/app#event-certificate-error) event:+ *+ * ```js+ * app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {+ * event.preventDefault();+ * callback(true);+ * });+ * ```+ *+ * - `timezoneId` - set an environment variable at the very top of the main file, before any other logic or Chromium+ * windows are initialized.+ *+ * ```js+ * // main.js+ * process.env.TZ = 'Europe/London';+ *+ * const { app } = require('electron');+ * // ... rest of your app logic+ * ```+ *+ */+export interface Electron {/**- * Shortcut for [mouse.move(x, y[, options])](https://playwright.dev/docs/api/class-mouse#mouse-move),- * [mouse.down([options])](https://playwright.dev/docs/api/class-mouse#mouse-down),- * [mouse.up([options])](https://playwright.dev/docs/api/class-mouse#mouse-up),- * [mouse.down([options])](https://playwright.dev/docs/api/class-mouse#mouse-down) and- * [mouse.up([options])](https://playwright.dev/docs/api/class-mouse#mouse-up).- * @param x X coordinate relative to the main frame's viewport in CSS pixels.- * @param y Y coordinate relative to the main frame's viewport in CSS pixels.+ * Launches electron application specified with the+ * [`executablePath`](https://playwright.dev/docs/api/class-electron#electron-launch-option-executable-path).* @param options*/- dblclick(x: number, y: number, options?: {- /**- * Defaults to `left`.- */- button?: "left"|"right"|"middle";-+ launch(options?: {/**- * Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.+ * Additional arguments to pass to the application when launching. You typically pass the main script name here.*/- delay?: number;- }): Promise<void>;+ args?: Array<string>;- /**- * Dispatches a `mousedown` event.- * @param options- */- down(options?: {/**- * Defaults to `left`.+ * Enable Chromium sandboxing. Defaults to `false`.*/- button?: "left"|"right"|"middle";+ chromiumSandbox?: boolean;/**- * defaults to 1. See [UIEvent.detail].+ * Current working directory to launch application from.*/- clickCount?: number;- }): Promise<void>;+ cwd?: string;- /**- * Dispatches a `mousemove` event.- * @param x X coordinate relative to the main frame's viewport in CSS pixels.- * @param y Y coordinate relative to the main frame's viewport in CSS pixels.- * @param options- */- move(x: number, y: number, options?: {/**- * Defaults to 1. Sends `n` interpolated `mousemove` events to represent travel between Playwright's current cursor- * position and the provided destination. When set to 1, emits a single `mousemove` event at the destination location.+ * Specifies environment variables that will be visible to Electron. Defaults to `process.env`.*/- steps?: number;- }): Promise<void>;+ env?: { [key: string]: string; };- /**- * Dispatches a `mouseup` event.- * @param options- */- up(options?: {/**- * Defaults to `left`.+ * Launches given Electron application. If not specified, launches the default Electron executable installed in this+ * package, located at `node_modules/.bin/electron`.*/- button?: "left"|"right"|"middle";+ executablePath?: string;/**- * defaults to 1. See [UIEvent.detail].+ * Maximum time in milliseconds to wait for the application to start. Defaults to `30000` (30 seconds). Pass `0` to+ * disable timeout.*/- clickCount?: number;- }): Promise<void>;-- /**- * Dispatches a `wheel` event. This method is usually used to manually scroll the page. See- * [scrolling](https://playwright.dev/docs/input#scrolling) for alternative ways to scroll.- *- * **NOTE** Wheel events may cause scrolling if they are not handled, and this method does not wait for the scrolling- * to finish before returning.- *- * @param deltaX Pixels to scroll horizontally.- * @param deltaY Pixels to scroll vertically.- */- wheel(deltaX: number, deltaY: number): Promise<void>;+ timeout?: number;+ }): Promise<ElectronApplication>;}/**- * This object can be used to launch or connect to Chromium, returning instances of- * [Browser](https://playwright.dev/docs/api/class-browser).- */-export const chromium: BrowserType;--/**- * This object can be used to launch or connect to Firefox, returning instances of- * [Browser](https://playwright.dev/docs/api/class-browser).- */-export const firefox: BrowserType;--/**- * Exposes API that can be used for the Web API testing.- */-export const request: APIRequest;--/**- * Selectors can be used to install custom selector engines. See [extensibility](https://playwright.dev/docs/extensibility) for more- * information.- */-export const selectors: Selectors;--/**- * This object can be used to launch or connect to WebKit, returning instances of- * [Browser](https://playwright.dev/docs/api/class-browser).- */-export const webkit: BrowserType;--/**- * Whenever the page sends a request for a network resource the following sequence of events are emitted by- * [Page](https://playwright.dev/docs/api/class-page):- * - [page.on('request')](https://playwright.dev/docs/api/class-page#page-event-request) emitted when the request is- * issued by the page.- * - [page.on('response')](https://playwright.dev/docs/api/class-page#page-event-response) emitted when/if the- * response status and headers are received for the request.- * - [page.on('requestfinished')](https://playwright.dev/docs/api/class-page#page-event-request-finished) emitted- * when the response body is downloaded and the request is complete.+ * Playwright has **experimental** support for Android automation. This includes Chrome for Android and Android+ * WebView.*- * If request fails at some point, then instead of `'requestfinished'` event (and possibly instead of 'response'- * event), the [page.on('requestfailed')](https://playwright.dev/docs/api/class-page#page-event-request-failed) event- * is emitted.+ * *Requirements*+ * - Android device or AVD Emulator.+ * - [ADB daemon](https://developer.android.com/studio/command-line/adb) running and authenticated with your device.+ * Typically running `adb devices` is all you need to do.+ * - [`Chrome 87`](https://play.google.com/store/apps/details?id=com.android.chrome) or newer installed on the+ * device+ * - "Enable command line on non-rooted devices" enabled in `chrome://flags`.*- * **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request- * will complete with `'requestfinished'` event.+ * *Known limitations*+ * - Raw USB operation is not yet supported, so you need ADB.+ * - Device needs to be awake to produce screenshots. Enabling "Stay awake" developer mode will help.+ * - We didn't run all the tests against the device, so not everything works.*- * If request gets a 'redirect' response, the request is successfully finished with the `requestfinished` event, and a- * new request is issued to a redirected url.- */-export interface Request {- /**- * An object with all the request HTTP headers associated with this request. The header names are lower-cased.- */- allHeaders(): Promise<{ [key: string]: string; }>;-- /**- * Returns the [Response](https://playwright.dev/docs/api/class-response) object if the response has already been- * received, `null` otherwise.- *- * Unlike [request.response()](https://playwright.dev/docs/api/class-request#request-response), this method does not- * wait for the response to arrive. It returns immediately with the response object if the response has been received,- * or `null` if the response has not been received yet.- */- existingResponse(): null|Response;-- /**- * The method returns `null` unless this request has failed, as reported by `requestfailed` event.- *- * **Usage**- *- * Example of logging of all the failed requests:- *- * ```js- * page.on('requestfailed', request => {- * console.log(request.url() + ' ' + request.failure().errorText);- * });- * ```- *- */- failure(): null|{- /**- * Human-readable error message, e.g. `'net::ERR_FAILED'`.- */- errorText: string;- };-- /**- * Returns the [Frame](https://playwright.dev/docs/api/class-frame) that initiated this request.- *- * **Usage**- *- * ```js- * const frameUrl = request.frame().url();- * ```- *- * **Details**- *- * Note that in some cases the frame is not available, and this method will throw.- * - When request originates in the Service Worker. You can use `request.serviceWorker()` to check that.- * - When navigation request is issued before the corresponding frame is created. You can use- * [request.isNavigationRequest()](https://playwright.dev/docs/api/class-request#request-is-navigation-request) to- * check that.- *- * Here is an example that handles all the cases:- *- * ```js- * if (request.serviceWorker())- * console.log(`request ${request.url()} from a service worker`);- * else if (request.isNavigationRequest())- * console.log(`request ${request.url()} is a navigation request`);- * else- * console.log(`request ${request.url()} from a frame ${request.frame().url()}`);- * ```- *- */- frame(): Frame;-- /**- * An object with the request HTTP headers. The header names are lower-cased. Note that this method does not return- * security-related headers, including cookie-related ones. You can use- * [request.allHeaders()](https://playwright.dev/docs/api/class-request#request-all-headers) for complete list of- * headers that include `cookie` information.- */- headers(): { [key: string]: string; };-+ * *How to run*+ *+ * An example of the Android automation script would be:+ *+ * ```js+ * const { _android: android } = require('playwright');+ *+ * (async () => {+ * // Connect to the device.+ * const [device] = await android.devices();+ * console.log(`Model: ${device.model()}`);+ * console.log(`Serial: ${device.serial()}`);+ * // Take screenshot of the whole device.+ * await device.screenshot({ path: 'device.png' });+ *+ * {+ * // --------------------- WebView -----------------------+ *+ * // Launch an application with WebView.+ * await device.shell('am force-stop org.chromium.webview_shell');+ * await device.shell('am start org.chromium.webview_shell/.WebViewBrowserActivity');+ * // Get the WebView.+ * const webview = await device.webView({ pkg: 'org.chromium.webview_shell' });+ *+ * // Fill the input box.+ * await device.fill({+ * res: 'org.chromium.webview_shell:id/url_field',+ * }, 'github.com/microsoft/playwright');+ * await device.press({+ * res: 'org.chromium.webview_shell:id/url_field',+ * }, 'Enter');+ *+ * // Work with WebView's page as usual.+ * const page = await webview.page();+ * await page.waitForNavigation({ url: /.*microsoft\/playwright.*\/ });+ * console.log(await page.title());+ * }+ *+ * {+ * // --------------------- Browser -----------------------+ *+ * // Launch Chrome browser.+ * await device.shell('am force-stop com.android.chrome');+ * const context = await device.launchBrowser();+ *+ * // Use BrowserContext as usual.+ * const page = await context.newPage();+ * await page.goto('https://webkit.org/');+ * console.log(await page.evaluate(() => window.location.href));+ * await page.screenshot({ path: 'page.png' });+ *+ * await context.close();+ * }+ *+ * // Close the device.+ * await device.close();+ * })();+ * ```+ *+ */+export interface Android {/**- * An array with all the request HTTP headers associated with this request. Unlike- * [request.allHeaders()](https://playwright.dev/docs/api/class-request#request-all-headers), header names are NOT- * lower-cased. Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple times.+ * This methods attaches Playwright to an existing Android device. Use+ * [android.launchServer([options])](https://playwright.dev/docs/api/class-android#android-launch-server) to launch a+ * new Android server instance.+ * @param endpoint A browser websocket endpoint to connect to.+ * @param options*/- headersArray(): Promise<Array<{+ connect(endpoint: string, options?: {/**- * Name of the header.+ * Additional HTTP headers to be sent with web socket connect request. Optional.*/- name: string;+ headers?: { [key: string]: string; };/**- * Value of the header.+ * Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going+ * on. Defaults to `0`.*/- value: string;- }>>;-- /**- * Returns the value of the header matching the name. The name is case-insensitive.- * @param name Name of the header.- */- headerValue(name: string): Promise<null|string>;-- /**- * Whether this request is driving frame's navigation.- *- * Some navigation requests are issued before the corresponding frame is created, and therefore do not have- * [request.frame()](https://playwright.dev/docs/api/class-request#request-frame) available.- */- isNavigationRequest(): boolean;+ slowMo?: number;- /**- * Request's method (GET, POST, etc.)- */- method(): string;+ /**+ * Maximum time in milliseconds to wait for the connection to be established. Defaults to `30000` (30 seconds). Pass+ * `0` to disable timeout.+ */+ timeout?: number;+ }): Promise<AndroidDevice>;/**- * Request's post body, if any.+ * Returns the list of detected Android devices.+ * @param options*/- postData(): null|string;+ devices(options?: {+ /**+ * Optional host to establish ADB server connection. Default to `127.0.0.1`.+ */+ host?: string;- /**- * Request's post body in a binary form, if any.- */- postDataBuffer(): null|Buffer;+ /**+ * Prevents automatic playwright driver installation on attach. Assumes that the drivers have been installed already.+ */+ omitDriverInstall?: boolean;- /**- * Returns parsed request's body for `form-urlencoded` and JSON as a fallback if any.- *- * When the response is `application/x-www-form-urlencoded` then a key/value object of the values will be returned.- * Otherwise it will be parsed as JSON.- */- postDataJSON(): null|Serializable;+ /**+ * Optional port to establish ADB server connection. Default to `5037`.+ */+ port?: number;+ }): Promise<Array<AndroidDevice>>;/**- * Request that was redirected by the server to this one, if any.- *- * When the server responds with a redirect, Playwright creates a new- * [Request](https://playwright.dev/docs/api/class-request) object. The two requests are connected by- * `redirectedFrom()` and `redirectedTo()` methods. When multiple server redirects has happened, it is possible to- * construct the whole redirect chain by repeatedly calling `redirectedFrom()`.+ * Launches Playwright Android server that clients can connect to. See the following example:** **Usage***- * For example, if the website `http://example.com` redirects to `https://example.com`:+ * Server Side:** ```js- * const response = await page.goto('http://example.com');- * console.log(response.request().redirectedFrom().url()); // 'http://example.com'- * ```- *- * If the website `https://google.com` has no redirects:+ * const { _android } = require('playwright');*- * ```js- * const response = await page.goto('https://google.com');- * console.log(response.request().redirectedFrom()); // null+ * (async () => {+ * const browserServer = await _android.launchServer({+ * // If you have multiple devices connected and want to use a specific one.+ * // deviceSerialNumber: '<deviceSerialNumber>',+ * });+ * const wsEndpoint = browserServer.wsEndpoint();+ * console.log(wsEndpoint);+ * })();* ```*- */- redirectedFrom(): null|Request;-- /**- * New request issued by the browser if the server responded with redirect.- *- * **Usage**- *- * This method is the opposite of- * [request.redirectedFrom()](https://playwright.dev/docs/api/class-request#request-redirected-from):+ * Client Side:** ```js- * console.log(request.redirectedFrom().redirectedTo() === request); // true- * ```- *- */- redirectedTo(): null|Request;-- /**- * Contains the request's resource type as it was perceived by the rendering engine. ResourceType will be one of the- * following: `document`, `stylesheet`, `image`, `media`, `font`, `script`, `texttrack`, `xhr`, `fetch`,- * `eventsource`, `websocket`, `manifest`, `other`.- */- resourceType(): string;-- /**- * Returns the matching [Response](https://playwright.dev/docs/api/class-response) object, or `null` if the response- * was not received due to error.- */- response(): Promise<null|Response>;-- /**- * The Service [Worker](https://playwright.dev/docs/api/class-worker) that is performing the request.- *- * **Details**+ * const { _android } = require('playwright');*- * This method is Chromium only. It's safe to call when using other browsers, but it will always be `null`.+ * (async () => {+ * const device = await _android.connect('<wsEndpoint>');*- * Requests originated in a Service Worker do not have a- * [request.frame()](https://playwright.dev/docs/api/class-request#request-frame) available.- */- serviceWorker(): null|Worker;-- /**- * Returns resource size information for given request.- */- sizes(): Promise<{- /**- * Size of the request body (POST data payload) in bytes. Set to 0 if there was no body.- */- requestBodySize: number;-- /**- * Total number of bytes from the start of the HTTP request message until (and including) the double CRLF before the- * body.- */- requestHeadersSize: number;-- /**- * Size of the received response body (encoded) in bytes.- */- responseBodySize: number;-- /**- * Total number of bytes from the start of the HTTP response message until (and including) the double CRLF before the- * body.- */- responseHeadersSize: number;- }>;-- /**- * Returns resource timing information for given request. Most of the timing values become available upon the- * response, `responseEnd` becomes available when request finishes. Find more information at- * [Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming).+ * console.log(device.model());+ * console.log(device.serial());+ * await device.shell('am force-stop com.android.chrome');+ * const context = await device.launchBrowser();*- * **Usage**+ * const page = await context.newPage();+ * await page.goto('https://webkit.org/');+ * console.log(await page.evaluate(() => window.location.href));+ * await page.screenshot({ path: 'page-chrome-1.png' });*- * ```js- * const requestFinishedPromise = page.waitForEvent('requestfinished');- * await page.goto('http://example.com');- * const request = await requestFinishedPromise;- * console.log(request.timing());+ * await context.close();+ * })();* ```*+ * @param options*/- timing(): {- /**- * Request start time in milliseconds elapsed since January 1, 1970 00:00:00 UTC- */- startTime: number;-- /**- * Time immediately before the browser starts the domain name lookup for the resource. The value is given in- * milliseconds relative to `startTime`, -1 if not available.- */- domainLookupStart: number;-+ launchServer(options?: {/**- * Time immediately after the browser starts the domain name lookup for the resource. The value is given in- * milliseconds relative to `startTime`, -1 if not available.+ * Optional host to establish ADB server connection. Default to `127.0.0.1`.*/- domainLookupEnd: number;+ adbHost?: string;/**- * Time immediately before the user agent starts establishing the connection to the server to retrieve the resource.- * The value is given in milliseconds relative to `startTime`, -1 if not available.+ * Optional port to establish ADB server connection. Default to `5037`.*/- connectStart: number;+ adbPort?: number;/**- * Time immediately before the browser starts the handshake process to secure the current connection. The value is- * given in milliseconds relative to `startTime`, -1 if not available.+ * Optional device serial number to launch the browser on. If not specified, it will throw if multiple devices are+ * connected.*/- secureConnectionStart: number;+ deviceSerialNumber?: string;/**- * Time immediately before the user agent starts establishing the connection to the server to retrieve the resource.- * The value is given in milliseconds relative to `startTime`, -1 if not available.+ * Host to use for the web socket. It is optional and defaults to `localhost`, accepting connections only from the+ * loopback interface. Pass an explicit address (e.g. `0.0.0.0`) to accept connections from the network — be aware+ * this exposes the device RPC to anything that can reach the listening port.*/- connectEnd: number;+ host?: string;/**- * Time immediately before the browser starts requesting the resource from the server, cache, or local resource. The- * value is given in milliseconds relative to `startTime`, -1 if not available.+ * Prevents automatic playwright driver installation on attach. Assumes that the drivers have been installed already.*/- requestStart: number;+ omitDriverInstall?: boolean;/**- * Time immediately after the browser receives the first byte of the response from the server, cache, or local- * resource. The value is given in milliseconds relative to `startTime`, -1 if not available.+ * Port to use for the web socket. Defaults to 0 that picks any available port.*/- responseStart: number;+ port?: number;/**- * Time immediately after the browser receives the last byte of the resource or immediately before the transport- * connection is closed, whichever comes first. The value is given in milliseconds relative to `startTime`, -1 if not- * available.+ * Path at which to serve the Android Server. For security, this defaults to an unguessable string.+ *+ * **NOTE** Any process or web page (including those running in Playwright) with knowledge of the `wsPath` can take+ * control of the OS user. For this reason, you should use an unguessable token when using this option.+ **/- responseEnd: number;- };+ wsPath?: string;+ }): Promise<BrowserServer>;/**- * URL of the request.+ * This setting will change the default maximum time for all the methods accepting+ * [`timeout`](https://playwright.dev/docs/api/class-android#android-set-default-timeout-option-timeout) option.+ * @param timeout Maximum time in milliseconds*/- url(): string;+ setDefaultTimeout(timeout: number): void;}/**- * [Response](https://playwright.dev/docs/api/class-response) class represents responses which are received by page.+ * [AndroidDevice](https://playwright.dev/docs/api/class-androiddevice) represents a connected device, either real+ * hardware or emulated. Devices can be obtained using+ * [android.devices([options])](https://playwright.dev/docs/api/class-android#android-devices).*/-export interface Response {- /**- * An object with all the response HTTP headers associated with this response.- */- allHeaders(): Promise<{ [key: string]: string; }>;-- /**- * Returns the buffer with response body.- */- body(): Promise<Buffer>;-- /**- * Waits for this response to finish, returns always `null`.- */- finished(): Promise<null|Error>;-- /**- * Returns the [Frame](https://playwright.dev/docs/api/class-frame) that initiated this response.- */- frame(): Frame;-- /**- * Indicates whether this Response was fulfilled by a Service Worker's Fetch Handler (i.e. via- * [FetchEvent.respondWith](https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent/respondWith)).- */- fromServiceWorker(): boolean;-- /**- * An object with the response HTTP headers. The header names are lower-cased. Note that this method does not return- * security-related headers, including cookie-related ones. You can use- * [response.allHeaders()](https://playwright.dev/docs/api/class-response#response-all-headers) for complete list of- * headers that include `cookie` information.- */- headers(): { [key: string]: string; };-- /**- * An array with all the request HTTP headers associated with this response. Unlike- * [response.allHeaders()](https://playwright.dev/docs/api/class-response#response-all-headers), header names are NOT- * lower-cased. Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple times.- */- headersArray(): Promise<Array<{- /**- * Name of the header.- */- name: string;-- /**- * Value of the header.- */- value: string;- }>>;-+export interface AndroidDevice {/**- * Returns the value of the header matching the name. The name is case-insensitive. If multiple headers have the same- * name (except `set-cookie`), they are returned as a list separated by `, `. For `set-cookie`, the `\n` separator is- * used. If no headers are found, `null` is returned.- * @param name Name of the header.+ * Emitted when the device connection gets closed.*/- headerValue(name: string): Promise<null|string>;+ on(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;/**- * Returns all values of the headers matching the name, for example `set-cookie`. The name is case-insensitive.- * @param name Name of the header.+ * Emitted when a new WebView instance is detected.*/- headerValues(name: string): Promise<Array<string>>;+ on(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;/**- * Returns the http version used by the response.+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.*/- httpVersion(): Promise<string>;+ once(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;/**- * Returns the JSON representation of response body.- *- * This method will throw if the response body is not parsable via `JSON.parse`.+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.*/- json(): Promise<Serializable>;+ once(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;/**- * Contains a boolean stating whether the response was successful (status in the range 200-299) or not.+ * Emitted when the device connection gets closed.*/- ok(): boolean;+ addListener(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;/**- * Returns the matching [Request](https://playwright.dev/docs/api/class-request) object.+ * Emitted when a new WebView instance is detected.*/- request(): Request;+ addListener(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;/**- * Returns SSL and other security information.+ * Removes an event listener added by `on` or `addListener`.*/- securityDetails(): Promise<null|{- /**- * Common Name component of the Issuer field. from the certificate. This should only be used for informational- * purposes. Optional.- */- issuer?: string;-- /**- * The specific TLS protocol used. (e.g. `TLS 1.3`). Optional.- */- protocol?: string;-- /**- * Common Name component of the Subject field from the certificate. This should only be used for informational- * purposes. Optional.- */- subjectName?: string;-- /**- * Unix timestamp (in seconds) specifying when this cert becomes valid. Optional.- */- validFrom?: number;-- /**- * Unix timestamp (in seconds) specifying when this cert becomes invalid. Optional.- */- validTo?: number;- }>;+ removeListener(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;/**- * Returns the IP address and port of the server.+ * Removes an event listener added by `on` or `addListener`.*/- serverAddr(): Promise<null|{- /**- * IPv4 or IPV6 address of the server.- */- ipAddress: string;-- port: number;- }>;+ removeListener(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;/**- * Contains the status code of the response (e.g., 200 for a success).+ * Removes an event listener added by `on` or `addListener`.*/- status(): number;+ off(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;/**- * Contains the status text of the response (e.g. usually an "OK" for a success).+ * Removes an event listener added by `on` or `addListener`.*/- statusText(): string;+ off(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;/**- * Returns the text representation of response body.+ * Emitted when the device connection gets closed.*/- text(): Promise<string>;+ prependListener(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;/**- * Contains the URL of the response.+ * Emitted when a new WebView instance is detected.*/- url(): string;-}+ prependListener(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;-/**- * Whenever a network route is set up with- * [page.route(url, handler[, options])](https://playwright.dev/docs/api/class-page#page-route) or- * [browserContext.route(url, handler[, options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-route),- * the `Route` object allows to handle the route.- *- * Learn more about [networking](https://playwright.dev/docs/network).- */-export interface Route {/**- * Aborts the route's request.- * @param errorCode Optional error code. Defaults to `failed`, could be one of the following:- * - `'aborted'` - An operation was aborted (due to user action)- * - `'accessdenied'` - Permission to access a resource, other than the network, was denied- * - `'addressunreachable'` - The IP address is unreachable. This usually means that there is no route to the- * specified host or network.- * - `'blockedbyclient'` - The client chose to block the request.- * - `'blockedbyresponse'` - The request failed because the response was delivered along with requirements which are- * not met ('X-Frame-Options' and 'Content-Security-Policy' ancestor checks, for instance).- * - `'connectionaborted'` - A connection timed out as a result of not receiving an ACK for data sent.- * - `'connectionclosed'` - A connection was closed (corresponding to a TCP FIN).- * - `'connectionfailed'` - A connection attempt failed.- * - `'connectionrefused'` - A connection attempt was refused.- * - `'connectionreset'` - A connection was reset (corresponding to a TCP RST).- * - `'internetdisconnected'` - The Internet connection has been lost.- * - `'namenotresolved'` - The host name could not be resolved.- * - `'timedout'` - An operation timed out.- * - `'failed'` - A generic failure occurred.+ * Disconnects from the device.*/- abort(errorCode?: string): Promise<void>;+ close(): Promise<void>;/**- * Sends route's request to the network with optional overrides.- *- * **Usage**- *- * ```js- * await page.route('**\/*', async (route, request) => {- * // Override headers- * const headers = {- * ...request.headers(),- * foo: 'foo-value', // set "foo" header- * bar: undefined, // remove "bar" header- * };- * await route.continue({ headers });- * });- * ```- *- * **Details**- *- * The [`headers`](https://playwright.dev/docs/api/class-route#route-continue-option-headers) option applies to both- * the routed request and any redirects it initiates. However,- * [`url`](https://playwright.dev/docs/api/class-route#route-continue-option-url),- * [`method`](https://playwright.dev/docs/api/class-route#route-continue-option-method), and- * [`postData`](https://playwright.dev/docs/api/class-route#route-continue-option-post-data) only apply to the- * original request and are not carried over to redirected requests.- *- * [route.continue([options])](https://playwright.dev/docs/api/class-route#route-continue) will immediately send the- * request to the network, other matching handlers won't be invoked. Use- * [route.fallback([options])](https://playwright.dev/docs/api/class-route#route-fallback) If you want next matching- * handler in the chain to be invoked.- *- * **NOTE** Some request headers are **forbidden** and cannot be overridden (for example, `Cookie`, `Host`,- * `Content-Length` and others, see- * [this MDN page](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_request_header) for full list). If an- * override is provided for a forbidden header, it will be ignored and the original request header will be used.- *- * To set custom cookies, use- * [browserContext.addCookies(cookies)](https://playwright.dev/docs/api/class-browsercontext#browser-context-add-cookies).- *- * @param options- */- continue(options?: {- /**- * If set changes the request HTTP headers. Header values will be converted to a string.- */- headers?: { [key: string]: string; };+ * Drags the widget defined by+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-drag-option-selector) towards+ * [`dest`](https://playwright.dev/docs/api/class-androiddevice#android-device-drag-option-dest) point.+ * @param selector Selector to drag.+ * @param dest Point to drag to.+ * @param options+ */+ drag(selector: AndroidSelector, dest: {+ x: number;+ y: number;+ }, options?: {/**- * If set changes the request method (e.g. GET or POST).+ * Optional speed of the drag in pixels per second.*/- method?: string;+ speed?: number;/**- * If set changes the post data of request.+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.*/- postData?: string|Buffer|Serializable;+ timeout?: number;+ }): Promise<void>;+ /**+ * Fills the specific+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-fill-option-selector) input box+ * with [`text`](https://playwright.dev/docs/api/class-androiddevice#android-device-fill-option-text).+ * @param selector Selector to fill.+ * @param text Text to be filled in the input box.+ * @param options+ */+ fill(selector: AndroidSelector, text: string, options?: {/**- * If set changes the request URL. New URL must have same protocol as original one.+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.*/- url?: string;+ timeout?: number;}): Promise<void>;/**- * Continues route's request with optional overrides. The method is similar to- * [route.continue([options])](https://playwright.dev/docs/api/class-route#route-continue) with the difference that- * other matching handlers will be invoked before sending the request.- *- * **Usage**- *- * When several routes match the given pattern, they run in the order opposite to their registration. That way the- * last registered route can always override all the previous ones. In the example below, request will be handled by- * the bottom-most handler first, then it'll fall back to the previous one and in the end will be aborted by the first- * registered route.- *- * ```js- * await page.route('**\/*', async route => {- * // Runs last.- * await route.abort();- * });- * await page.route('**\/*', async route => {- * // Runs second.- * await route.fallback();- * });- * await page.route('**\/*', async route => {- * // Runs first.- * await route.fallback();- * });- * ```- *- * Registering multiple routes is useful when you want separate handlers to handle different kinds of requests, for- * example API calls vs page resources or GET requests vs POST requests as in the example below.- *- * ```js- * // Handle GET requests.- * await page.route('**\/*', async route => {- * if (route.request().method() !== 'GET') {- * await route.fallback();- * return;- * }- * // Handling GET only.- * // ...- * });- *- * // Handle POST requests.- * await page.route('**\/*', async route => {- * if (route.request().method() !== 'POST') {- * await route.fallback();- * return;- * }- * // Handling POST only.- * // ...- * });- * ```- *- * One can also modify request while falling back to the subsequent handler, that way intermediate route handler can- * modify url, method, headers and postData of the request.- *- * ```js- * await page.route('**\/*', async (route, request) => {- * // Override headers- * const headers = {- * ...request.headers(),- * foo: 'foo-value', // set "foo" header- * bar: undefined, // remove "bar" header- * };- * await route.fallback({ headers });- * });- * ```- *- * Use [route.continue([options])](https://playwright.dev/docs/api/class-route#route-continue) to immediately send the- * request to the network, other matching handlers won't be invoked in that case.+ * Flings the widget defined by+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-fling-option-selector) in the+ * specified [`direction`](https://playwright.dev/docs/api/class-androiddevice#android-device-fling-option-direction).+ * @param selector Selector to fling.+ * @param direction Fling direction.* @param options*/- fallback(options?: {+ fling(selector: AndroidSelector, direction: "down"|"up"|"left"|"right", options?: {/**- * If set changes the request HTTP headers. Header values will be converted to a string.+ * Optional speed of the fling in pixels per second.*/- headers?: { [key: string]: string; };+ speed?: number;/**- * If set changes the request method (e.g. GET or POST).+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.*/- method?: string;+ timeout?: number;+ }): Promise<void>;- /**- * If set changes the post data of request.- */- postData?: string|Buffer|Serializable;+ /**+ * Returns information about a widget defined by+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-info-option-selector).+ * @param selector Selector to return information about.+ */+ info(selector: AndroidSelector): Promise<AndroidElementInfo>;+ /**+ * Installs an apk on the device.+ * @param file Either a path to the apk file, or apk file content.+ * @param options+ */+ installApk(file: string|Buffer, options?: {/**- * If set changes the request URL. New URL must have same protocol as original one. Changing the URL won't affect the- * route matching, all the routes are matched using the original request URL.+ * Optional arguments to pass to the `shell:cmd package install` call. Defaults to `-r -t -S`.*/- url?: string;+ args?: Array<string>;}): Promise<void>;/**- * Performs the request and fetches result without fulfilling it, so that the response could be modified and then- * fulfilled.- *- * **Usage**- *- * ```js- * await page.route('https://dog.ceo/api/breeds/list/all', async route => {- * const response = await route.fetch();- * const json = await response.json();- * json.message['big_red_dog'] = [];- * await route.fulfill({ response, json });- * });- * ```- *- * **Details**- *- * Note that [`headers`](https://playwright.dev/docs/api/class-route#route-fetch-option-headers) option will apply to- * the fetched request as well as any redirects initiated by it. If you want to only apply- * [`headers`](https://playwright.dev/docs/api/class-route#route-fetch-option-headers) to the original request, but- * not to redirects, look into [route.continue([options])](https://playwright.dev/docs/api/class-route#route-continue)- * instead.+ * Launches Chrome browser on the device, and returns its persistent context.* @param options*/- fetch(options?: {+ launchBrowser(options?: {/**- * If set changes the request HTTP headers. Header values will be converted to a string.+ * Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.*/- headers?: { [key: string]: string; };+ acceptDownloads?: boolean;/**- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.+ * **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality.+ *+ * Additional arguments to pass to the browser instance. The list of Chromium flags can be found+ * [here](https://peter.sh/experiments/chromium-command-line-switches/).*/- maxRedirects?: number;+ args?: Array<string>;/**- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.+ * When using [page.goto(url[, options])](https://playwright.dev/docs/api/class-page#page-goto),+ * [page.route(url, handler[, options])](https://playwright.dev/docs/api/class-page#page-route),+ * [page.waitForURL(url[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-url),+ * [page.waitForRequest(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-request),+ * or+ * [page.waitForResponse(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-response)+ * it takes the base URL in consideration by using the+ * [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL.+ * Unset by default. Examples:+ * - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`+ * - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in+ * `http://localhost:3000/foo/bar.html`+ * - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in+ * `http://localhost:3000/bar.html`*/- maxRetries?: number;+ baseURL?: string;/**- * If set changes the request method (e.g. GET or POST).+ * Toggles bypassing page's Content-Security-Policy. Defaults to `false`.*/- method?: string;+ bypassCSP?: boolean;/**- * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string- * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`- * header will be set to `application/octet-stream` if not explicitly set.+ * Emulates [prefers-colors-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)+ * media feature, supported values are `'light'` and `'dark'`. See+ * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.+ * Passing `null` resets emulation to system defaults. Defaults to `'light'`.*/- postData?: string|Buffer|Serializable;+ colorScheme?: null|"light"|"dark"|"no-preference";/**- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.+ * Emulates `'prefers-contrast'` media feature, supported values are `'no-preference'`, `'more'`. See+ * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.+ * Passing `null` resets emulation to system defaults. Defaults to `'no-preference'`.*/- timeout?: number;+ contrast?: null|"no-preference"|"more";/**- * If set changes the request URL. New URL must have same protocol as original one.+ * Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about+ * [emulating devices with device scale factor](https://playwright.dev/docs/emulation#devices).*/- url?: string;- }): Promise<APIResponse>;+ deviceScaleFactor?: number;++ /**+ * An object containing additional HTTP headers to be sent with every request. Defaults to none.+ */+ extraHTTPHeaders?: { [key: string]: string; };++ /**+ * Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See+ * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.+ * Passing `null` resets emulation to system defaults. Defaults to `'none'`.+ */+ forcedColors?: null|"active"|"none";++ geolocation?: {+ /**+ * Latitude between -90 and 90.+ */+ latitude: number;++ /**+ * Longitude between -180 and 180.+ */+ longitude: number;++ /**+ * Non-negative accuracy value. Defaults to `0`.+ */+ accuracy?: number;+ };- /**- * Fulfills route's request with given response.- *- * **Usage**- *- * An example of fulfilling all requests with 404 responses:- *- * ```js- * await page.route('**\/*', async route => {- * await route.fulfill({- * status: 404,- * contentType: 'text/plain',- * body: 'Not Found!'- * });- * });- * ```- *- * An example of serving static file:- *- * ```js- * await page.route('**\/xhr_endpoint', route => route.fulfill({ path: 'mock_data.json' }));- * ```- *- * @param options- */- fulfill(options?: {/**- * Response body.+ * Specifies if viewport supports touch events. Defaults to false. Learn more about+ * [mobile emulation](https://playwright.dev/docs/emulation#devices).*/- body?: string|Buffer;+ hasTouch?: boolean;/**- * If set, equals to setting `Content-Type` response header.+ * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no+ * origin is specified, the username and password are sent to any servers upon unauthorized responses.*/- contentType?: string;+ httpCredentials?: {+ username: string;++ password: string;++ /**+ * Restrain sending http credentials on specific origin (scheme://host:port).+ */+ origin?: string;++ /**+ * This option only applies to the requests sent from corresponding+ * [APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext) and does not affect requests sent from+ * the browser. `'always'` - `Authorization` header with basic authentication credentials will be sent with the each+ * API request. `'unauthorized` - the credentials are only sent when 401 (Unauthorized) response with+ * `WWW-Authenticate` header is received. Defaults to `'unauthorized'`.+ */+ send?: "unauthorized"|"always";+ };/**- * Response headers. Header values will be converted to a string.+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.*/- headers?: { [key: string]: string; };+ ignoreHTTPSErrors?: boolean;/**- * JSON response. This method will set the content type to `application/json` if not set.+ * Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,+ * so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more+ * about [mobile emulation](https://playwright.dev/docs/emulation#ismobile).*/- json?: Serializable;+ isMobile?: boolean;/**- * File path to respond with. The content type will be inferred from file extension. If `path` is a relative path,- * then it is resolved relative to the current working directory.+ * Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about+ * [disabling JavaScript](https://playwright.dev/docs/emulation#javascript-enabled).*/- path?: string;+ javaScriptEnabled?: boolean;/**- * [APIResponse](https://playwright.dev/docs/api/class-apiresponse) to fulfill route's request with. Individual fields- * of the response (such as headers) can be overridden using fulfill options.+ * Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value,+ * `Accept-Language` request header value as well as number and date formatting rules. Defaults to the system default+ * locale. Learn more about emulation in our [emulation guide](https://playwright.dev/docs/emulation#locale--timezone).*/- response?: APIResponse;+ locale?: string;/**- * Response status code, defaults to `200`.+ * Logger sink for Playwright logging.+ * @deprecated The logs received by the logger are incomplete. Please use tracing instead.*/- status?: number;- }): Promise<void>;+ logger?: Logger;- /**- * A request to be routed.- */- request(): Request;-}+ /**+ * Whether to emulate network being offline. Defaults to `false`. Learn more about+ * [network emulation](https://playwright.dev/docs/emulation#offline).+ */+ offline?: boolean;-/**- * Selectors can be used to install custom selector engines. See [extensibility](https://playwright.dev/docs/extensibility) for more- * information.- */-export interface Selectors {- /**- * Selectors must be registered before creating the page.- *- * **Usage**- *- * An example of registering selector engine that queries elements based on a tag name:- *- * ```js- * const { selectors, firefox } = require('@playwright/test'); // Or 'chromium' or 'webkit'.- *- * (async () => {- * // Must be a function that evaluates to a selector engine instance.- * const createTagNameEngine = () => ({- * // Returns the first element matching given selector in the root's subtree.- * query(root, selector) {- * return root.querySelector(selector);- * },- *- * // Returns all elements matching given selector in the root's subtree.- * queryAll(root, selector) {- * return Array.from(root.querySelectorAll(selector));- * }- * });- *- * // Register the engine. Selectors will be prefixed with "tag=".- * await selectors.register('tag', createTagNameEngine);- *- * const browser = await firefox.launch();- * const page = await browser.newPage();- * await page.setContent(`<div><button>Click me</button></div>`);- *- * // Use the selector prefixed with its name.- * const button = page.locator('tag=button');- * // We can combine it with built-in locators.- * await page.locator('tag=div').getByText('Click me').click();- * // Can use it in any methods supporting selectors.- * const buttonCount = await page.locator('tag=button').count();- *- * await browser.close();- * })();- * ```- *- * @param name Name that is used in selectors as a prefix, e.g. `{name: 'foo'}` enables `foo=myselectorbody` selectors. May only- * contain `[a-zA-Z0-9_]` characters.- * @param script Script that evaluates to a selector engine instance. The script is evaluated in the page context.- * @param options- */- register(name: string, script: Function|string|{/**- * Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working- * directory. Optional.+ * A list of permissions to grant to all pages in this context. See+ * [browserContext.grantPermissions(permissions[, options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-grant-permissions)+ * for more details. Defaults to none.*/- path?: string;+ permissions?: Array<string>;/**- * Raw script content. Optional.+ * Optional package name to launch instead of default Chrome for Android.*/- content?: string;- }, options?: {+ pkg?: string;+/**- * Whether to run this selector engine in isolated JavaScript environment. This environment has access to the same- * DOM, but not any JavaScript objects from the frame's scripts. Defaults to `false`. Note that running as a content- * script is not guaranteed when this engine is used together with other registered engines.+ * Network proxy settings.*/- contentScript?: boolean;- }): Promise<void>;+ proxy?: {+ /**+ * Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example `http://myproxy.com:3128` or+ * `socks5://myproxy.com:3128`. Short form `myproxy.com:3128` is considered an HTTP proxy.+ */+ server: string;- /**- * Defines custom attribute name to be used in- * [page.getByTestId(testId)](https://playwright.dev/docs/api/class-page#page-get-by-test-id). `data-testid` is used- * by default.- * @param attributeName Test id attribute name.- */- setTestIdAttribute(attributeName: string): void;-}+ /**+ * Optional comma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.+ */+ bypass?: string;-/**- * The Touchscreen class operates in main-frame CSS pixels relative to the top-left corner of the viewport. Methods on- * the touchscreen can only be used in browser contexts that have been initialized with `hasTouch` set to true.- *- * This class is limited to emulating tap gestures. For examples of other gestures simulated by manually dispatching- * touch events, see the [emulating legacy touch events](https://playwright.dev/docs/touch-events) page.- */-export interface Touchscreen {- /**- * Dispatches a `touchstart` and `touchend` event with a single touch at the position- * ([`x`](https://playwright.dev/docs/api/class-touchscreen#touchscreen-tap-option-x),[`y`](https://playwright.dev/docs/api/class-touchscreen#touchscreen-tap-option-y)).- *- * **NOTE** [page.tap(selector[, options])](https://playwright.dev/docs/api/class-page#page-tap) the method will throw- * if [`hasTouch`](https://playwright.dev/docs/api/class-browser#browser-new-context-option-has-touch) option of the- * browser context is false.- *- * @param x X coordinate relative to the main frame's viewport in CSS pixels.- * @param y Y coordinate relative to the main frame's viewport in CSS pixels.- */- tap(x: number, y: number): Promise<void>;-}+ /**+ * Optional username to use if HTTP proxy requires authentication.+ */+ username?: string;++ /**+ * Optional password to use if HTTP proxy requires authentication.+ */+ password?: string;+ };++ /**+ * Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into `recordHar.path` file.+ * If not specified, the HAR is not recorded. Make sure to await+ * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for+ * the HAR to be saved.+ */+ recordHar?: {+ /**+ * Optional setting to control whether to omit request content from the HAR. Defaults to `false`. Deprecated, use+ * `content` policy instead.+ */+ omitContent?: boolean;++ /**+ * Optional setting to control resource content management. If `omit` is specified, content is not persisted. If+ * `attach` is specified, resources are persisted as separate files or entries in the ZIP archive. If `embed` is+ * specified, content is stored inline the HAR file as per HAR specification. Defaults to `attach` for `.zip` output+ * files and to `embed` for all other file extensions.+ */+ content?: "omit"|"embed"|"attach";++ /**+ * Path on the filesystem to write the HAR file to. If the file name ends with `.zip`, `content: 'attach'` is used by+ * default.+ */+ path: string;++ /**+ * When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,+ * cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.+ */+ mode?: "full"|"minimal";++ /**+ * A glob or regex pattern to filter requests that are stored in the HAR. When a+ * [`baseURL`](https://playwright.dev/docs/api/class-browser#browser-new-context-option-base-url) via the context+ * options was provided and the passed URL is a path, it gets merged via the+ * [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor. Defaults to none.+ */+ urlFilter?: string|RegExp;+ };-/**- * API for collecting and saving Playwright traces. Playwright traces can be opened in- * [Trace Viewer](https://playwright.dev/docs/trace-viewer) after Playwright script runs.- *- * **NOTE** You probably want to- * [enable tracing in your config file](https://playwright.dev/docs/api/class-testoptions#test-options-trace) instead- * of using `context.tracing`.- *- * The `context.tracing` API captures browser operations and network activity, but it doesn't record test assertions- * (like `expect` calls). We recommend- * [enabling tracing through Playwright Test configuration](https://playwright.dev/docs/api/class-testoptions#test-options-trace),- * which includes those assertions and provides a more complete trace for debugging test failures.- *- * Start recording a trace before performing actions. At the end, stop tracing and save it to a file.- *- * ```js- * const browser = await chromium.launch();- * const context = await browser.newContext();- * await context.tracing.start({ screenshots: true, snapshots: true });- * const page = await context.newPage();- * await page.goto('https://playwright.dev');- * expect(page.url()).toBe('https://playwright.dev');- * await context.tracing.stop({ path: 'trace.zip' });- * ```- *- */-export interface Tracing {- /**- * **NOTE** Use `test.step` instead when available.- *- * Creates a new group within the trace, assigning any subsequent API calls to this group, until- * [tracing.groupEnd()](https://playwright.dev/docs/api/class-tracing#tracing-group-end) is called. Groups can be- * nested and will be visible in the trace viewer.- *- * **Usage**- *- * ```js- * // use test.step instead- * await test.step('Log in', async () => {- * // ...- * });- * ```- *- * @param name Group name shown in the trace viewer.- * @param options- */- group(name: string, options?: {/**- * Specifies a custom location for the group to be shown in the trace viewer. Defaults to the location of the- * [tracing.group(name[, options])](https://playwright.dev/docs/api/class-tracing#tracing-group) call.+ * Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded.+ * Make sure to await+ * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for+ * videos to be saved.*/- location?: {- file: string;+ recordVideo?: {+ /**+ * Path to the directory to put videos into. If not specified, the videos will be stored in `artifactsDir` (see+ * [browserType.launch([options])](https://playwright.dev/docs/api/class-browsertype#browser-type-launch) options).+ */+ dir?: string;- line?: number;+ /**+ * Optional dimensions of the recorded videos. If not specified the size will be equal to `viewport` scaled down to+ * fit into 800x800. If `viewport` is not configured explicitly the video size defaults to 800x450. Actual picture of+ * each page will be scaled down if necessary to fit the specified size.+ */+ size?: {+ /**+ * Video frame width.+ */+ width: number;- column?: number;+ /**+ * Video frame height.+ */+ height: number;+ };++ /**+ * If specified, enables visual annotations on interacted elements during video recording.+ */+ showActions?: {+ /**+ * How long each annotation is displayed in milliseconds. Defaults to `500`.+ */+ duration?: number;++ /**+ * Position of the action title overlay. Defaults to `"top-right"`.+ */+ position?: "top-left"|"top"|"top-right"|"bottom-left"|"bottom"|"bottom-right";++ /**+ * Font size of the action title in pixels. Defaults to `24`.+ */+ fontSize?: number;+ };};- }): Promise<Disposable>;- /**- * Closes the last group created by- * [tracing.group(name[, options])](https://playwright.dev/docs/api/class-tracing#tracing-group).- */- groupEnd(): Promise<void>;+ /**+ * Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See+ * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.+ * Passing `null` resets emulation to system defaults. Defaults to `'no-preference'`.+ */+ reducedMotion?: null|"reduce"|"no-preference";- /**- * Start tracing.- *- * **NOTE** You probably want to- * [enable tracing in your config file](https://playwright.dev/docs/api/class-testoptions#test-options-trace) instead- * of using `Tracing.start`.- *- * The `context.tracing` API captures browser operations and network activity, but it doesn't record test assertions- * (like `expect` calls). We recommend- * [enabling tracing through Playwright Test configuration](https://playwright.dev/docs/api/class-testoptions#test-options-trace),- * which includes those assertions and provides a more complete trace for debugging test failures.- *- * **Usage**- *- * ```js- * await context.tracing.start({ screenshots: true, snapshots: true });- * const page = await context.newPage();- * await page.goto('https://playwright.dev');- * expect(page.url()).toBe('https://playwright.dev');- * await context.tracing.stop({ path: 'trace.zip' });- * ```- *- * @param options- */- start(options?: {/**- * When enabled, the trace is written to an unarchived file that is updated in real time as actions occur, instead of- * caching changes and archiving them into a zip file at the end. This is useful for live trace viewing during test- * execution.+ * Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the+ * [`viewport`](https://playwright.dev/docs/api/class-androiddevice#android-device-launch-browser-option-viewport) is+ * set.*/- live?: boolean;+ screen?: {+ /**+ * page width in pixels.+ */+ width: number;++ /**+ * page height in pixels.+ */+ height: number;+ };/**- * If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the- * [`tracesDir`](https://playwright.dev/docs/api/class-browsertype#browser-type-launch-option-traces-dir) directory- * specified in- * [browserType.launch([options])](https://playwright.dev/docs/api/class-browsertype#browser-type-launch). To specify- * the final trace zip file name, you need to pass `path` option to- * [tracing.stop([options])](https://playwright.dev/docs/api/class-tracing#tracing-stop) instead.+ * Whether to allow sites to register Service workers. Defaults to `'allow'`.+ * - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be+ * registered.+ * - `'block'`: Playwright will block all registration of Service Workers.*/- name?: string;+ serviceWorkers?: "allow"|"block";/**- * Whether to capture screenshots during tracing. Screenshots are used to build a timeline preview.+ * If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on+ * selectors that imply single target DOM element will throw when more than one element matches the selector. This+ * option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See+ * [Locator](https://playwright.dev/docs/api/class-locator) to learn more about the strict mode.*/- screenshots?: boolean;+ strictSelectors?: boolean;/**- * If this option is true tracing will- * - capture DOM snapshot on every action- * - record network activity+ * Changes the timezone of the context. See+ * [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)+ * for a list of supported timezone IDs. Defaults to the system timezone.*/- snapshots?: boolean;+ timezoneId?: string;/**- * Whether to include source files for trace actions.+ * Specific user agent to use in this context.*/- sources?: boolean;+ userAgent?: string;/**- * Trace name to be shown in the Trace Viewer.+ * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use `null` to disable the consistent+ * viewport emulation. Learn more about [viewport emulation](https://playwright.dev/docs/emulation#viewport).+ *+ * **NOTE** The `null` value opts out from the default presets, makes viewport depend on the host window size defined+ * by the operating system. It makes the execution of the tests non-deterministic.+ **/- title?: string;- }): Promise<void>;+ viewport?: null|{+ /**+ * page width in pixels.+ */+ width: number;++ /**+ * page height in pixels.+ */+ height: number;+ };+ }): Promise<BrowserContext>;/**- * Start a new trace chunk. If you'd like to record multiple traces on the same- * [BrowserContext](https://playwright.dev/docs/api/class-browsercontext), use- * [tracing.start([options])](https://playwright.dev/docs/api/class-tracing#tracing-start) once, and then create- * multiple trace chunks with- * [tracing.startChunk([options])](https://playwright.dev/docs/api/class-tracing#tracing-start-chunk) and- * [tracing.stopChunk([options])](https://playwright.dev/docs/api/class-tracing#tracing-stop-chunk).- *- * **Usage**- *- * ```js- * await context.tracing.start({ screenshots: true, snapshots: true });- * const page = await context.newPage();- * await page.goto('https://playwright.dev');- *- * await context.tracing.startChunk();- * await page.getByText('Get Started').click();- * // Everything between startChunk and stopChunk will be recorded in the trace.- * await context.tracing.stopChunk({ path: 'trace1.zip' });- *- * await context.tracing.startChunk();- * await page.goto('http://example.com');- * // Save a second trace file with different actions.- * await context.tracing.stopChunk({ path: 'trace2.zip' });- * ```- *+ * Performs a long tap on the widget defined by+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-long-tap-option-selector).+ * @param selector Selector to tap on.* @param options*/- startChunk(options?: {- /**- * If specified, intermediate trace files are going to be saved into the files with the given name prefix inside the- * [`tracesDir`](https://playwright.dev/docs/api/class-browsertype#browser-type-launch-option-traces-dir) directory- * specified in- * [browserType.launch([options])](https://playwright.dev/docs/api/class-browsertype#browser-type-launch). To specify- * the final trace zip file name, you need to pass `path` option to- * [tracing.stopChunk([options])](https://playwright.dev/docs/api/class-tracing#tracing-stop-chunk) instead.- */- name?: string;-+ longTap(selector: AndroidSelector, options?: {/**- * Trace name to be shown in the Trace Viewer.+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.*/- title?: string;+ timeout?: number;}): Promise<void>;/**- * Start recording a HAR (HTTP Archive) of network activity in this context. The HAR file is written to disk when- * [tracing.stopHar()](https://playwright.dev/docs/api/class-tracing#tracing-stop-har) is called, or when the returned- * [Disposable](https://playwright.dev/docs/api/class-disposable) is disposed.- *- * Only one HAR recording can be active at a time per- * [BrowserContext](https://playwright.dev/docs/api/class-browsercontext).- *- * **Usage**- *- * ```js- * await context.tracing.startHar('trace.har');- * const page = await context.newPage();- * await page.goto('https://playwright.dev');- * await context.tracing.stopHar();- * ```- *- * @param path Path on the filesystem to write the HAR file to. If the file name ends with `.zip`, the HAR is saved as a zip- * archive with response bodies attached as separate files.+ * Device model.+ */+ model(): string;++ /**+ * Launches a process in the shell on the device and returns a socket to communicate with the launched process.+ * @param command Shell command to execute.+ */+ open(command: string): Promise<AndroidSocket>;++ /**+ * Pinches the widget defined by+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-pinch-close-option-selector) in the+ * closing direction.+ * @param selector Selector to pinch close.+ * @param percent The size of the pinch as a percentage of the widget's size.* @param options*/- startHar(path: string, options?: {+ pinchClose(selector: AndroidSelector, percent: number, options?: {/**- * Optional setting to control resource content management. If `omit` is specified, content is not persisted. If- * `attach` is specified, resources are persisted as separate files or entries in the ZIP archive. If `embed` is- * specified, content is stored inline the HAR file as per HAR specification. Defaults to `attach` for `.zip` output- * files and to `embed` for all other file extensions.+ * Optional speed of the pinch in pixels per second.*/- content?: "omit"|"embed"|"attach";+ speed?: number;/**- * When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,- * cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.*/- mode?: "full"|"minimal";+ timeout?: number;+ }): Promise<void>;+ /**+ * Pinches the widget defined by+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-pinch-open-option-selector) in the+ * open direction.+ * @param selector Selector to pinch open.+ * @param percent The size of the pinch as a percentage of the widget's size.+ * @param options+ */+ pinchOpen(selector: AndroidSelector, percent: number, options?: {/**- * Only used together with `content: 'attach'`. When set, response bodies are placed in this directory instead of next- * to the HAR file. Not compatible with a `.zip` HAR file.+ * Optional speed of the pinch in pixels per second.*/- resourcesDir?: string;+ speed?: number;/**- * A glob or regex pattern to filter requests that are stored in the HAR. Defaults to none.+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.*/- urlFilter?: string|RegExp;- }): Promise<Disposable>;+ timeout?: number;+ }): Promise<void>;/**- * Stop tracing.+ * Presses the specific [`key`](https://playwright.dev/docs/api/class-androiddevice#android-device-press-option-key)+ * in the widget defined by+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-press-option-selector).+ * @param selector Selector to press the key in.+ * @param key The key to press.* @param options*/- stop(options?: {+ press(selector: AndroidSelector, key: AndroidKey, options?: {/**- * Export trace into the file with the given path.+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.*/- path?: string;+ timeout?: number;}): Promise<void>;/**- * Stop the trace chunk. See- * [tracing.startChunk([options])](https://playwright.dev/docs/api/class-tracing#tracing-start-chunk) for more details- * about multiple trace chunks.+ * Copies a file to the device.+ * @param file Either a path to the file, or file content.+ * @param path Path to the file on the device.* @param options*/- stopChunk(options?: {+ push(file: string|Buffer, path: string, options?: {/**- * Export trace collected since the last- * [tracing.startChunk([options])](https://playwright.dev/docs/api/class-tracing#tracing-start-chunk) call into the- * file with the given path.+ * Optional file mode, defaults to `644` (`rw-r--r--`).*/- path?: string;+ mode?: number;}): Promise<void>;/**- * Stop HAR recording and save the HAR file to the path given to- * [tracing.startHar(path[, options])](https://playwright.dev/docs/api/class-tracing#tracing-start-har).- */- stopHar(): Promise<void>;-}--/**- * When browser context is created with the `recordVideo` option, each page has a video object associated with it.- *- * ```js- * console.log(await page.video().path());- * ```- *- */-export interface Video {- /**- * Deletes the video file. Will wait for the video to finish if necessary.- */- delete(): Promise<void>;-- /**- * Returns the file system path this video will be recorded to. The video is guaranteed to be written to the- * filesystem upon closing the browser context. This method throws when connected remotely.- */- path(): Promise<string>;-- /**- * Saves the video to a user-specified path. It is safe to call this method while the video is still in progress, or- * after the page has closed. This method waits until the page is closed and the video is fully saved.- * @param path Path where the video should be saved.+ * Returns the buffer with the captured screenshot of the device.+ * @param options*/- saveAs(path: string): Promise<void>;-}+ screenshot(options?: {+ /**+ * The file path to save the image to. If+ * [`path`](https://playwright.dev/docs/api/class-androiddevice#android-device-screenshot-option-path) is a relative+ * path, then it is resolved relative to the current working directory. If no path is provided, the image won't be+ * saved to the disk.+ */+ path?: string;+ }): Promise<Buffer>;-/**- * [WebError](https://playwright.dev/docs/api/class-weberror) class represents an unhandled exception thrown in the- * page. It is dispatched via the- * [browserContext.on('weberror')](https://playwright.dev/docs/api/class-browsercontext#browser-context-event-web-error)- * event.- *- * ```js- * // Log all uncaught errors to the terminal- * context.on('weberror', webError => {- * console.log(`Uncaught exception: "${webError.error()}"`);- * });- *- * // Navigate to a page with an exception.- * await page.goto('data:text/html,<script>throw new Error("Test")</script>');- * ```- *- */-export interface WebError {/**- * Unhandled error that was thrown.+ * Scrolls the widget defined by+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-scroll-option-selector) in the+ * specified+ * [`direction`](https://playwright.dev/docs/api/class-androiddevice#android-device-scroll-option-direction).+ * @param selector Selector to scroll.+ * @param direction Scroll direction.+ * @param percent Distance to scroll as a percentage of the widget's size.+ * @param options*/- error(): Error;-- location(): {+ scroll(selector: AndroidSelector, direction: "down"|"up"|"left"|"right", percent: number, options?: {/**- * URL of the resource.+ * Optional speed of the scroll in pixels per second.*/- url: string;+ speed?: number;/**- * 0-based line number in the resource.+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.*/- line: number;+ timeout?: number;+ }): Promise<void>;- /**- * 0-based column number in the resource.- */- column: number;- };+ /**+ * Device serial number.+ */+ serial(): string;/**- * The page that produced this unhandled exception, if any.+ * This setting will change the default maximum time for all the methods accepting+ * [`timeout`](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout-option-timeout)+ * option.+ * @param timeout Maximum time in milliseconds*/- page(): null|Page;-}+ setDefaultTimeout(timeout: number): void;-/**- * The [WebSocket](https://playwright.dev/docs/api/class-websocket) class represents WebSocket connections within a- * page. It provides the ability to inspect and manipulate the data being transmitted and received.- *- * If you want to intercept or modify WebSocket frames, consider using- * [WebSocketRoute](https://playwright.dev/docs/api/class-websocketroute).- */-export interface WebSocket {/**- * Fired when the websocket closes.+ * Executes a shell command on the device and returns its output.+ * @param command Shell command to execute.*/- on(event: 'close', listener: (webSocket: WebSocket) => any): this;+ shell(command: string): Promise<Buffer>;/**- * Fired when the websocket receives a frame.+ * Swipes the widget defined by+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-swipe-option-selector) in the+ * specified [`direction`](https://playwright.dev/docs/api/class-androiddevice#android-device-swipe-option-direction).+ * @param selector Selector to swipe.+ * @param direction Swipe direction.+ * @param percent Distance to swipe as a percentage of the widget's size.+ * @param options*/- on(event: 'framereceived', listener: (data: {+ swipe(selector: AndroidSelector, direction: "down"|"up"|"left"|"right", percent: number, options?: {/**- * frame payload+ * Optional speed of the swipe in pixels per second.*/- payload: string|Buffer;- }) => any): this;+ speed?: number;- /**- * Fired when the websocket sends a frame.- */- on(event: 'framesent', listener: (data: {/**- * frame payload+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.*/- payload: string|Buffer;- }) => any): this;+ timeout?: number;+ }): Promise<void>;/**- * Fired when the websocket has an error.+ * Taps on the widget defined by+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-tap-option-selector).+ * @param selector Selector to tap on.+ * @param options*/- on(event: 'socketerror', listener: (string: string) => any): this;+ tap(selector: AndroidSelector, options?: {+ /**+ * Optional duration of the tap in milliseconds.+ */+ duration?: number;- /**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.- */- once(event: 'close', listener: (webSocket: WebSocket) => any): this;+ /**+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.+ */+ timeout?: number;+ }): Promise<void>;/**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ * Waits for the specific+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-wait-option-selector) to either+ * appear or disappear, depending on the+ * [`state`](https://playwright.dev/docs/api/class-androiddevice#android-device-wait-option-state).+ * @param selector Selector to wait for.+ * @param options*/- once(event: 'framereceived', listener: (data: {+ wait(selector: AndroidSelector, options?: {/**- * frame payload+ * Optional state. Can be either:+ * - default - wait for element to be present.+ * - `'gone'` - wait for element to not be present.*/- payload: string|Buffer;- }) => any): this;+ state?: "gone";- /**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.- */- once(event: 'framesent', listener: (data: {/**- * frame payload+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.*/- payload: string|Buffer;- }) => any): this;+ timeout?: number;+ }): Promise<void>;/**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ * Emitted when the device connection gets closed.*/- once(event: 'socketerror', listener: (string: string) => any): this;+ waitForEvent(event: 'close', optionsOrPredicate?: { predicate?: (androidDevice: AndroidDevice) => boolean | Promise<boolean>, timeout?: number } | ((androidDevice: AndroidDevice) => boolean | Promise<boolean>)): Promise<AndroidDevice>;/**- * Fired when the websocket closes.+ * Emitted when a new WebView instance is detected.*/- addListener(event: 'close', listener: (webSocket: WebSocket) => any): this;+ waitForEvent(event: 'webview', optionsOrPredicate?: { predicate?: (androidWebView: AndroidWebView) => boolean | Promise<boolean>, timeout?: number } | ((androidWebView: AndroidWebView) => boolean | Promise<boolean>)): Promise<AndroidWebView>;+/**- * Fired when the websocket receives a frame.+ * This method waits until [AndroidWebView](https://playwright.dev/docs/api/class-androidwebview) matching the+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-web-view-option-selector) is opened+ * and returns it. If there is already an open [AndroidWebView](https://playwright.dev/docs/api/class-androidwebview)+ * matching the+ * [`selector`](https://playwright.dev/docs/api/class-androiddevice#android-device-web-view-option-selector), returns+ * immediately.+ * @param selector+ * @param options*/- addListener(event: 'framereceived', listener: (data: {+ webView(selector: {/**- * frame payload+ * Optional Package identifier.*/- payload: string|Buffer;- }) => any): this;+ pkg?: string;- /**- * Fired when the websocket sends a frame.- */- addListener(event: 'framesent', listener: (data: {/**- * frame payload+ * Optional webview socket name.*/- payload: string|Buffer;- }) => any): this;+ socketName?: string;+ }, options?: {+ /**+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed+ * by using the+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)+ * method.+ */+ timeout?: number;+ }): Promise<AndroidWebView>;/**- * Fired when the websocket has an error.+ * Currently open WebViews.*/- addListener(event: 'socketerror', listener: (string: string) => any): this;+ webViews(): Array<AndroidWebView>;- /**- * Removes an event listener added by `on` or `addListener`.- */- removeListener(event: 'close', listener: (webSocket: WebSocket) => any): this;+ input: AndroidInput;++ [Symbol.asyncDispose](): Promise<void>;+}+export interface AndroidInput {/**- * Removes an event listener added by `on` or `addListener`.+ * Performs a drag between [`from`](https://playwright.dev/docs/api/class-androidinput#android-input-drag-option-from)+ * and [`to`](https://playwright.dev/docs/api/class-androidinput#android-input-drag-option-to) points.+ * @param from The start point of the drag.+ * @param to The end point of the drag.+ * @param steps The number of steps in the drag. Each step takes 5 milliseconds to complete.*/- removeListener(event: 'framereceived', listener: (data: {- /**- * frame payload- */- payload: string|Buffer;- }) => any): this;+ drag(from: {+ x: number;++ y: number;+ }, to: {+ x: number;++ y: number;+ }, steps: number): Promise<void>;/**- * Removes an event listener added by `on` or `addListener`.+ * Presses the [`key`](https://playwright.dev/docs/api/class-androidinput#android-input-press-option-key).+ * @param key Key to press.*/- removeListener(event: 'framesent', listener: (data: {- /**- * frame payload- */- payload: string|Buffer;- }) => any): this;+ press(key: AndroidKey): Promise<void>;/**- * Removes an event listener added by `on` or `addListener`.+ * Swipes following the path defined by+ * [`segments`](https://playwright.dev/docs/api/class-androidinput#android-input-swipe-option-segments).+ * @param from The point to start swiping from.+ * @param segments Points following the [`from`](https://playwright.dev/docs/api/class-androidinput#android-input-swipe-option-from)+ * point in the swipe gesture.+ * @param steps The number of steps for each segment. Each step takes 5 milliseconds to complete, so 100 steps means half a second+ * per each segment.*/- removeListener(event: 'socketerror', listener: (string: string) => any): this;+ swipe(from: {+ x: number;++ y: number;+ }, segments: ReadonlyArray<{+ x: number;++ y: number;+ }>, steps: number): Promise<void>;/**- * Removes an event listener added by `on` or `addListener`.+ * Taps at the specified [`point`](https://playwright.dev/docs/api/class-androidinput#android-input-tap-option-point).+ * @param point The point to tap at.*/- off(event: 'close', listener: (webSocket: WebSocket) => any): this;+ tap(point: {+ x: number;++ y: number;+ }): Promise<void>;/**- * Removes an event listener added by `on` or `addListener`.+ * Types [`text`](https://playwright.dev/docs/api/class-androidinput#android-input-type-option-text) into currently+ * focused widget.+ * @param text Text to type.*/- off(event: 'framereceived', listener: (data: {- /**- * frame payload- */- payload: string|Buffer;- }) => any): this;+ type(text: string): Promise<void>;+}+/**+ * [AndroidSocket](https://playwright.dev/docs/api/class-androidsocket) is a way to communicate with a process+ * launched on the [AndroidDevice](https://playwright.dev/docs/api/class-androiddevice). Use+ * [androidDevice.open(command)](https://playwright.dev/docs/api/class-androiddevice#android-device-open) to open a+ * socket.+ */+export interface AndroidSocket {/**- * Removes an event listener added by `on` or `addListener`.+ * Emitted when the socket is closed.*/- off(event: 'framesent', listener: (data: {- /**- * frame payload- */- payload: string|Buffer;- }) => any): this;+ on(event: 'close', listener: () => any): this;/**- * Removes an event listener added by `on` or `addListener`.+ * Emitted when data is available to read from the socket.*/- off(event: 'socketerror', listener: (string: string) => any): this;+ on(event: 'data', listener: (buffer: Buffer) => any): this;/**- * Fired when the websocket closes.+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.*/- prependListener(event: 'close', listener: (webSocket: WebSocket) => any): this;+ once(event: 'close', listener: () => any): this;/**- * Fired when the websocket receives a frame.+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.*/- prependListener(event: 'framereceived', listener: (data: {- /**- * frame payload- */- payload: string|Buffer;- }) => any): this;+ once(event: 'data', listener: (buffer: Buffer) => any): this;/**- * Fired when the websocket sends a frame.+ * Emitted when the socket is closed.*/- prependListener(event: 'framesent', listener: (data: {- /**- * frame payload- */- payload: string|Buffer;- }) => any): this;+ addListener(event: 'close', listener: () => any): this;/**- * Fired when the websocket has an error.+ * Emitted when data is available to read from the socket.*/- prependListener(event: 'socketerror', listener: (string: string) => any): this;+ addListener(event: 'data', listener: (buffer: Buffer) => any): this;/**- * Indicates that the web socket has been closed.+ * Removes an event listener added by `on` or `addListener`.*/- isClosed(): boolean;+ removeListener(event: 'close', listener: () => any): this;/**- * Contains the URL of the WebSocket.+ * Removes an event listener added by `on` or `addListener`.*/- url(): string;+ removeListener(event: 'data', listener: (buffer: Buffer) => any): this;/**- * Fired when the websocket closes.+ * Removes an event listener added by `on` or `addListener`.*/- waitForEvent(event: 'close', optionsOrPredicate?: { predicate?: (webSocket: WebSocket) => boolean | Promise<boolean>, timeout?: number } | ((webSocket: WebSocket) => boolean | Promise<boolean>)): Promise<WebSocket>;+ off(event: 'close', listener: () => any): this;/**- * Fired when the websocket receives a frame.+ * Removes an event listener added by `on` or `addListener`.*/- waitForEvent(event: 'framereceived', optionsOrPredicate?: { predicate?: (data: {- /**- * frame payload- */- payload: string|Buffer;- }) => boolean | Promise<boolean>, timeout?: number } | ((data: {- /**- * frame payload- */- payload: string|Buffer;- }) => boolean | Promise<boolean>)): Promise<{- /**- * frame payload- */- payload: string|Buffer;- }>;+ off(event: 'data', listener: (buffer: Buffer) => any): this;/**- * Fired when the websocket sends a frame.+ * Emitted when the socket is closed.*/- waitForEvent(event: 'framesent', optionsOrPredicate?: { predicate?: (data: {- /**- * frame payload- */- payload: string|Buffer;- }) => boolean | Promise<boolean>, timeout?: number } | ((data: {- /**- * frame payload- */- payload: string|Buffer;- }) => boolean | Promise<boolean>)): Promise<{- /**- * frame payload- */- payload: string|Buffer;- }>;+ prependListener(event: 'close', listener: () => any): this;/**- * Fired when the websocket has an error.+ * Emitted when data is available to read from the socket.*/- waitForEvent(event: 'socketerror', optionsOrPredicate?: { predicate?: (string: string) => boolean | Promise<boolean>, timeout?: number } | ((string: string) => boolean | Promise<boolean>)): Promise<string>;+ prependListener(event: 'data', listener: (buffer: Buffer) => any): this;++ /**+ * Closes the socket.+ */+ close(): Promise<void>;++ /**+ * Writes some [`data`](https://playwright.dev/docs/api/class-androidsocket#android-socket-write-option-data) to the+ * socket.+ * @param data Data to write.+ */+ write(data: Buffer): Promise<void>;+ [Symbol.asyncDispose](): Promise<void>;}/**- * Playwright has **experimental** support for Electron automation, exposed as `_electron`. An example of the Electron- * automation script would be:- *- * ```js- * import { _electron as electron } from 'playwright';- *- * (async () => {- * // Launch Electron app.- * const electronApp = await electron.launch({ args: ['main.js'] });- *- * // Evaluation expression in the Electron context.- * const appPath = await electronApp.evaluate(async ({ app }) => {- * // This runs in the main Electron process, parameter here is always- * // the result of the require('electron') in the main app script.- * return app.getAppPath();- * });- * console.log(appPath);- *- * // Get the first window that the app opens, wait if necessary.- * const window = await electronApp.firstWindow();- * // Print the title.- * console.log(await window.title());- * // Capture a screenshot.- * await window.screenshot({ path: 'intro.png' });- * // Direct Electron console to Node terminal.- * window.on('console', console.log);- * // Click button.- * await window.click('text=Click me');- * // Exit app.- * await electronApp.close();- * })();- * ```- *- * **Supported Electron versions are:**- * - v12.2.0+- * - v13.4.0+- * - v14+- *- * **Known issues:**- *- * If you are not able to launch Electron and it will end up in timeouts during launch, try the following:- * - Ensure that `nodeCliInspect`- * ([FuseV1Options.EnableNodeCliInspectArguments](https://www.electronjs.org/docs/latest/tutorial/fuses#nodecliinspect))- * fuse is **not** set to `false`.- *- * **Migrating from v1.59**- *- * A number of launch options have been removed after v1.59. See below for alternatives.- * - `recordHar` - use- * [tracing.startHar(path[, options])](https://playwright.dev/docs/api/class-tracing#tracing-start-har).- *- * ```js- * const electronApp = await electron.launch({ args: ['main.js'] });- * await electronApp.context().tracing.startHar('network.har');- * // ... drive the app ...- * await electronApp.context().tracing.stopHar();- * await electronApp.close();- * ```- *- * - `recordVideo` - use- * [screencast.start([options])](https://playwright.dev/docs/api/class-screencast#screencast-start) on each- * window.- *- * ```js- * const electronApp = await electron.launch({ args: ['main.js'] });- * const window = await electronApp.firstWindow();- * await window.screencast.start({ path: 'video.webm' });- * // ... drive the window ...- * await window.screencast.stop();- * await electronApp.close();- * ```- *- * - `colorScheme` - use- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) on each window.- *- * ```js- * const window = await electronApp.firstWindow();- * await window.emulateMedia({ colorScheme: 'dark' });- * ```- *- * - `extraHTTPHeaders` - use- * [browserContext.setExtraHTTPHeaders(headers)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-extra-http-headers).- *- * ```js- * await electronApp.context().setExtraHTTPHeaders({ 'X-My-Header': 'value' });- * ```- *- * - `geolocation` - use- * [browserContext.setGeolocation(geolocation)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-geolocation).- *- * ```js- * await electronApp.context().setGeolocation({ latitude: 48.858455, longitude: 2.294474 });- * ```- *- * - `httpCredentials` - use- * [browserContext.setHTTPCredentials(httpCredentials)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-http-credentials).- *- * ```js- * await electronApp.context().setHTTPCredentials({ username: 'user', password: 'pass' });- * ```- *- * - `offline` - use- * [browserContext.setOffline(offline)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-offline).- *- * ```js- * await electronApp.context().setOffline(true);- * ```- *- * - `bypassCSP` - disable CSP at the `BrowserWindow` level via Electron's- * [web preferences](https://www.electronjs.org/docs/latest/api/structures/web-preferences). Note that- * `webSecurity: false` also disables CORS and the Same-Origin Policy.- *- * ```js- * const win = new BrowserWindow({- * webPreferences: {- * webSecurity: false,- * },- * });- * ```- *- * - `ignoreHTTPSErrors`- *- * There are several ways to relax HTTPS checks in Electron. Pick the one that matches the scope you need.- *- * Per-window, allow mixed content through- * [web preferences](https://www.electronjs.org/docs/latest/api/structures/web-preferences):- *- * ```js- * const win = new BrowserWindow({- * webPreferences: {- * allowRunningInsecureContent: true,- * },- * });- * ```- *- * Process-wide, ignore certificate errors via Chromium command-line switches (must run before the `ready` event):- *- * ```js- * const { app } = require('electron');- * app.commandLine.appendSwitch('ignore-certificate-errors');- * // Optional: also ignore localhost certificate errors when testing on an IP.- * app.commandLine.appendSwitch('allow-insecure-localhost', 'true');- * ```- *- * Per-request, accept the certificate manually via the- * [`certificate-error`](https://www.electronjs.org/docs/latest/api/app#event-certificate-error) event:- *- * ```js- * app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {- * event.preventDefault();- * callback(true);- * });- * ```- *- * - `timezoneId` - set an environment variable at the very top of the main file, before any other logic or Chromium- * windows are initialized.- *- * ```js- * // main.js- * process.env.TZ = 'Europe/London';- *- * const { app } = require('electron');- * // ... rest of your app logic- * ```- *+ * [AndroidWebView](https://playwright.dev/docs/api/class-androidwebview) represents a WebView open on the+ * [AndroidDevice](https://playwright.dev/docs/api/class-androiddevice). WebView is usually obtained using+ * [androidDevice.webView(selector[, options])](https://playwright.dev/docs/api/class-androiddevice#android-device-web-view).*/-export interface Electron {+export interface AndroidWebView {/**- * Launches electron application specified with the- * [`executablePath`](https://playwright.dev/docs/api/class-electron#electron-launch-option-executable-path).- * @param options+ * Emitted when the WebView is closed.*/- launch(options?: {- /**- * Additional arguments to pass to the application when launching. You typically pass the main script name here.- */- args?: Array<string>;+ on(event: 'close', listener: () => any): this;- /**- * Enable Chromium sandboxing. Defaults to `false`.- */- chromiumSandbox?: boolean;+ /**+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.+ */+ once(event: 'close', listener: () => any): this;- /**- * Current working directory to launch application from.- */- cwd?: string;+ /**+ * Emitted when the WebView is closed.+ */+ addListener(event: 'close', listener: () => any): this;- /**- * Specifies environment variables that will be visible to Electron. Defaults to `process.env`.- */- env?: { [key: string]: string; };+ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ removeListener(event: 'close', listener: () => any): this;- /**- * Launches given Electron application. If not specified, launches the default Electron executable installed in this- * package, located at `node_modules/.bin/electron`.- */- executablePath?: string;+ /**+ * Removes an event listener added by `on` or `addListener`.+ */+ off(event: 'close', listener: () => any): this;- /**- * Maximum time in milliseconds to wait for the application to start. Defaults to `30000` (30 seconds). Pass `0` to- * disable timeout.- */- timeout?: number;- }): Promise<ElectronApplication>;+ /**+ * Emitted when the WebView is closed.+ */+ prependListener(event: 'close', listener: () => any): this;++ /**+ * Connects to the WebView and returns a regular Playwright [Page](https://playwright.dev/docs/api/class-page) to+ * interact with.+ */+ page(): Promise<Page>;++ /**+ * WebView process PID.+ */+ pid(): number;++ /**+ * WebView package identifier.+ */+ pkg(): string;}export interface LaunchOptions {diff --git a/utils/build/build.js b/utils/build/build.jsindex 5c1398858f..a47606df42 100644--- a/utils/build/build.js+++ b/utils/build/build.js@@ -964,6 +964,7 @@ onChanges.push({'docs/src/test-api/','docs/src/test-reporter-api/','docs/src/electron-api/',+ 'docs/src/mobile-api/','utils/generate_types/overrides.d.ts','utils/generate_types/overrides-test.d.ts','utils/generate_types/overrides-testReporter.d.ts',diff --git a/utils/doclint/cli.js b/utils/doclint/cli.jsindex a7471868c9..141ecf3eb2 100755--- a/utils/doclint/cli.js+++ b/utils/doclint/cli.js@@ -134,6 +134,7 @@ async function run() {const testApiRoot = path.join(documentationRoot, 'test-api');const testReporterApiRoot = path.join(documentationRoot, 'test-reporter-api');const electronApiRoot = path.join(documentationRoot, 'electron-api');+ const mobileApiRoot = path.join(documentationRoot, 'mobile-api');for (const lang of langs) {try {let documentation = parseApi(apiRoot);@@ -144,6 +145,8 @@ async function run() {parseApi(testReporterApiRoot)).mergeWith(parseApi(electronApiRoot, path.join(documentationRoot, 'api', 'params.md'))+ ).mergeWith(+ parseApi(mobileApiRoot, path.join(documentationRoot, 'api', 'params.md')));}documentation.filterForLanguage(lang);@@ -181,7 +184,7 @@ async function run() {// Standardise naming and remove the filter in the file name// Also, Internally (playwright.dev generator) we merge test-api and test-reporter-api into api.- const canonicalName = filePath.replace(/(-(js|python|csharp|java))+/, '').replace(/(\/|\\)(test-api|test-reporter-api|electron-api)(\/|\\)/, `${path.sep}api${path.sep}`);+ const canonicalName = filePath.replace(/(-(js|python|csharp|java))+/, '').replace(/(\/|\\)(test-api|test-reporter-api|electron-api|mobile-api)(\/|\\)/, `${path.sep}api${path.sep}`);mdSections.add(canonicalName);const data = fs.readFileSync(filePath, 'utf-8');@@ -189,7 +192,7 @@ async function run() {// Validates code snippet groups.rootNode = docs.processCodeGroups(rootNode, lang, tabs => tabs.map(tab => tab.spec));// Renders links.- if (!filePath.startsWith(apiRoot) && !filePath.startsWith(testApiRoot) && !filePath.startsWith(testReporterApiRoot) && !filePath.startsWith(electronApiRoot))+ if (!filePath.startsWith(apiRoot) && !filePath.startsWith(testApiRoot) && !filePath.startsWith(testReporterApiRoot) && !filePath.startsWith(electronApiRoot) && !filePath.startsWith(mobileApiRoot))documentation.renderLinksInNodes(rootNode);// Validate links.{@@ -268,7 +271,8 @@ async function run() {// Check for missing docs{- const apiDocumentation = parseApi(path.join(PROJECT_DIR, 'docs', 'src', 'api'));+ const apiDocumentation = parseApi(path.join(PROJECT_DIR, 'docs', 'src', 'api'))+ .mergeWith(parseApi(path.join(PROJECT_DIR, 'docs', 'src', 'mobile-api'), path.join(PROJECT_DIR, 'docs', 'src', 'api', 'params.md')));apiDocumentation.filterForLanguage('js');const srcClient = path.join(PROJECT_DIR, 'packages', 'playwright-core', 'src', 'client');const sources = fs.readdirSync(srcClient).map(n => path.join(srcClient, n));diff --git a/utils/generate_types/index.js b/utils/generate_types/index.jsindex b5e5128fc0..2274c79577 100644--- a/utils/generate_types/index.js+++ b/utils/generate_types/index.js@@ -498,7 +498,8 @@ class TypesGenerator {(async function () {const coreDocumentation = parseApi(path.join(PROJECT_DIR, 'docs', 'src', 'api'))- .mergeWith(parseApi(path.join(PROJECT_DIR, 'docs', 'src', 'electron-api'), path.join(PROJECT_DIR, 'docs', 'src', 'api', 'params.md')));+ .mergeWith(parseApi(path.join(PROJECT_DIR, 'docs', 'src', 'electron-api'), path.join(PROJECT_DIR, 'docs', 'src', 'api', 'params.md')))+ .mergeWith(parseApi(path.join(PROJECT_DIR, 'docs', 'src', 'mobile-api'), path.join(PROJECT_DIR, 'docs', 'src', 'api', 'params.md')));const testDocumentation = parseApi(path.join(PROJECT_DIR, 'docs', 'src', 'test-api'), path.join(PROJECT_DIR, 'docs', 'src', 'api', 'params.md'));const reporterDocumentation = parseApi(path.join(PROJECT_DIR, 'docs', 'src', 'test-reporter-api'));const assertionClasses = new Set([