Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

api: alias Fetch as ApiRequest (#9330)

Pavel Feldmane8fdbbfa0381
diff --git a/docs/src/api/class-apirequest.md b/docs/src/api/class-apirequest.md
new file mode 100644
index 0000000000..09bba3555c
--- /dev/null
+++ b/docs/src/api/class-apirequest.md
@@ -0,0 +1,53 @@
+# class: ApiRequest
+* langs: js
+
+Exposes API that can be used for the Web API testing.
+
+## async method: ApiRequest.newContext
+* langs: js
+- returns: <[ApiRequestContext]>
+
+**experimental** Creates new instances of [ApiRequestContext].
+
+### option: ApiRequest.newContext.useragent = %%-context-option-useragent-%%
+### option: ApiRequest.newContext.extraHTTPHeaders = %%-context-option-extrahttpheaders-%%
+### option: ApiRequest.newContext.httpCredentials = %%-context-option-httpcredentials-%%
+### option: ApiRequest.newContext.proxy = %%-browser-option-proxy-%%
+### option: ApiRequest.newContext.ignoreHTTPSErrors = %%-context-option-ignorehttpserrors-%%
+
+### option: ApiRequest.newContext.timeout
+- `timeout` <[float]>
+
+Maximum time in milliseconds to wait for the response. Defaults to
+`30000` (30 seconds). Pass `0` to disable timeout.
+
+
+### option: ApiRequest.newContext.baseURL
+- `baseURL` <[string]>
+
+When using [`method: ApiRequestContext.get`], [`method: ApiRequestContext.post`], [`method: ApiRequestContext.fetch`] 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. Examples:
+* baseURL: `http://localhost:3000` and sending rquest to `/bar.html` results in `http://localhost:3000/bar.html`
+* baseURL: `http://localhost:3000/foo/` and sending rquest to `./bar.html` results in `http://localhost:3000/foo/bar.html`
+
+### option: ApiRequest.newContext.storageState
+- `storageState` <[path]|[Object]>
+ - `cookies` <[Array]<[Object]>>
+ - `name` <[string]>
+ - `value` <[string]>
+ - `domain` <[string]>
+ - `path` <[string]>
+ - `expires` <[float]> Unix time in seconds.
+ - `httpOnly` <[boolean]>
+ - `secure` <[boolean]>
+ - `sameSite` <[SameSiteAttribute]<"Strict"|"Lax"|"None">>
+ - `origins` <[Array]<[Object]>>
+ - `origin` <[string]>
+ - `localStorage` <[Array]<[Object]>>
+ - `name` <[string]>
+ - `value` <[string]>
+
+Populates context with given storage state. This option can be used to initialize context with logged-in information
+obtained via [`method: BrowserContext.storageState`] or [`method: ApiRequestContext.storageState`]. Either a path to the
+file with saved storage, or the value returned by one of [`method: BrowserContext.storageState`] or
+[`method: ApiRequestContext.storageState`] methods.
+
diff --git a/docs/src/api/class-fetchrequest.md b/docs/src/api/class-apirequestcontext.md
similarity index 57%
rename from docs/src/api/class-fetchrequest.md
rename to docs/src/api/class-apirequestcontext.md
index 4fcd187552..24b3a85b69 100644
--- a/docs/src/api/class-fetchrequest.md
+++ b/docs/src/api/class-apirequestcontext.md
@@ -1,137 +1,136 @@
-# class: FetchRequest
+# class: ApiRequestContext
* langs: js
-This API is used for Web API testing. You can use it to trigger API endpoints, configure micro-services, prepare
+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. When used on [Page] or a [BrowserContext], this API will automatically use
the cookies from the corresponding [BrowserContext]. This means that if you log in using this API, your e2e test
will be logged in and vice versa.
-## async method: FetchRequest.dispose
+## async method: ApiRequestContext.dispose
-All responses received through [`method: FetchRequest.fetch`], [`method: FetchRequest.get`], [`method: FetchRequest.post`]
-and other methods are stored in the memory, so that you can later call [`method: FetchResponse.body`]. This method
-discards all stored responses, and makes [`method: FetchResponse.body`] throw "Response disposed" error.
+All responses received through [`method: ApiRequestContext.fetch`], [`method: ApiRequestContext.get`], [`method: ApiRequestContext.post`]
+and other methods are stored in the memory, so that you can later call [`method: ApiResponse.body`]. This method
+discards all stored responses, and makes [`method: ApiResponse.body`] throw "Response disposed" error.
-## async method: FetchRequest.fetch
-- returns: <[FetchResponse]>
+## async method: ApiRequestContext.fetch
+- returns: <[ApiResponse]>
Sends HTTP(S) fetch and returns its response. The method will populate fetch cookies from the context and update
context cookies from the response. The method will automatically follow redirects.
-### param: FetchRequest.fetch.urlOrRequest
+### param: ApiRequestContext.fetch.urlOrRequest
- `urlOrRequest` <[string]|[Request]>
Target URL or Request to get all fetch parameters from.
-### option: FetchRequest.fetch.params
+### option: ApiRequestContext.fetch.params
- `params` <[Object]<[string], [string]>>
Query parameters to be send with the URL.
-### option: FetchRequest.fetch.method
+### option: ApiRequestContext.fetch.method
- `method` <[string]>
If set changes the fetch method (e.g. PUT or POST). If not specified, GET method is used.
-### option: FetchRequest.fetch.headers
+### option: ApiRequestContext.fetch.headers
- `headers` <[Object]<[string], [string]>>
Allows to set HTTP headers.
-### option: FetchRequest.fetch.data = %%-fetch-option-data-%%
+### option: ApiRequestContext.fetch.data = %%-fetch-option-data-%%
+### option: ApiRequestContext.fetch.form = %%-fetch-option-form-%%
+### option: ApiRequestContext.fetch.multipart = %%-fetch-option-multipart-%%
-### option: FetchRequest.fetch.form = %%-fetch-option-form-%%
-
-### option: FetchRequest.fetch.multipart = %%-fetch-option-multipart-%%
-
-### option: FetchRequest.fetch.timeout
+### option: ApiRequestContext.fetch.timeout
- `timeout` <[float]>
Request timeout in milliseconds.
-### option: FetchRequest.fetch.failOnStatusCode
+### option: ApiRequestContext.fetch.failOnStatusCode
- `failOnStatusCode` <[boolean]>
Whether to throw on response codes other than 2xx and 3xx. By default response object is returned
for all status codes.
-### option: FetchRequest.fetch.ignoreHTTPSErrors = %%-context-option-ignorehttpserrors-%%
+### option: ApiRequestContext.fetch.ignoreHTTPSErrors = %%-context-option-ignorehttpserrors-%%
+
-## async method: FetchRequest.get
-- returns: <[FetchResponse]>
+## async method: ApiRequestContext.get
+- returns: <[ApiResponse]>
Sends HTTP(S) GET request and returns its response. The method will populate fetch cookies from the context and update
context cookies from the response. The method will automatically follow redirects.
-### param: FetchRequest.get.url
+### param: ApiRequestContext.get.url
- `url` <[string]>
Target URL.
-### option: FetchRequest.get.params
+### option: ApiRequestContext.get.params
- `params` <[Object]<[string], [string]>>
Query parameters to be send with the URL.
-### option: FetchRequest.get.headers
+### option: ApiRequestContext.get.headers
- `headers` <[Object]<[string], [string]>>
Allows to set HTTP headers.
-### option: FetchRequest.get.timeout
+### option: ApiRequestContext.get.timeout
- `timeout` <[float]>
Request timeout in milliseconds.
-### option: FetchRequest.get.failOnStatusCode
+### option: ApiRequestContext.get.failOnStatusCode
- `failOnStatusCode` <[boolean]>
Whether to throw on response codes other than 2xx and 3xx. By default response object is returned
for all status codes.
-### option: FetchRequest.get.ignoreHTTPSErrors = %%-context-option-ignorehttpserrors-%%
+### option: ApiRequestContext.get.ignoreHTTPSErrors = %%-context-option-ignorehttpserrors-%%
-## async method: FetchRequest.post
-- returns: <[FetchResponse]>
+## async method: ApiRequestContext.post
+- returns: <[ApiResponse]>
Sends HTTP(S) fetch and returns its response. The method will populate fetch cookies from the context and update
context cookies from the response. The method will automatically follow redirects.
-### param: FetchRequest.post.url
+### param: ApiRequestContext.post.url
- `url` <[string]>
Target URL.
-### option: FetchRequest.post.params
+### option: ApiRequestContext.post.params
- `params` <[Object]<[string], [string]>>
Query parameters to be send with the URL.
-### option: FetchRequest.post.headers
+### option: ApiRequestContext.post.headers
- `headers` <[Object]<[string], [string]>>
Allows to set HTTP headers.
-### option: FetchRequest.post.data = %%-fetch-option-data-%%
+### option: ApiRequestContext.post.data = %%-fetch-option-data-%%
-### option: FetchRequest.post.form = %%-fetch-option-form-%%
+### option: ApiRequestContext.post.form = %%-fetch-option-form-%%
-### option: FetchRequest.post.multipart = %%-fetch-option-multipart-%%
+### option: ApiRequestContext.post.multipart = %%-fetch-option-multipart-%%
-### option: FetchRequest.post.timeout
+### option: ApiRequestContext.post.timeout
- `timeout` <[float]>
Request timeout in milliseconds.
-### option: FetchRequest.post.failOnStatusCode
+### option: ApiRequestContext.post.failOnStatusCode
- `failOnStatusCode` <[boolean]>
Whether to throw on response codes other than 2xx and 3xx. By default response object is returned
for all status codes.
-### option: FetchRequest.post.ignoreHTTPSErrors = %%-context-option-ignorehttpserrors-%%
+### option: ApiRequestContext.post.ignoreHTTPSErrors = %%-context-option-ignorehttpserrors-%%
-## async method: FetchRequest.storageState
+## async method: ApiRequestContext.storageState
- returns: <[Object]>
- `cookies` <[Array]<[Object]>>
- `name` <[string]>
@@ -150,4 +149,4 @@ for all status codes.
Returns storage state for this request context, contains current cookies and local storage snapshot if it was passed to the constructor.
-### option: FetchRequest.storageState.path = %%-storagestate-option-path-%%
+### option: ApiRequestContext.storageState.path = %%-storagestate-option-path-%%
diff --git a/docs/src/api/class-fetchresponse.md b/docs/src/api/class-apiresponse.md
similarity index 74%
rename from docs/src/api/class-fetchresponse.md
rename to docs/src/api/class-apiresponse.md
index 6c5ee6342a..b2e32df641 100644
--- a/docs/src/api/class-fetchresponse.md
+++ b/docs/src/api/class-apiresponse.md
@@ -1,23 +1,23 @@
-# class: FetchResponse
+# class: ApiResponse
* langs: js
-[FetchResponse] class represents responses received from [`method: FetchRequest.fetch`].
+[ApiResponse] class represents responses received from [`method: ApiRequestContext.fetch`].
-## async method: FetchResponse.body
+## async method: ApiResponse.body
- returns: <[Buffer]>
Returns the buffer with response body.
-## async method: FetchResponse.dispose
+## async method: ApiResponse.dispose
Disposes the body of this response. If not called then the body will stay in memory until the context closes.
-## method: FetchResponse.headers
+## method: ApiResponse.headers
- returns: <[Object]<[string], [string]>>
An object with all the response HTTP headers associated with this response.
-## method: FetchResponse.headersArray
+## method: ApiResponse.headersArray
- returns: <[Array]<[Object]>>
- `name` <[string]> Name of the header.
- `value` <[string]> Value of the header.
@@ -25,7 +25,7 @@ An object with all the response HTTP headers associated with this response.
An array with all the request 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.
-## async method: FetchResponse.json
+## async method: ApiResponse.json
* langs: js, python
- returns: <[Serializable]>
@@ -33,7 +33,7 @@ Returns the JSON representation of response body.
This method will throw if the response body is not parsable via `JSON.parse`.
-## async method: FetchResponse.json
+## async method: ApiResponse.json
* langs: csharp
- returns: <[null]|[JsonElement]>
@@ -41,27 +41,27 @@ Returns the JSON representation of response body.
This method will throw if the response body is not parsable via `JSON.parse`.
-## method: FetchResponse.ok
+## method: ApiResponse.ok
- returns: <[boolean]>
Contains a boolean stating whether the response was successful (status in the range 200-299) or not.
-## method: FetchResponse.status
+## method: ApiResponse.status
- returns: <[int]>
Contains the status code of the response (e.g., 200 for a success).
-## method: FetchResponse.statusText
+## method: ApiResponse.statusText
- returns: <[string]>
Contains the status text of the response (e.g. usually an "OK" for a success).
-## async method: FetchResponse.text
+## async method: ApiResponse.text
- returns: <[string]>
Returns the text representation of response body.
-## method: FetchResponse.url
+## method: ApiResponse.url
- returns: <[string]>
Contains the URL of the response.
diff --git a/docs/src/api/class-browsercontext.md b/docs/src/api/class-browsercontext.md
index 9a2adb200c..7ee8ba6265 100644
--- a/docs/src/api/class-browsercontext.md
+++ b/docs/src/api/class-browsercontext.md
@@ -851,7 +851,7 @@ Returns all open pages in the context.
## property: BrowserContext.request
* langs: js
-- type: <[FetchRequest]>
+- type: <[ApiRequestContext]>
API testing helper associated with this context. Requests made with this API will use context cookies.
diff --git a/docs/src/api/class-page.md b/docs/src/api/class-page.md
index 2cef4864a4..85fb9bb244 100644
--- a/docs/src/api/class-page.md
+++ b/docs/src/api/class-page.md
@@ -2416,7 +2416,7 @@ last redirect.
## property: Page.request
* langs: js
-- type: <[FetchRequest]>
+- type: <[ApiRequestContext]>
API testing helper associated with this page. Requests made with this API will use page cookies.
diff --git a/docs/src/api/class-playwright.md b/docs/src/api/class-playwright.md
index b6e293d029..ad6bb1c67e 100644
--- a/docs/src/api/class-playwright.md
+++ b/docs/src/api/class-playwright.md
@@ -214,56 +214,11 @@ except TimeoutError as e:
This object can be used to launch or connect to Firefox, returning instances of [Browser].
-## async method: Playwright.newRequest
+## property: Playwright.request
* langs: js
-- returns: <[FetchRequest]>
+- type: <[ApiRequest]>
-**experimental** Creates new instances of [FetchRequest].
-
-### option: Playwright.newRequest.useragent = %%-context-option-useragent-%%
-
-### option: Playwright.newRequest.extraHTTPHeaders = %%-context-option-extrahttpheaders-%%
-
-### option: Playwright.newRequest.httpCredentials = %%-context-option-httpcredentials-%%
-
-### option: Playwright.newRequest.proxy = %%-browser-option-proxy-%%
-
-### option: Playwright.newRequest.timeout
-- `timeout` <[float]>
-
-Maximum time in milliseconds to wait for the response. Defaults to
-`30000` (30 seconds). Pass `0` to disable timeout.
-
-### option: Playwright.newRequest.ignoreHTTPSErrors = %%-context-option-ignorehttpserrors-%%
-
-### option: Playwright.newRequest.baseURL
-- `baseURL` <[string]>
-
-When using [`method: FetchRequest.get`], [`method: FetchRequest.post`], [`method: FetchRequest.fetch`] 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. Examples:
-* baseURL: `http://localhost:3000` and sending rquest to `/bar.html` results in `http://localhost:3000/bar.html`
-* baseURL: `http://localhost:3000/foo/` and sending rquest to `./bar.html` results in `http://localhost:3000/foo/bar.html`
-
-### option: Playwright.newRequest.storageState
-- `storageState` <[path]|[Object]>
- - `cookies` <[Array]<[Object]>>
- - `name` <[string]>
- - `value` <[string]>
- - `domain` <[string]>
- - `path` <[string]>
- - `expires` <[float]> Unix time in seconds.
- - `httpOnly` <[boolean]>
- - `secure` <[boolean]>
- - `sameSite` <[SameSiteAttribute]<"Strict"|"Lax"|"None">>
- - `origins` <[Array]<[Object]>>
- - `origin` <[string]>
- - `localStorage` <[Array]<[Object]>>
- - `name` <[string]>
- - `value` <[string]>
-
-Populates context with given storage state. This option can be used to initialize context with logged-in information
-obtained via [`method: BrowserContext.storageState`] or [`method: FetchRequest.storageState`]. Either a path to the
-file with saved storage, or the value returned by one of [`method: BrowserContext.storageState`] or
-[`method: FetchRequest.storageState`] methods.
+Exposes API that can be used for the Web API testing.
## property: Playwright.selectors
- type: <[Selectors]>
diff --git a/docs/src/api/class-route.md b/docs/src/api/class-route.md
index eb2a5f806a..c4af7b88b8 100644
--- a/docs/src/api/class-route.md
+++ b/docs/src/api/class-route.md
@@ -222,9 +222,9 @@ is resolved relative to the current working directory.
### option: Route.fulfill.response
* langs: js
-- `response` <[FetchResponse]>
+- `response` <[ApiResponse]>
-[FetchResponse] to fulfill route's request with. Individual fields of the response (such as headers) can be overridden using fulfill options.
+[ApiResponse] to fulfill route's request with. Individual fields of the response (such as headers) can be overridden using fulfill options.
## method: Route.request
- returns: <[Request]>
diff --git a/src/client/api.ts b/src/client/api.ts
index 3fb9dac488..6668582423 100644
--- a/src/client/api.ts
+++ b/src/client/api.ts
@@ -34,7 +34,7 @@ export { Frame } from './frame';
export { Keyboard, Mouse, Touchscreen } from './input';
export { JSHandle } from './jsHandle';
export { Request, Response, Route, WebSocket } from './network';
-export { FetchRequest, FetchResponse } from './fetch';
+export { Fetch as ApiRequest, FetchRequest as ApiRequestContext, FetchResponse as ApiResponse } from './fetch';
export { Page } from './page';
export { Selectors } from './selectors';
export { Tracing } from './tracing';
diff --git a/src/client/fetch.ts b/src/client/fetch.ts
index 4af738da19..eb9b6c2be9 100644
--- a/src/client/fetch.ts
+++ b/src/client/fetch.ts
@@ -27,6 +27,7 @@ import { ChannelOwner } from './channelOwner';
import * as network from './network';
import { RawHeaders } from './network';
import { FilePayload, Headers, StorageState } from './types';
+import { Playwright } from './playwright';
export type FetchOptions = {
params?: { [key: string]: string; },
@@ -40,7 +41,32 @@ export type FetchOptions = {
ignoreHTTPSErrors?: boolean,
};
-export class FetchRequest extends ChannelOwner<channels.FetchRequestChannel, channels.FetchRequestInitializer> implements api.FetchRequest {
+type NewContextOptions = Omit<channels.PlaywrightNewRequestOptions, 'extraHTTPHeaders' | 'storageState'> & {
+ extraHTTPHeaders?: Headers,
+ storageState?: string | StorageState,
+};
+
+export class Fetch implements api.ApiRequest {
+ private _playwright: Playwright;
+ constructor(playwright: Playwright) {
+ this._playwright = playwright;
+ }
+
+ async newContext(options: NewContextOptions = {}): Promise<FetchRequest> {
+ return await this._playwright._wrapApiCall(async (channel: channels.PlaywrightChannel) => {
+ const storageState = typeof options.storageState === 'string' ?
+ JSON.parse(await fs.promises.readFile(options.storageState, 'utf8')) :
+ options.storageState;
+ return FetchRequest.from((await channel.newRequest({
+ ...options,
+ extraHTTPHeaders: options.extraHTTPHeaders ? headersObjectToArray(options.extraHTTPHeaders) : undefined,
+ storageState,
+ })).request);
+ });
+ }
+}
+
+export class FetchRequest extends ChannelOwner<channels.FetchRequestChannel, channels.FetchRequestInitializer> implements api.ApiRequestContext {
static from(channel: channels.FetchRequestChannel): FetchRequest {
return (channel as any)._object;
}
@@ -153,7 +179,7 @@ export class FetchRequest extends ChannelOwner<channels.FetchRequestChannel, cha
}
}
-export class FetchResponse implements api.FetchResponse {
+export class FetchResponse implements api.ApiResponse {
private readonly _initializer: channels.FetchResponse;
private readonly _headers: RawHeaders;
private readonly _request: FetchRequest;
diff --git a/src/client/network.ts b/src/client/network.ts
index 8ba5de14b6..a1d7ed36fa 100644
--- a/src/client/network.ts
+++ b/src/client/network.ts
@@ -320,7 +320,7 @@ export class Route extends ChannelOwner<channels.RouteChannel, channels.RouteIni
});
}
- async fulfill(options: { response?: api.Response | api.FetchResponse, status?: number, headers?: Headers, contentType?: string, body?: string | Buffer, path?: string } = {}) {
+ async fulfill(options: { response?: api.Response | api.ApiResponse, status?: number, headers?: Headers, contentType?: string, body?: string | Buffer, path?: string } = {}) {
return this._wrapApiCall(async (channel: channels.RouteChannel) => {
let useInterceptedResponseBody;
let fetchResponseUid;
diff --git a/src/client/playwright.ts b/src/client/playwright.ts
index bbf0290b78..d862944b86 100644
--- a/src/client/playwright.ts
+++ b/src/client/playwright.ts
@@ -15,20 +15,18 @@
*/
import dns from 'dns';
-import fs from 'fs';
import net from 'net';
import util from 'util';
import * as channels from '../protocol/channels';
import { TimeoutError } from '../utils/errors';
import { createSocket } from '../utils/netUtils';
-import { headersObjectToArray } from '../utils/utils';
import { Android } from './android';
import { BrowserType } from './browserType';
import { ChannelOwner } from './channelOwner';
import { Electron } from './electron';
-import { FetchRequest } from './fetch';
+import { Fetch } from './fetch';
import { Selectors, SelectorsOwner, sharedSelectors } from './selectors';
-import { NewRequestOptions, Size } from './types';
+import { Size } from './types';
const dnsLookupAsync = util.promisify(dns.lookup);
type DeviceDescriptor = {
@@ -49,6 +47,7 @@ export class Playwright extends ChannelOwner<channels.PlaywrightChannel, channel
readonly webkit: BrowserType;
readonly devices: Devices;
readonly selectors: Selectors;
+ readonly request: Fetch;
readonly errors: { TimeoutError: typeof TimeoutError };
private _selectorsOwner: SelectorsOwner;
private _sockets = new Map<string, net.Socket>();
@@ -56,6 +55,7 @@ export class Playwright extends ChannelOwner<channels.PlaywrightChannel, channel
constructor(parent: ChannelOwner, type: string, guid: string, initializer: channels.PlaywrightInitializer) {
super(parent, type, guid, initializer);
+ this.request = new Fetch(this);
this.chromium = BrowserType.from(initializer.chromium);
this.firefox = BrowserType.from(initializer.firefox);
this.webkit = BrowserType.from(initializer.webkit);
@@ -71,19 +71,6 @@ export class Playwright extends ChannelOwner<channels.PlaywrightChannel, channel
this.selectors._addChannel(this._selectorsOwner);
}
- async newRequest(options: NewRequestOptions = {}): Promise<FetchRequest> {
- return await this._wrapApiCall(async (channel: channels.PlaywrightChannel) => {
- const storageState = typeof options.storageState === 'string' ?
- JSON.parse(await fs.promises.readFile(options.storageState, 'utf8')) :
- options.storageState;
- return FetchRequest.from((await channel.newRequest({
- ...options,
- extraHTTPHeaders: options.extraHTTPHeaders ? headersObjectToArray(options.extraHTTPHeaders) : undefined,
- storageState,
- })).request);
- });
- }
-
_enablePortForwarding(redirectPortForTest?: number) {
this._redirectPortForTest = redirectPortForTest;
this._channel.on('socksRequested', ({ uid, host, port }) => this._onSocksRequested(uid, host, port));
diff --git a/src/client/types.ts b/src/client/types.ts
index 8bae20de73..353ccbbe2c 100644
--- a/src/client/types.ts
+++ b/src/client/types.ts
@@ -118,8 +118,3 @@ export type SelectorEngine = {
export type RemoteAddr = channels.RemoteAddr;
export type SecurityDetails = channels.SecurityDetails;
-
-export type NewRequestOptions = Omit<channels.PlaywrightNewRequestOptions, 'extraHTTPHeaders' | 'storageState'> & {
- extraHTTPHeaders?: Headers,
- storageState?: string | StorageState,
-};
diff --git a/tests/browsercontext-fetch.spec.ts b/tests/browsercontext-fetch.spec.ts
index ed23bc92d9..d1c0d334b7 100644
--- a/tests/browsercontext-fetch.spec.ts
+++ b/tests/browsercontext-fetch.spec.ts
@@ -885,4 +885,4 @@ it('context request should export same storage state as context', async ({ conte
expect(requestState).toEqual(contextState);
const pageState = await page.request.storageState();
expect(pageState).toEqual(contextState);
-});
\ No newline at end of file
+});
diff --git a/tests/global-fetch-cookie.spec.ts b/tests/global-fetch-cookie.spec.ts
index 841d75345e..24167e5563 100644
--- a/tests/global-fetch-cookie.spec.ts
+++ b/tests/global-fetch-cookie.spec.ts
@@ -16,23 +16,23 @@
import fs from 'fs';
import http from 'http';
-import { FetchRequest } from '../index';
+import { ApiRequestContext } from '../index';
import { expect, playwrightTest } from './config/browserTest';
export type GlobalFetchFixtures = {
- request: FetchRequest;
+ request: ApiRequestContext;
};
const it = playwrightTest.extend<GlobalFetchFixtures>({
request: async ({ playwright }, use) => {
- const request = await playwright.newRequest({ ignoreHTTPSErrors: true });
+ const request = await playwright.request.newContext({ ignoreHTTPSErrors: true });
await use(request);
await request.dispose();
},
});
type PromiseArg<T> = T extends Promise<infer R> ? R : never;
-type StorageStateType = PromiseArg<ReturnType<FetchRequest['storageState']>>;
+type StorageStateType = PromiseArg<ReturnType<ApiRequestContext['storageState']>>;
it.skip(({ mode }) => mode !== 'default');
@@ -235,7 +235,7 @@ it('should preserve local storage on import/export of storage state', async ({ p
},
]
};
- const request = await playwright.newRequest({ storageState });
+ const request = await playwright.request.newContext({ storageState });
await request.get(server.EMPTY_PAGE);
const exportedState = await request.storageState();
expect(exportedState).toEqual(storageState);
@@ -279,7 +279,7 @@ it('should send cookies from storage state', async ({ playwright, server }) => {
],
'origins': []
};
- const request = await playwright.newRequest({ storageState });
+ const request = await playwright.request.newContext({ storageState });
const [serverRequest] = await Promise.all([
server.waitForRequest('/first/second/third/not_found.html'),
request.get(`http://www.a.b.one.com:${server.PORT}/first/second/third/not_found.html`)
@@ -304,7 +304,7 @@ it('storage state should round-trip through file', async ({ playwright, server }
'origins': []
};
- const request1 = await playwright.newRequest({ storageState });
+ const request1 = await playwright.request.newContext({ storageState });
const path = testInfo.outputPath('storage-state.json');
const state1 = await request1.storageState({ path });
expect(state1).toEqual(storageState);
@@ -312,7 +312,7 @@ it('storage state should round-trip through file', async ({ playwright, server }
const written = await fs.promises.readFile(path, 'utf8');
expect(JSON.stringify(state1, undefined, 2)).toBe(written);
- const request2 = await playwright.newRequest({ storageState: path });
+ const request2 = await playwright.request.newContext({ storageState: path });
const state2 = await request2.storageState();
expect(state2).toEqual(storageState);
});
diff --git a/tests/global-fetch.spec.ts b/tests/global-fetch.spec.ts
index e53608be4f..2ec950e300 100644
--- a/tests/global-fetch.spec.ts
+++ b/tests/global-fetch.spec.ts
@@ -40,7 +40,7 @@ it.afterAll(() => {
for (const method of ['get', 'post', 'fetch']) {
it(`${method} should work`, async ({ playwright, server }) => {
- const request = await playwright.newRequest();
+ const request = await playwright.request.newContext();
const response = await request[method](server.PREFIX + '/simple.json');
expect(response.url()).toBe(server.PREFIX + '/simple.json');
expect(response.status()).toBe(200);
@@ -53,7 +53,7 @@ for (const method of ['get', 'post', 'fetch']) {
});
it(`should dispose global ${method} request`, async function({ playwright, context, server }) {
- const request = await playwright.newRequest();
+ const request = await playwright.request.newContext();
const response = await request.get(server.PREFIX + '/simple.json');
expect(await response.json()).toEqual({ foo: 'bar' });
await request.dispose();
@@ -63,7 +63,7 @@ for (const method of ['get', 'post', 'fetch']) {
}
it('should support global userAgent option', async ({ playwright, server }) => {
- const request = await playwright.newRequest({ userAgent: 'My Agent' });
+ const request = await playwright.request.newContext({ userAgent: 'My Agent' });
const [serverRequest, response] = await Promise.all([
server.waitForRequest('/empty.html'),
request.get(server.EMPTY_PAGE)
@@ -74,7 +74,7 @@ it('should support global userAgent option', async ({ playwright, server }) => {
});
it('should support global timeout option', async ({ playwright, server }) => {
- const request = await playwright.newRequest({ timeout: 1 });
+ const request = await playwright.request.newContext({ timeout: 1 });
server.setRoute('/empty.html', (req, res) => {});
const error = await request.get(server.EMPTY_PAGE).catch(e => e);
expect(error.message).toContain('Request timed out after 1ms');
@@ -83,7 +83,7 @@ it('should support global timeout option', async ({ playwright, server }) => {
it('should propagate extra http headers with redirects', async ({ playwright, server }) => {
server.setRedirect('/a/redirect1', '/b/c/redirect2');
server.setRedirect('/b/c/redirect2', '/simple.json');
- const request = await playwright.newRequest({ extraHTTPHeaders: { 'My-Secret': 'Value' } });
+ const request = await playwright.request.newContext({ extraHTTPHeaders: { 'My-Secret': 'Value' } });
const [req1, req2, req3] = await Promise.all([
server.waitForRequest('/a/redirect1'),
server.waitForRequest('/b/c/redirect2'),
@@ -97,12 +97,12 @@ it('should propagate extra http headers with redirects', async ({ playwright, se
it('should support global httpCredentials option', async ({ playwright, server }) => {
server.setAuth('/empty.html', 'user', 'pass');
- const request1 = await playwright.newRequest();
+ const request1 = await playwright.request.newContext();
const response1 = await request1.get(server.EMPTY_PAGE);
expect(response1.status()).toBe(401);
await request1.dispose();
- const request2 = await playwright.newRequest({ httpCredentials: { username: 'user', password: 'pass' } });
+ const request2 = await playwright.request.newContext({ httpCredentials: { username: 'user', password: 'pass' } });
const response2 = await request2.get(server.EMPTY_PAGE);
expect(response2.status()).toBe(200);
await request2.dispose();
@@ -110,7 +110,7 @@ it('should support global httpCredentials option', async ({ playwright, server }
it('should return error with wrong credentials', async ({ playwright, server }) => {
server.setAuth('/empty.html', 'user', 'pass');
- const request = await playwright.newRequest({ httpCredentials: { username: 'user', password: 'wrong' } });
+ const request = await playwright.request.newContext({ httpCredentials: { username: 'user', password: 'wrong' } });
const response2 = await request.get(server.EMPTY_PAGE);
expect(response2.status()).toBe(401);
});
@@ -122,7 +122,7 @@ it('should pass proxy credentials', async ({ playwright, server, proxyServer })
auth = req.headers['proxy-authorization'];
return !!auth;
});
- const request = await playwright.newRequest({
+ const request = await playwright.request.newContext({
proxy: { server: `localhost:${proxyServer.PORT}`, username: 'user', password: 'secret' }
});
const response = await request.get('http://non-existent.com/simple.json');
@@ -133,19 +133,19 @@ it('should pass proxy credentials', async ({ playwright, server, proxyServer })
});
it('should support global ignoreHTTPSErrors option', async ({ playwright, httpsServer }) => {
- const request = await playwright.newRequest({ ignoreHTTPSErrors: true });
+ const request = await playwright.request.newContext({ ignoreHTTPSErrors: true });
const response = await request.get(httpsServer.EMPTY_PAGE);
expect(response.status()).toBe(200);
});
it('should resolve url relative to gobal baseURL option', async ({ playwright, server }) => {
- const request = await playwright.newRequest({ baseURL: server.PREFIX });
+ const request = await playwright.request.newContext({ baseURL: server.PREFIX });
const response = await request.get('/empty.html');
expect(response.url()).toBe(server.EMPTY_PAGE);
});
it('should set playwright as user-agent', async ({ playwright, server }) => {
- const request = await playwright.newRequest();
+ const request = await playwright.request.newContext();
const [serverRequest] = await Promise.all([
server.waitForRequest('/empty.html'),
request.get(server.EMPTY_PAGE)
diff --git a/tests/page/page-request-fulfill.spec.ts b/tests/page/page-request-fulfill.spec.ts
index 3fab893ba0..a20ce630f1 100644
--- a/tests/page/page-request-fulfill.spec.ts
+++ b/tests/page/page-request-fulfill.spec.ts
@@ -197,7 +197,7 @@ it('should include the origin header', async ({ page, server, isAndroid }) => {
it('should fulfill with global fetch result', async ({ playwright, page, server, isElectron }) => {
it.fixme(isElectron, 'error: Browser context management is not supported.');
await page.route('**/*', async route => {
- const request = await playwright.newRequest();
+ const request = await playwright.request.newContext();
const response = await request.get(server.PREFIX + '/simple.json');
route.fulfill({ response });
});
@@ -277,7 +277,7 @@ it('should fulfill with fetch response that has multiple set-cookie', async ({ p
res.end();
});
await page.route('**/empty.html', async route => {
- const request = await playwright.newRequest();
+ const request = await playwright.request.newContext();
const response = await request.fetch(route.request());
route.fulfill({ response });
});
diff --git a/types/types.d.ts b/types/types.d.ts
index 28ff99f817..116e50e777 100644
--- a/types/types.d.ts
+++ b/types/types.d.ts
@@ -2753,7 +2753,7 @@ export interface Page {
/**
* API testing helper associated with this page. Requests made with this API will use page cookies.
*/
- request: FetchRequest;
+ request: ApiRequestContext;
/**
* Routing provides the capability to modify network requests that are made by a page.
@@ -6455,7 +6455,7 @@ export interface BrowserContext {
/**
* API testing helper associated with this context. Requests made with this API will use context cookies.
*/
- request: FetchRequest;
+ request: ApiRequestContext;
/**
* Routing provides the capability to modify network requests that are made by any page in the browser context. Once route
@@ -11590,192 +11590,32 @@ export interface AndroidWebView {
}
/**
- * - extends: [EventEmitter]
- *
- * A Browser is created via
- * [browserType.launch([options])](https://playwright.dev/docs/api/class-browsertype#browser-type-launch). An example of
- * using a [Browser] to create a [Page]:
- *
- * ```js
- * const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
- *
- * (async () => {
- * const browser = await firefox.launch();
- * const page = await browser.newPage();
- * await page.goto('https://example.com');
- * await browser.close();
- * })();
- * ```
- *
+ * Exposes API that can be used for the Web API testing.
*/
-export interface Browser extends EventEmitter {
- /**
- * Emitted when Browser gets disconnected from the browser application. This might happen because of one of the following:
- * - Browser application is closed or crashed.
- * - The [browser.close()](https://playwright.dev/docs/api/class-browser#browser-close) method was called.
- */
- on(event: 'disconnected', listener: (browser: Browser) => void): 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: 'disconnected', listener: (browser: Browser) => void): this;
-
- /**
- * Emitted when Browser gets disconnected from the browser application. This might happen because of one of the following:
- * - Browser application is closed or crashed.
- * - The [browser.close()](https://playwright.dev/docs/api/class-browser#browser-close) method was called.
- */
- addListener(event: 'disconnected', listener: (browser: Browser) => void): this;
-
- /**
- * Removes an event listener added by `on` or `addListener`.
- */
- removeListener(event: 'disconnected', listener: (browser: Browser) => void): this;
-
- /**
- * Removes an event listener added by `on` or `addListener`.
- */
- off(event: 'disconnected', listener: (browser: Browser) => void): this;
-
- /**
- * In case this browser is obtained using
- * [browserType.launch([options])](https://playwright.dev/docs/api/class-browsertype#browser-type-launch), closes the
- * browser and all of its pages (if any were opened).
- *
- * In case this browser is connected to, clears all created contexts belonging to this browser and disconnects from the
- * browser server.
- *
- * The [Browser] object itself is considered to be disposed and cannot be used anymore.
- */
- close(): Promise<void>;
-
- /**
- * Returns an array of all open browser contexts. In a newly created browser, this will return zero browser contexts.
- *
- * ```js
- * const browser = await pw.webkit.launch();
- * console.log(browser.contexts().length); // prints `0`
- *
- * const context = await browser.newContext();
- * console.log(browser.contexts().length); // prints `1`
- * ```
- *
- */
- contexts(): Array<BrowserContext>;
-
- /**
- * Indicates that the browser is connected.
- */
- isConnected(): boolean;
-
- /**
- * > NOTE: CDP Sessions are only supported on Chromium-based browsers.
- *
- * Returns the newly created browser session.
- */
- newBrowserCDPSession(): Promise<CDPSession>;
-
- /**
- * Creates a new browser context. It won't share cookies/cache with other browser contexts.
- *
- * ```js
- * (async () => {
- * const browser = await playwright.firefox.launch(); // Or 'chromium' or 'webkit'.
- * // Create a new incognito browser context.
- * const context = await browser.newContext();
- * // Create a new page in a pristine context.
- * const page = await context.newPage();
- * await page.goto('https://example.com');
- * })();
- * ```
- *
- * @param options
- */
- newContext(options?: BrowserContextOptions): Promise<BrowserContext>;
-
+export interface ApiRequest {
/**
- * Creates a new page in a new browser context. Closing this page will close the context as well.
- *
- * This is a convenience API that should only be used for the single-page scenarios and short snippets. Production code and
- * testing frameworks should explicitly create
- * [browser.newContext([options])](https://playwright.dev/docs/api/class-browser#browser-new-context) followed by the
- * [browserContext.newPage()](https://playwright.dev/docs/api/class-browsercontext#browser-context-new-page) to control
- * their exact life times.
+ * **experimental** Creates new instances of [ApiRequestContext].
* @param options
*/
- newPage(options?: {
- /**
- * Whether to automatically download all the attachments. Defaults to `false` where all the downloads are canceled.
- */
- acceptDownloads?: boolean;
-
+ newContext(options?: {
/**
- * 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)
+ * When using
+ * [apiRequestContext.get(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-get),
+ * [apiRequestContext.post(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-post),
+ * [apiRequestContext.fetch(urlOrRequest[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-fetch)
+ * 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. 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` and sending rquest to `/bar.html` results in `http://localhost:3000/bar.html`
+ * - baseURL: `http://localhost:3000/foo/` and sending rquest to `./bar.html` results in
+ * `http://localhost:3000/foo/bar.html`
*/
baseURL?: string;
- /**
- * Toggles bypassing page's Content-Security-Policy.
- */
- bypassCSP?: boolean;
-
- /**
- * Emulates `'prefers-colors-scheme'` media feature, supported values are `'light'`, `'dark'`, `'no-preference'`. See
- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details. Defaults
- * to `'light'`.
- */
- colorScheme?: "light"|"dark"|"no-preference";
-
- /**
- * Specify device scale factor (can be thought of as dpr). Defaults to `1`.
- */
- deviceScaleFactor?: number;
-
/**
* An object containing additional HTTP headers to be sent with every request.
*/
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. Defaults
- * to `'none'`.
- *
- * > NOTE: It's not supported in WebKit, see [here](https://bugs.webkit.org/show_bug.cgi?id=225281) in their issue tracker.
- */
- forcedColors?: "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;
- };
-
- /**
- * Specifies if viewport supports touch events. Defaults to false.
- */
- hasTouch?: boolean;
-
/**
* Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
*/
@@ -11791,45 +11631,7 @@ export interface Browser extends EventEmitter {
ignoreHTTPSErrors?: boolean;
/**
- * Whether the `meta viewport` tag is taken into account and touch events are enabled. Defaults to `false`. Not supported
- * in Firefox.
- */
- isMobile?: boolean;
-
- /**
- * Whether or not to enable JavaScript in the context. Defaults to `true`.
- */
- javaScriptEnabled?: boolean;
-
- /**
- * 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.
- */
- locale?: string;
-
- /**
- * Logger sink for Playwright logging.
- */
- logger?: Logger;
-
- /**
- * Whether to emulate network being offline. Defaults to `false`.
- */
- offline?: boolean;
-
- /**
- * 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.
- */
- permissions?: Array<string>;
-
- /**
- * Network proxy settings to use with this context.
- *
- * > NOTE: For Chromium on Windows the browser needs to be launched with the global proxy for this option to work. If all
- * contexts override the proxy, global proxy will be never used and can be any string, for example `launch({ proxy: {
- * server: 'http://per-context' } })`.
+ * Network proxy settings.
*/
proxy?: {
/**
@@ -11855,130 +11657,40 @@ export interface Browser extends EventEmitter {
};
/**
- * 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()](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for the HAR to be
- * saved.
+ * 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.
*/
- recordHar?: {
- /**
- * Optional setting to control whether to omit request content from the HAR. Defaults to `false`.
- */
- omitContent?: boolean;
+ storageState?: string|{
+ cookies: Array<{
+ name: string;
- /**
- * Path on the filesystem to write the HAR file to.
- */
- path: string;
- };
+ value: string;
- /**
- * Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded. Make
- * sure to await [browserContext.close()](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for
- * videos to be saved.
- */
- recordVideo?: {
- /**
- * Path to the directory to put videos into.
- */
- dir: string;
+ domain: 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.
- */
- size?: {
- /**
- * Video frame width.
- */
- width: number;
+ path: string;
/**
- * Video frame height.
+ * Unix time in seconds.
*/
- height: number;
- };
- };
+ expires: number;
- /**
- * 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. Defaults
- * to `'no-preference'`.
- */
- reducedMotion?: "reduce"|"no-preference";
-
- /**
- * Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the `viewport`
- * is set.
- */
- screen?: {
- /**
- * page width in pixels.
- */
- width: number;
-
- /**
- * page height in pixels.
- */
- height: number;
- };
-
- /**
- * 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).
- * Either a path to the file with saved storage, or an object with the following fields:
- */
- storageState?: string|{
- /**
- * Optional cookies to set for context
- */
- cookies?: Array<{
- name: string;
-
- value: string;
-
- /**
- * Optional either url or domain / path are required
- */
- url?: string;
-
- /**
- * Optional either url or domain / path are required
- */
- domain?: string;
-
- /**
- * Optional either url or domain / path are required
- */
- path?: string;
-
- /**
- * Optional Unix time in seconds.
- */
- expires?: number;
+ httpOnly: boolean;
- /**
- * Optional httpOnly flag
- */
- httpOnly?: boolean;
-
- /**
- * Optional secure flag
- */
- secure?: boolean;
+ secure: boolean;
- /**
- * Optional sameSite flag
- */
- sameSite?: "Strict"|"Lax"|"None";
+ sameSite: "Strict"|"Lax"|"None";
}>;
- /**
- * Optional localStorage to set for context
- */
- origins?: Array<{
+ origins: Array<{
origin: string;
localStorage: Array<{
@@ -11990,981 +11702,1392 @@ export interface Browser extends EventEmitter {
};
/**
- * It specified, 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. See [Locator] to learn
- * more about the strict mode.
+ * Maximum time in milliseconds to wait for the response. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
*/
- strictSelectors?: boolean;
+ timeout?: number;
/**
- * 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.
+ * Specific user agent to use in this context.
*/
- timezoneId?: string;
+ 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. When used on [Page] or a [BrowserContext], this API will automatically use
+ * the cookies from the corresponding [BrowserContext]. This means that if you log in using this API, your e2e test will be
+ * logged in and vice versa.
+ */
+export interface ApiRequestContext {
+ /**
+ * All responses received through
+ * [apiRequestContext.fetch(urlOrRequest[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-fetch),
+ * [apiRequestContext.get(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-get),
+ * [apiRequestContext.post(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-post)
+ * and other 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
+ * stored responses, and makes [apiResponse.body()](https://playwright.dev/docs/api/class-apiresponse#api-response-body)
+ * throw "Response disposed" error.
+ */
+ dispose(): Promise<void>;
+ /**
+ * Sends HTTP(S) fetch and returns its response. The method will populate fetch cookies from the context and update context
+ * cookies from the response. The method will automatically follow redirects.
+ * @param urlOrRequest Target URL or Request to get all fetch parameters from.
+ * @param options
+ */
+ fetch(urlOrRequest: string|Request, options?: {
/**
- * Specific user agent to use in this context.
+ * 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.
*/
- userAgent?: string;
+ data?: string|Buffer|Serializable;
/**
- * **DEPRECATED** Use `recordVideo` instead.
- * @deprecated
+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.
*/
- videoSize?: {
- /**
- * Video frame width.
- */
- width: number;
+ failOnStatusCode?: boolean;
- /**
- * Video frame height.
- */
- height: number;
- };
+ /**
+ * 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; };
/**
- * **DEPRECATED** Use `recordVideo` instead.
- * @deprecated
+ * Allows to set HTTP headers.
*/
- videosPath?: string;
+ headers?: { [key: string]: string; };
/**
- * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. `null` disables the default viewport.
+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
*/
- viewport?: null|{
+ ignoreHTTPSErrors?: boolean;
+
+ /**
+ * If set changes the fetch method (e.g. PUT or POST). If not specified, GET method is used.
+ */
+ method?: 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?: { [key: string]: string|number|boolean|ReadStream|{
/**
- * page width in pixels.
+ * File name
*/
- width: number;
+ name: string;
/**
- * page height in pixels.
+ * File type
*/
- height: number;
- };
- }): Promise<Page>;
+ mimeType: string;
+
+ /**
+ * File content
+ */
+ buffer: Buffer;
+ }; };
+
+ /**
+ * Query parameters to be send with the URL.
+ */
+ params?: { [key: string]: string; };
+
+ /**
+ * Request timeout in milliseconds.
+ */
+ timeout?: number;
+ }): Promise<ApiResponse>;
/**
- * > NOTE: This API controls [Chromium Tracing](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool)
- * which is a low-level chromium-specific debugging tool. API to control [Playwright Tracing](../trace-viewer) could be
- * found [here](https://playwright.dev/docs/class-tracing).
- *
- * You can use [browser.startTracing([page, options])](https://playwright.dev/docs/api/class-browser#browser-start-tracing)
- * and [browser.stopTracing()](https://playwright.dev/docs/api/class-browser#browser-stop-tracing) to create a trace file
- * that can be opened in Chrome DevTools performance panel.
- *
- * ```js
- * await browser.startTracing(page, {path: 'trace.json'});
- * await page.goto('https://www.google.com');
- * await browser.stopTracing();
- * ```
- *
- * @param page Optional, if specified, tracing includes screenshots of the given page.
+ * Sends HTTP(S) GET request and returns its response. The method will populate fetch cookies from the context and update
+ * context cookies from the response. The method will automatically follow redirects.
+ * @param url Target URL.
* @param options
*/
- startTracing(page?: Page, options?: {
+ get(url: string, options?: {
/**
- * specify custom categories to use instead of default.
+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.
*/
- categories?: Array<string>;
+ failOnStatusCode?: boolean;
/**
- * A path to write the trace file to.
+ * Allows to set HTTP headers.
*/
- path?: string;
+ headers?: { [key: string]: string; };
/**
- * captures screenshots in the trace.
+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
*/
- screenshots?: boolean;
- }): Promise<void>;
+ ignoreHTTPSErrors?: boolean;
- /**
- * > NOTE: This API controls [Chromium Tracing](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool)
- * which is a low-level chromium-specific debugging tool. API to control [Playwright Tracing](../trace-viewer) could be
- * found [here](https://playwright.dev/docs/class-tracing).
- *
- * Returns the buffer with trace data.
- */
- stopTracing(): Promise<Buffer>;
+ /**
+ * Query parameters to be send with the URL.
+ */
+ params?: { [key: string]: string; };
- /**
- * Returns the browser version.
- */
- version(): string;
-}
+ /**
+ * Request timeout in milliseconds.
+ */
+ timeout?: number;
+ }): Promise<ApiResponse>;
-export interface BrowserServer {
/**
- * Emitted when the browser server closes.
+ * Sends HTTP(S) fetch and returns its response. The method will populate fetch cookies from the context and update context
+ * cookies from the response. The method will automatically follow redirects.
+ * @param url Target URL.
+ * @param options
*/
- on(event: 'close', listener: () => void): this;
+ 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;
- /**
- * 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: () => void): this;
+ /**
+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.
+ */
+ failOnStatusCode?: boolean;
- /**
- * Emitted when the browser server closes.
- */
- addListener(event: 'close', listener: () => void): this;
+ /**
+ * 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; };
+
+ /**
+ * Allows to set HTTP headers.
+ */
+ headers?: { [key: string]: string; };
+
+ /**
+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
+ */
+ ignoreHTTPSErrors?: 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.
+ */
+ multipart?: { [key: string]: string|number|boolean|ReadStream|{
+ /**
+ * File name
+ */
+ name: string;
+
+ /**
+ * File type
+ */
+ mimeType: string;
+
+ /**
+ * File content
+ */
+ buffer: Buffer;
+ }; };
+
+ /**
+ * Query parameters to be send with the URL.
+ */
+ params?: { [key: string]: string; };
+
+ /**
+ * Request timeout in milliseconds.
+ */
+ timeout?: number;
+ }): Promise<ApiResponse>;
/**
- * Removes an event listener added by `on` or `addListener`.
+ * Returns storage state for this request context, contains current cookies and local storage snapshot if it was passed to
+ * the constructor.
+ * @param options
*/
- removeListener(event: 'close', listener: () => void): this;
+ storageState(options?: {
+ /**
+ * The file path to save the storage state to. If `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;
+ }>;
+ }>;
+ }>;
+}
+/**
+ * [ApiResponse] class represents responses received from
+ * [apiRequestContext.fetch(urlOrRequest[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-fetch).
+ */
+export interface ApiResponse {
/**
- * Removes an event listener added by `on` or `addListener`.
+ * Returns the buffer with response body.
*/
- off(event: 'close', listener: () => void): this;
+ body(): Promise<Buffer>;
/**
- * Closes the browser gracefully and makes sure the process is terminated.
+ * Disposes the body of this response. If not called then the body will stay in memory until the context closes.
*/
- close(): Promise<void>;
+ dispose(): Promise<void>;
/**
- * Kills the browser process and waits for the process to exit.
+ * An object with all the response HTTP headers associated with this response.
*/
- kill(): Promise<void>;
+ headers(): { [key: string]: string; };
/**
- * Spawned browser application process.
+ * An array with all the request 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.
*/
- process(): ChildProcess;
+ headersArray(): Array<{
+ /**
+ * Name of the header.
+ */
+ name: string;
+
+ /**
+ * Value of the header.
+ */
+ value: string;
+ }>;
/**
- * Browser websocket url.
+ * Returns the JSON representation of response body.
*
- * Browser websocket endpoint which can be used as an argument to
- * [browserType.connect(wsEndpoint[, options])](https://playwright.dev/docs/api/class-browsertype#browser-type-connect) to
- * establish connection to the browser.
+ * This method will throw if the response body is not parsable via `JSON.parse`.
*/
- wsEndpoint(): string;
-}
+ json(): Promise<Serializable>;
-/**
- * [ConsoleMessage] objects are dispatched by page via the
- * [page.on('console')](https://playwright.dev/docs/api/class-page#page-event-console) event.
- */
-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).
+ * Contains a boolean stating whether the response was successful (status in the range 200-299) or not.
*/
- args(): Array<JSHandle>;
-
- location(): {
- /**
- * URL of the resource.
- */
- url: string;
+ ok(): boolean;
- /**
- * 0-based line number in the resource.
- */
- lineNumber: number;
+ /**
+ * Contains the status code of the response (e.g., 200 for a success).
+ */
+ status(): number;
- /**
- * 0-based column number in the resource.
- */
- columnNumber: number;
- };
+ /**
+ * Contains the status text of the response (e.g. usually an "OK" for a success).
+ */
+ statusText(): string;
/**
- * The text of the console message.
+ * Returns the text representation of response body.
*/
- text(): string;
+ text(): Promise<string>;
/**
- * One of the following values: `'log'`, `'debug'`, `'info'`, `'error'`, `'warning'`, `'dir'`, `'dirxml'`, `'table'`,
- * `'trace'`, `'clear'`, `'startGroup'`, `'startGroupCollapsed'`, `'endGroup'`, `'assert'`, `'profile'`, `'profileEnd'`,
- * `'count'`, `'timeEnd'`.
+ * Contains the URL of the response.
*/
- type(): string;
+ url(): string;
}
/**
- * 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:
+ * - extends: [EventEmitter]
*
- * > NOTE: Coverage APIs are only supported on Chromium-based browsers.
+ * A Browser is created via
+ * [browserType.launch([options])](https://playwright.dev/docs/api/class-browsertype#browser-type-launch). An example of
+ * using a [Browser] to create a [Page]:
*
* ```js
- * const { chromium } = require('playwright');
- * const v8toIstanbul = require('v8-to-istanbul');
+ * const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
*
- * (async() => {
- * const browser = await chromium.launch();
+ * (async () => {
+ * const browser = await firefox.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 = new v8toIstanbul('', 0, { source: entry.source });
- * await converter.load();
- * converter.applyCoverage(entry.functions);
- * console.log(JSON.stringify(converter.toIstanbul()));
- * }
+ * await page.goto('https://example.com');
* await browser.close();
* })();
* ```
*
*/
-export interface Coverage {
+export interface Browser extends EventEmitter {
/**
- * Returns coverage is started
- * @param options
+ * Emitted when Browser gets disconnected from the browser application. This might happen because of one of the following:
+ * - Browser application is closed or crashed.
+ * - The [browser.close()](https://playwright.dev/docs/api/class-browser#browser-close) method was called.
*/
- startCSSCoverage(options?: {
- /**
- * Whether to reset coverage on every navigation. Defaults to `true`.
- */
- resetOnNavigation?: boolean;
- }): Promise<void>;
+ on(event: 'disconnected', listener: (browser: Browser) => void): this;
/**
- * 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` is set to `true`, anonymous scripts will have
- * `__playwright_evaluation_script__` as their URL.
- * @param options
+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.
*/
- startJSCoverage(options?: {
- /**
- * Whether anonymous scripts generated by the page should be reported. Defaults to `false`.
- */
- reportAnonymousScripts?: boolean;
+ once(event: 'disconnected', listener: (browser: Browser) => void): this;
- /**
- * Whether to reset coverage on every navigation. Defaults to `true`.
- */
- resetOnNavigation?: boolean;
- }): Promise<void>;
+ /**
+ * Emitted when Browser gets disconnected from the browser application. This might happen because of one of the following:
+ * - Browser application is closed or crashed.
+ * - The [browser.close()](https://playwright.dev/docs/api/class-browser#browser-close) method was called.
+ */
+ addListener(event: 'disconnected', listener: (browser: Browser) => void): this;
/**
- * Returns the array of coverage reports for all stylesheets
- *
- * > NOTE: CSS Coverage doesn't include dynamically injected style tags without sourceURLs.
+ * Removes an event listener added by `on` or `addListener`.
*/
- stopCSSCoverage(): Promise<Array<{
- /**
- * StyleSheet URL
- */
- url: string;
+ removeListener(event: 'disconnected', listener: (browser: Browser) => void): this;
- /**
- * StyleSheet content, if available.
- */
- text?: string;
+ /**
+ * Removes an event listener added by `on` or `addListener`.
+ */
+ off(event: 'disconnected', listener: (browser: Browser) => void): this;
- /**
- * StyleSheet ranges that were used. Ranges are sorted and non-overlapping.
+ /**
+ * In case this browser is obtained using
+ * [browserType.launch([options])](https://playwright.dev/docs/api/class-browsertype#browser-type-launch), closes the
+ * browser and all of its pages (if any were opened).
+ *
+ * In case this browser is connected to, clears all created contexts belonging to this browser and disconnects from the
+ * browser server.
+ *
+ * The [Browser] object itself is considered to be disposed and cannot be used anymore.
+ */
+ close(): Promise<void>;
+
+ /**
+ * Returns an array of all open browser contexts. In a newly created browser, this will return zero browser contexts.
+ *
+ * ```js
+ * const browser = await pw.webkit.launch();
+ * console.log(browser.contexts().length); // prints `0`
+ *
+ * const context = await browser.newContext();
+ * console.log(browser.contexts().length); // prints `1`
+ * ```
+ *
+ */
+ contexts(): Array<BrowserContext>;
+
+ /**
+ * Indicates that the browser is connected.
+ */
+ isConnected(): boolean;
+
+ /**
+ * > NOTE: CDP Sessions are only supported on Chromium-based browsers.
+ *
+ * Returns the newly created browser session.
+ */
+ newBrowserCDPSession(): Promise<CDPSession>;
+
+ /**
+ * Creates a new browser context. It won't share cookies/cache with other browser contexts.
+ *
+ * ```js
+ * (async () => {
+ * const browser = await playwright.firefox.launch(); // Or 'chromium' or 'webkit'.
+ * // Create a new incognito browser context.
+ * const context = await browser.newContext();
+ * // Create a new page in a pristine context.
+ * const page = await context.newPage();
+ * await page.goto('https://example.com');
+ * })();
+ * ```
+ *
+ * @param options
+ */
+ newContext(options?: BrowserContextOptions): Promise<BrowserContext>;
+
+ /**
+ * Creates a new page in a new browser context. Closing this page will close the context as well.
+ *
+ * This is a convenience API that should only be used for the single-page scenarios and short snippets. Production code and
+ * testing frameworks should explicitly create
+ * [browser.newContext([options])](https://playwright.dev/docs/api/class-browser#browser-new-context) followed by the
+ * [browserContext.newPage()](https://playwright.dev/docs/api/class-browsercontext#browser-context-new-page) to control
+ * their exact life times.
+ * @param options
+ */
+ newPage(options?: {
+ /**
+ * Whether to automatically download all the attachments. Defaults to `false` where all the downloads are canceled.
*/
- ranges: Array<{
+ acceptDownloads?: boolean;
+
+ /**
+ * 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. 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?: string;
+
+ /**
+ * Toggles bypassing page's Content-Security-Policy.
+ */
+ bypassCSP?: boolean;
+
+ /**
+ * Emulates `'prefers-colors-scheme'` media feature, supported values are `'light'`, `'dark'`, `'no-preference'`. See
+ * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details. Defaults
+ * to `'light'`.
+ */
+ colorScheme?: "light"|"dark"|"no-preference";
+
+ /**
+ * Specify device scale factor (can be thought of as dpr). Defaults to `1`.
+ */
+ deviceScaleFactor?: number;
+
+ /**
+ * An object containing additional HTTP headers to be sent with every request.
+ */
+ 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. Defaults
+ * to `'none'`.
+ *
+ * > NOTE: It's not supported in WebKit, see [here](https://bugs.webkit.org/show_bug.cgi?id=225281) in their issue tracker.
+ */
+ forcedColors?: "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;
+ };
+
+ /**
+ * Specifies if viewport supports touch events. Defaults to false.
+ */
+ hasTouch?: boolean;
+
+ /**
+ * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
+ */
+ httpCredentials?: {
+ username: string;
+
+ password: string;
+ };
+
+ /**
+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
+ */
+ ignoreHTTPSErrors?: boolean;
+
+ /**
+ * Whether the `meta viewport` tag is taken into account and touch events are enabled. Defaults to `false`. Not supported
+ * in Firefox.
+ */
+ isMobile?: boolean;
+
+ /**
+ * Whether or not to enable JavaScript in the context. Defaults to `true`.
+ */
+ javaScriptEnabled?: boolean;
+
+ /**
+ * 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.
+ */
+ locale?: string;
+
+ /**
+ * Logger sink for Playwright logging.
+ */
+ logger?: Logger;
+
+ /**
+ * Whether to emulate network being offline. Defaults to `false`.
+ */
+ offline?: boolean;
+
+ /**
+ * 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.
+ */
+ permissions?: Array<string>;
+
+ /**
+ * Network proxy settings to use with this context.
+ *
+ * > NOTE: For Chromium on Windows the browser needs to be launched with the global proxy for this option to work. If all
+ * contexts override the proxy, global proxy will be never used and can be any string, for example `launch({ proxy: {
+ * server: 'http://per-context' } })`.
+ */
+ 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;
+
+ /**
+ * Optional coma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.
+ */
+ bypass?: string;
+
+ /**
+ * 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()](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`.
+ */
+ omitContent?: boolean;
+
+ /**
+ * Path on the filesystem to write the HAR file to.
+ */
+ path: string;
+ };
+
+ /**
+ * Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded. Make
+ * sure to await [browserContext.close()](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for
+ * videos to be saved.
+ */
+ recordVideo?: {
+ /**
+ * Path to the directory to put videos into.
+ */
+ dir: 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.
+ */
+ size?: {
+ /**
+ * Video frame width.
+ */
+ width: number;
+
+ /**
+ * Video frame height.
+ */
+ height: number;
+ };
+ };
+
+ /**
+ * 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. Defaults
+ * to `'no-preference'`.
+ */
+ reducedMotion?: "reduce"|"no-preference";
+
+ /**
+ * Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the `viewport`
+ * is set.
+ */
+ screen?: {
+ /**
+ * page width in pixels.
+ */
+ width: number;
+
+ /**
+ * page height in pixels.
+ */
+ height: number;
+ };
+
+ /**
+ * 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).
+ * Either a path to the file with saved storage, or an object with the following fields:
+ */
+ storageState?: string|{
+ /**
+ * Optional cookies to set for context
+ */
+ cookies?: Array<{
+ name: string;
+
+ value: string;
+
+ /**
+ * Optional either url or domain / path are required
+ */
+ url?: string;
+
+ /**
+ * Optional either url or domain / path are required
+ */
+ domain?: string;
+
+ /**
+ * Optional either url or domain / path are required
+ */
+ path?: string;
+
+ /**
+ * Optional Unix time in seconds.
+ */
+ expires?: number;
+
+ /**
+ * Optional httpOnly flag
+ */
+ httpOnly?: boolean;
+
+ /**
+ * Optional secure flag
+ */
+ secure?: boolean;
+
+ /**
+ * Optional sameSite flag
+ */
+ sameSite?: "Strict"|"Lax"|"None";
+ }>;
+
+ /**
+ * Optional localStorage to set for context
+ */
+ origins?: Array<{
+ origin: string;
+
+ localStorage: Array<{
+ name: string;
+
+ value: string;
+ }>;
+ }>;
+ };
+
+ /**
+ * It specified, 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. See [Locator] to learn
+ * more about the strict mode.
+ */
+ strictSelectors?: boolean;
+
+ /**
+ * 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.
+ */
+ timezoneId?: string;
+
+ /**
+ * Specific user agent to use in this context.
+ */
+ userAgent?: string;
+
+ /**
+ * **DEPRECATED** Use `recordVideo` instead.
+ * @deprecated
+ */
+ videoSize?: {
+ /**
+ * Video frame width.
+ */
+ width: number;
+
+ /**
+ * Video frame height.
+ */
+ height: number;
+ };
+
+ /**
+ * **DEPRECATED** Use `recordVideo` instead.
+ * @deprecated
+ */
+ videosPath?: string;
+
+ /**
+ * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. `null` disables the default viewport.
+ */
+ viewport?: null|{
/**
- * A start offset in text, inclusive
+ * page width in pixels.
*/
- start: number;
+ width: number;
/**
- * An end offset in text, exclusive
+ * page height in pixels.
*/
- end: number;
- }>;
- }>>;
+ height: number;
+ };
+ }): Promise<Page>;
/**
- * Returns the array of coverage reports for all scripts
+ * > NOTE: This API controls [Chromium Tracing](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool)
+ * which is a low-level chromium-specific debugging tool. API to control [Playwright Tracing](../trace-viewer) could be
+ * found [here](https://playwright.dev/docs/class-tracing).
*
- * > NOTE: JavaScript Coverage doesn't include anonymous scripts by default. However, scripts with sourceURLs are reported.
+ * You can use [browser.startTracing([page, options])](https://playwright.dev/docs/api/class-browser#browser-start-tracing)
+ * and [browser.stopTracing()](https://playwright.dev/docs/api/class-browser#browser-stop-tracing) to create a trace file
+ * that can be opened in Chrome DevTools performance panel.
+ *
+ * ```js
+ * await browser.startTracing(page, {path: 'trace.json'});
+ * await page.goto('https://www.google.com');
+ * await browser.stopTracing();
+ * ```
+ *
+ * @param page Optional, if specified, tracing includes screenshots of the given page.
+ * @param options
*/
- stopJSCoverage(): Promise<Array<{
- /**
- * Script URL
- */
- url: string;
-
+ startTracing(page?: Page, options?: {
/**
- * Script ID
+ * specify custom categories to use instead of default.
*/
- scriptId: string;
+ categories?: Array<string>;
/**
- * Script content, if applicable.
+ * A path to write the trace file to.
*/
- source?: string;
+ path?: string;
/**
- * V8-specific coverage format.
+ * captures screenshots in the trace.
*/
- functions: Array<{
- functionName: string;
-
- isBlockCoverage: boolean;
-
- ranges: Array<{
- count: number;
-
- startOffset: number;
-
- endOffset: number;
- }>;
- }>;
- }>>;
-}
+ screenshots?: boolean;
+ }): Promise<void>;
-/**
- * [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.
+ * > NOTE: This API controls [Chromium Tracing](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool)
+ * which is a low-level chromium-specific debugging tool. API to control [Playwright Tracing](../trace-viewer) could be
+ * found [here](https://playwright.dev/docs/class-tracing).
+ *
+ * Returns the buffer with trace data.
*/
- accept(promptText?: string): Promise<void>;
+ stopTracing(): Promise<Buffer>;
/**
- * If dialog is prompt, returns default prompt value. Otherwise, returns empty string.
+ * Returns the browser version.
*/
- defaultValue(): string;
+ version(): string;
+}
+export interface BrowserServer {
/**
- * Returns when the dialog has been dismissed.
+ * Emitted when the browser server closes.
*/
- dismiss(): Promise<void>;
+ on(event: 'close', listener: () => void): this;
/**
- * A message displayed in the dialog.
+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.
*/
- message(): string;
+ once(event: 'close', listener: () => void): this;
/**
- * Returns dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`.
+ * Emitted when the browser server closes.
*/
- type(): string;
-}
+ addListener(event: 'close', listener: () => void): this;
-/**
- * [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
- * const [ download ] = await Promise.all([
- * page.waitForEvent('download'), // wait for download to start
- * page.click('a')
- * ]);
- * // wait for download to complete
- * const path = await download.path();
- * ```
- *
- * > NOTE: Browser context **must** be created with the `acceptDownloads` set to `true` when user needs access to the
- * downloaded content. If `acceptDownloads` is not set, download events are emitted, but the actual download is not
- * performed and user has no access to the downloaded files.
- */
-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'`.
+ * Removes an event listener added by `on` or `addListener`.
*/
- cancel(): Promise<void>;
+ removeListener(event: 'close', listener: () => void): this;
/**
- * Returns readable stream for current download or `null` if download failed.
+ * Removes an event listener added by `on` or `addListener`.
*/
- createReadStream(): Promise<null|Readable>;
+ off(event: 'close', listener: () => void): this;
/**
- * Deletes the downloaded file. Will wait for the download to finish if necessary.
+ * Closes the browser gracefully and makes sure the process is terminated.
*/
- delete(): Promise<void>;
+ close(): Promise<void>;
/**
- * Returns download error if any. Will wait for the download to finish if necessary.
+ * Kills the browser process and waits for the process to exit.
*/
- failure(): Promise<null|string>;
+ kill(): Promise<void>;
/**
- * Get the page that the download belongs to.
+ * Spawned browser application process.
*/
- page(): Page;
+ process(): ChildProcess;
/**
- * Returns path to the downloaded file in case of successful download. The method will wait for the download to finish if
- * necessary. The method throws when connected remotely.
+ * Browser websocket url.
*
- * 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.
+ * Browser websocket endpoint which can be used as an argument to
+ * [browserType.connect(wsEndpoint[, options])](https://playwright.dev/docs/api/class-browsertype#browser-type-connect) to
+ * establish connection to the browser.
*/
- path(): Promise<null|string>;
+ wsEndpoint(): string;
+}
+/**
+ * [ConsoleMessage] objects are dispatched by page via the
+ * [page.on('console')](https://playwright.dev/docs/api/class-page#page-event-console) event.
+ */
+export interface ConsoleMessage {
/**
- * 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.
- * @param path Path where the download should be copied.
+ * List of arguments passed to a `console` function call. See also
+ * [page.on('console')](https://playwright.dev/docs/api/class-page#page-event-console).
*/
- saveAs(path: string): Promise<void>;
+ args(): Array<JSHandle>;
+
+ location(): {
+ /**
+ * URL of the resource.
+ */
+ url: string;
+
+ /**
+ * 0-based line number in the resource.
+ */
+ lineNumber: number;
+
+ /**
+ * 0-based column number in the resource.
+ */
+ columnNumber: number;
+ };
/**
- * 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.
+ * The text of the console message.
*/
- suggestedFilename(): string;
+ text(): string;
/**
- * Returns downloaded url.
+ * One of the following values: `'log'`, `'debug'`, `'info'`, `'error'`, `'warning'`, `'dir'`, `'dirxml'`, `'table'`,
+ * `'trace'`, `'clear'`, `'startGroup'`, `'startGroupCollapsed'`, `'endGroup'`, `'assert'`, `'profile'`, `'profileEnd'`,
+ * `'count'`, `'timeEnd'`.
*/
- url(): string;
+ type(): string;
}
-/**
- * Playwright has **experimental** support for Electron automation. You can access electron namespace via:
- *
- * ```js
- * const { _electron } = require('playwright');
- * ```
- *
- * An example of the Electron automation script would be:
- *
- * ```js
- * const { _electron: electron } = require('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();
- * })();
- * ```
+/**
+ * Coverage gathers information about parts of JavaScript and CSS that were used by the page.
*
- * Note that since you don't need Playwright to install web browsers when testing Electron, you can omit browser download
- * via setting the following environment variable when installing Playwright:
+ * An example of using JavaScript coverage to produce Istanbul report for page load:
*
- * ```bash js
- * PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm i -D playwright
+ * > 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 = new v8toIstanbul('', 0, { source: entry.source });
+ * await converter.load();
+ * converter.applyCoverage(entry.functions);
+ * console.log(JSON.stringify(converter.toIstanbul()));
+ * }
+ * await browser.close();
+ * })();
* ```
*
*/
-export interface Electron {
+export interface Coverage {
/**
- * Launches electron application specified with the `executablePath`.
+ * Returns coverage is started
* @param options
*/
- launch(options?: {
- /**
- * Whether to automatically download all the attachments. Defaults to `false` where all the downloads are canceled.
- */
- acceptDownloads?: boolean;
-
- /**
- * Additional arguments to pass to the application when launching. You typically pass the main script name here.
- */
- args?: Array<string>;
-
+ startCSSCoverage(options?: {
/**
- * Toggles bypassing page's Content-Security-Policy.
+ * Whether to reset coverage on every navigation. Defaults to `true`.
*/
- bypassCSP?: boolean;
+ 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` is set to `true`, anonymous scripts will have
+ * `__playwright_evaluation_script__` as their URL.
+ * @param options
+ */
+ startJSCoverage(options?: {
/**
- * Emulates `'prefers-colors-scheme'` media feature, supported values are `'light'`, `'dark'`, `'no-preference'`. See
- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details. Defaults
- * to `'light'`.
+ * Whether anonymous scripts generated by the page should be reported. Defaults to `false`.
*/
- colorScheme?: "light"|"dark"|"no-preference";
+ reportAnonymousScripts?: boolean;
/**
- * Current working directory to launch application from.
+ * Whether to reset coverage on every navigation. Defaults to `true`.
*/
- cwd?: string;
+ 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<{
/**
- * Specifies environment variables that will be visible to Electron. Defaults to `process.env`.
+ * StyleSheet URL
*/
- env?: { [key: string]: string; };
+ url: string;
/**
- * Launches given Electron application. If not specified, launches the default Electron executable installed in this
- * package, located at `node_modules/.bin/electron`.
+ * StyleSheet content, if available.
*/
- executablePath?: string;
+ text?: string;
/**
- * An object containing additional HTTP headers to be sent with every request.
+ * StyleSheet ranges that were used. Ranges are sorted and non-overlapping.
*/
- extraHTTPHeaders?: { [key: string]: string; };
-
- geolocation?: {
- /**
- * Latitude between -90 and 90.
- */
- latitude: number;
-
+ ranges: Array<{
/**
- * Longitude between -180 and 180.
+ * A start offset in text, inclusive
*/
- longitude: number;
+ start: number;
/**
- * Non-negative accuracy value. Defaults to `0`.
+ * An end offset in text, exclusive
*/
- accuracy?: number;
- };
+ 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<{
/**
- * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
+ * Script URL
*/
- httpCredentials?: {
- username: string;
-
- password: string;
- };
+ url: string;
/**
- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
+ * Script ID
*/
- ignoreHTTPSErrors?: boolean;
+ scriptId: string;
/**
- * 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.
+ * Script content, if applicable.
*/
- locale?: string;
+ source?: string;
/**
- * Whether to emulate network being offline. Defaults to `false`.
+ * V8-specific coverage format.
*/
- offline?: boolean;
+ functions: Array<{
+ functionName: 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()](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`.
- */
- omitContent?: boolean;
+ isBlockCoverage: boolean;
- /**
- * Path on the filesystem to write the HAR file to.
- */
- path: string;
- };
+ ranges: Array<{
+ count: number;
- /**
- * Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded. Make
- * sure to await [browserContext.close()](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for
- * videos to be saved.
- */
- recordVideo?: {
- /**
- * Path to the directory to put videos into.
- */
- dir: string;
+ startOffset: 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;
+ endOffset: number;
+ }>;
+ }>;
+ }>>;
+}
- /**
- * Video frame height.
- */
- height: number;
- };
- };
+/**
+ * [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 time in milliseconds to wait for the application to start. Defaults to `30000` (30 seconds). Pass `0` to disable
- * timeout.
- */
- timeout?: number;
+ /**
+ * If dialog is prompt, returns default prompt value. Otherwise, returns empty string.
+ */
+ defaultValue(): string;
- /**
- * 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.
- */
- timezoneId?: string;
- }): Promise<ElectronApplication>;
+ /**
+ * Returns when the dialog has been dismissed.
+ */
+ dismiss(): Promise<void>;
+
+ /**
+ * A message displayed in the dialog.
+ */
+ message(): string;
+
+ /**
+ * Returns dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`.
+ */
+ type(): string;
}
/**
- * This API is used for Web API testing. You can use it to trigger API endpoints, configure micro-services, prepare
- * environment or the service to your e2e test. When used on [Page] or a [BrowserContext], this API will automatically use
- * the cookies from the corresponding [BrowserContext]. This means that if you log in using this API, your e2e test will be
- * logged in and vice versa.
+ * [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
+ * const [ download ] = await Promise.all([
+ * page.waitForEvent('download'), // wait for download to start
+ * page.click('a')
+ * ]);
+ * // wait for download to complete
+ * const path = await download.path();
+ * ```
+ *
+ * > NOTE: Browser context **must** be created with the `acceptDownloads` set to `true` when user needs access to the
+ * downloaded content. If `acceptDownloads` is not set, download events are emitted, but the actual download is not
+ * performed and user has no access to the downloaded files.
*/
-export interface FetchRequest {
+export interface Download {
/**
- * All responses received through
- * [fetchRequest.fetch(urlOrRequest[, options])](https://playwright.dev/docs/api/class-fetchrequest#fetch-request-fetch),
- * [fetchRequest.get(url[, options])](https://playwright.dev/docs/api/class-fetchrequest#fetch-request-get),
- * [fetchRequest.post(url[, options])](https://playwright.dev/docs/api/class-fetchrequest#fetch-request-post) and other
- * methods are stored in the memory, so that you can later call
- * [fetchResponse.body()](https://playwright.dev/docs/api/class-fetchresponse#fetch-response-body). This method discards
- * all stored responses, and makes
- * [fetchResponse.body()](https://playwright.dev/docs/api/class-fetchresponse#fetch-response-body) throw "Response
- * disposed" error.
+ * Cancels a download. Will not fail if the download is already finished or canceled. Upon successful cancellations,
+ * `download.failure()` would resolve to `'canceled'`.
*/
- dispose(): Promise<void>;
+ cancel(): Promise<void>;
/**
- * Sends HTTP(S) fetch and returns its response. The method will populate fetch cookies from the context and update context
- * cookies from the response. The method will automatically follow redirects.
- * @param urlOrRequest Target URL or Request to get all fetch parameters from.
- * @param options
+ * Returns readable stream for current download or `null` if download failed.
*/
- 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.
- */
- 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; };
-
- /**
- * Allows to set HTTP headers.
- */
- headers?: { [key: string]: string; };
+ createReadStream(): Promise<null|Readable>;
- /**
- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
- */
- ignoreHTTPSErrors?: boolean;
+ /**
+ * Deletes the downloaded file. Will wait for the download to finish if necessary.
+ */
+ delete(): Promise<void>;
- /**
- * If set changes the fetch method (e.g. PUT or POST). If not specified, GET method is used.
- */
- method?: string;
+ /**
+ * Returns download error if any. Will wait for the download to finish if necessary.
+ */
+ failure(): Promise<null|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?: { [key: string]: string|number|boolean|ReadStream|{
- /**
- * File name
- */
- name: string;
+ /**
+ * Get the page that the download belongs to.
+ */
+ page(): Page;
- /**
- * File type
- */
- mimeType: string;
+ /**
+ * Returns path to the downloaded file in case of successful 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<null|string>;
- /**
- * File content
- */
- buffer: Buffer;
- }; };
+ /**
+ * 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.
+ * @param path Path where the download should be copied.
+ */
+ saveAs(path: string): Promise<void>;
- /**
- * Query parameters to be send with the URL.
- */
- params?: { [key: string]: string; };
+ /**
+ * 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;
- /**
- * Request timeout in milliseconds.
- */
- timeout?: number;
- }): Promise<FetchResponse>;
+ /**
+ * Returns downloaded url.
+ */
+ url(): string;
+}
+/**
+ * Playwright has **experimental** support for Electron automation. You can access electron namespace via:
+ *
+ * ```js
+ * const { _electron } = require('playwright');
+ * ```
+ *
+ * An example of the Electron automation script would be:
+ *
+ * ```js
+ * const { _electron: electron } = require('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();
+ * })();
+ * ```
+ *
+ * Note that since you don't need Playwright to install web browsers when testing Electron, you can omit browser download
+ * via setting the following environment variable when installing Playwright:
+ *
+ * ```bash js
+ * PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm i -D playwright
+ * ```
+ *
+ */
+export interface Electron {
/**
- * Sends HTTP(S) GET request and returns its response. The method will populate fetch cookies from the context and update
- * context cookies from the response. The method will automatically follow redirects.
- * @param url Target URL.
+ * Launches electron application specified with the `executablePath`.
* @param options
*/
- get(url: string, options?: {
- /**
- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.
- */
- failOnStatusCode?: boolean;
-
- /**
- * Allows to set HTTP headers.
- */
- headers?: { [key: string]: string; };
-
+ launch(options?: {
/**
- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
+ * Whether to automatically download all the attachments. Defaults to `false` where all the downloads are canceled.
*/
- ignoreHTTPSErrors?: boolean;
+ acceptDownloads?: boolean;
/**
- * Query parameters to be send with the URL.
+ * Additional arguments to pass to the application when launching. You typically pass the main script name here.
*/
- params?: { [key: string]: string; };
+ args?: Array<string>;
/**
- * Request timeout in milliseconds.
+ * Toggles bypassing page's Content-Security-Policy.
*/
- timeout?: number;
- }): Promise<FetchResponse>;
+ bypassCSP?: boolean;
- /**
- * Sends HTTP(S) fetch and returns its response. The method will populate fetch cookies from the context and update context
- * cookies from the response. The method will automatically follow redirects.
- * @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.
+ * Emulates `'prefers-colors-scheme'` media feature, supported values are `'light'`, `'dark'`, `'no-preference'`. See
+ * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details. Defaults
+ * to `'light'`.
*/
- data?: string|Buffer|Serializable;
+ colorScheme?: "light"|"dark"|"no-preference";
/**
- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status codes.
+ * Current working directory to launch application from.
*/
- failOnStatusCode?: boolean;
+ cwd?: 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.
+ * Specifies environment variables that will be visible to Electron. Defaults to `process.env`.
*/
- form?: { [key: string]: string|number|boolean; };
+ env?: { [key: string]: string; };
/**
- * Allows to set HTTP headers.
+ * Launches given Electron application. If not specified, launches the default Electron executable installed in this
+ * package, located at `node_modules/.bin/electron`.
*/
- headers?: { [key: string]: string; };
+ executablePath?: string;
/**
- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
+ * An object containing additional HTTP headers to be sent with every request.
*/
- ignoreHTTPSErrors?: boolean;
+ extraHTTPHeaders?: { [key: string]: 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?: { [key: string]: string|number|boolean|ReadStream|{
+ geolocation?: {
/**
- * File name
+ * Latitude between -90 and 90.
*/
- name: string;
+ latitude: number;
/**
- * File type
+ * Longitude between -180 and 180.
*/
- mimeType: string;
+ longitude: number;
/**
- * File content
- */
- buffer: Buffer;
- }; };
+ * Non-negative accuracy value. Defaults to `0`.
+ */
+ accuracy?: number;
+ };
/**
- * Query parameters to be send with the URL.
+ * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
*/
- params?: { [key: string]: string; };
+ httpCredentials?: {
+ username: string;
+
+ password: string;
+ };
/**
- * Request timeout in milliseconds.
+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
*/
- timeout?: number;
- }): Promise<FetchResponse>;
+ ignoreHTTPSErrors?: boolean;
- /**
- * Returns storage state for this request context, contains current cookies and local storage snapshot if it was passed to
- * the constructor.
- * @param options
- */
- storageState(options?: {
/**
- * The file path to save the storage state to. If `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.
+ * 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.
*/
- path?: string;
- }): Promise<{
- cookies: Array<{
- name: string;
+ locale?: string;
- value: string;
+ /**
+ * Whether to emulate network being offline. Defaults to `false`.
+ */
+ offline?: boolean;
- domain: 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()](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`.
+ */
+ omitContent?: boolean;
+ /**
+ * Path on the filesystem to write the HAR file to.
+ */
path: string;
+ };
+ /**
+ * Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded. Make
+ * sure to await [browserContext.close()](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for
+ * videos to be saved.
+ */
+ recordVideo?: {
/**
- * Unix time in seconds.
+ * Path to the directory to put videos into.
*/
- expires: number;
-
- httpOnly: boolean;
-
- secure: boolean;
-
- sameSite: "Strict"|"Lax"|"None";
- }>;
-
- origins: Array<{
- origin: string;
-
- localStorage: Array<{
- name: string;
-
- value: string;
- }>;
- }>;
- }>;
-}
-
-/**
- * [FetchResponse] class represents responses received from
- * [fetchRequest.fetch(urlOrRequest[, options])](https://playwright.dev/docs/api/class-fetchrequest#fetch-request-fetch).
- */
-export interface FetchResponse {
- /**
- * Returns the buffer with response body.
- */
- body(): Promise<Buffer>;
+ dir: string;
- /**
- * Disposes the body of this response. If not called then the body will stay in memory until the context closes.
- */
- dispose(): Promise<void>;
+ /**
+ * 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;
- /**
- * An object with all the response HTTP headers associated with this response.
- */
- headers(): { [key: string]: string; };
+ /**
+ * Video frame height.
+ */
+ height: number;
+ };
+ };
- /**
- * An array with all the request 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.
- */
- headersArray(): Array<{
/**
- * Name of the header.
+ * Maximum time in milliseconds to wait for the application to start. Defaults to `30000` (30 seconds). Pass `0` to disable
+ * timeout.
*/
- name: string;
+ timeout?: number;
/**
- * Value of the header.
+ * 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.
*/
- value: 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;
-
- /**
- * Contains the status code of the response (e.g., 200 for a success).
- */
- status(): number;
-
- /**
- * Contains the status text of the response (e.g. usually an "OK" for a success).
- */
- statusText(): string;
-
- /**
- * Returns the text representation of response body.
- */
- text(): Promise<string>;
-
- /**
- * Contains the URL of the response.
- */
- url(): string;
+ timezoneId?: string;
+ }): Promise<ElectronApplication>;
}
/**
@@ -13382,122 +13505,9 @@ export const chromium: BrowserType;
export const firefox: BrowserType;
/**
- * **experimental** Creates new instances of [FetchRequest].
- * @param options
+ * Exposes API that can be used for the Web API testing.
*/
-export const newRequest: (options?: {
- /**
- * When using [fetchRequest.get(url[, options])](https://playwright.dev/docs/api/class-fetchrequest#fetch-request-get),
- * [fetchRequest.post(url[, options])](https://playwright.dev/docs/api/class-fetchrequest#fetch-request-post),
- * [fetchRequest.fetch(urlOrRequest[, options])](https://playwright.dev/docs/api/class-fetchrequest#fetch-request-fetch) 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. Examples:
- * - baseURL: `http://localhost:3000` and sending rquest to `/bar.html` results in `http://localhost:3000/bar.html`
- * - baseURL: `http://localhost:3000/foo/` and sending rquest to `./bar.html` results in
- * `http://localhost:3000/foo/bar.html`
- */
- baseURL?: string;
-
- /**
- * An object containing additional HTTP headers to be sent with every request.
- */
- extraHTTPHeaders?: { [key: string]: string; };
-
- /**
- * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
- */
- httpCredentials?: {
- username: string;
-
- password: string;
- };
-
- /**
- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
- */
- ignoreHTTPSErrors?: boolean;
-
- /**
- * 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;
-
- /**
- * Optional coma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.
- */
- bypass?: string;
-
- /**
- * Optional username to use if HTTP proxy requires authentication.
- */
- username?: string;
-
- /**
- * Optional password to use if HTTP proxy requires authentication.
- */
- password?: string;
- };
-
- /**
- * 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
- * [fetchRequest.storageState([options])](https://playwright.dev/docs/api/class-fetchrequest#fetch-request-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
- * [fetchRequest.storageState([options])](https://playwright.dev/docs/api/class-fetchrequest#fetch-request-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<FetchRequest>;
+export const request: ApiRequest;
/**
* Selectors can be used to install custom selector engines. See [Working with selectors](https://playwright.dev/docs/selectors) for more
@@ -14021,10 +14031,10 @@ export interface Route {
path?: string;
/**
- * [FetchResponse] to fulfill route's request with. Individual fields of the response (such as headers) can be overridden
+ * [ApiResponse] to fulfill route's request with. Individual fields of the response (such as headers) can be overridden
* using fulfill options.
*/
- response?: FetchResponse;
+ response?: ApiResponse;
/**
* Response status code, defaults to `200`.