Skip to content

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

feat(events): allow waiting for removeAllListeners (#31941)

Pavel Feldman3c87f217df29
diff --git a/docs/src/api/class-browser.md b/docs/src/api/class-browser.md
index 9ae59571fc..8d1d2d99c1 100644
--- a/docs/src/api/class-browser.md
+++ b/docs/src/api/class-browser.md
@@ -296,6 +296,18 @@ testing frameworks should explicitly create [`method: Browser.newContext`] follo
### option: Browser.newPage.storageStatePath = %%-csharp-java-context-option-storage-state-path-%%
* since: v1.9
+## async method: Browser.removeAllListeners
+* since: v1.47
+
+Removes all the listeners of the given type if the type is given. Otherwise removes all the listeners.
+
+### param: Browser.removeAllListeners.type
+* since: v1.47
+- `type` ?<[string]>
+
+### option: Browser.removeAllListeners.behavior = %%-remove-all-listeners-options-behavior-%%
+* since: v1.47
+
## async method: Browser.startTracing
* since: v1.11
* langs: java, js, python
diff --git a/docs/src/api/class-browsercontext.md b/docs/src/api/class-browsercontext.md
index 48542a2603..cf7efd7af1 100644
--- a/docs/src/api/class-browsercontext.md
+++ b/docs/src/api/class-browsercontext.md
@@ -1016,6 +1016,18 @@ Creates a new page in the browser context.
Returns all open pages in the context.
+## async method: BrowserContext.removeAllListeners
+* since: v1.47
+
+Removes all the listeners of the given type if the type is given. Otherwise removes all the listeners.
+
+### param: BrowserContext.removeAllListeners.type
+* since: v1.47
+- `type` ?<[string]>
+
+### option: BrowserContext.removeAllListeners.behavior = %%-remove-all-listeners-options-behavior-%%
+* since: v1.47
+
## property: BrowserContext.request
* since: v1.16
* langs:
diff --git a/docs/src/api/class-page.md b/docs/src/api/class-page.md
index 7953952e30..47303634b0 100644
--- a/docs/src/api/class-page.md
+++ b/docs/src/api/class-page.md
@@ -3340,6 +3340,17 @@ Specifies the maximum number of times this handler should be called. Unlimited b
By default, after calling the handler Playwright will wait until the overlay becomes hidden, and only then Playwright will continue with the action/assertion that triggered the handler. This option allows to opt-out of this behavior, so that overlay can stay visible after the handler has run.
+## async method: Page.removeAllListeners
+* since: v1.47
+
+Removes all the listeners of the given type if the type is given. Otherwise removes all the listeners.
+
+### param: Page.removeAllListeners.type
+* since: v1.47
+- `type` ?<[string]>
+
+### option: Page.removeAllListeners.behavior = %%-remove-all-listeners-options-behavior-%%
+* since: v1.47
## async method: Page.removeLocatorHandler
* since: v1.44
diff --git a/docs/src/api/params.md b/docs/src/api/params.md
index 5a3a17d97e..1743066647 100644
--- a/docs/src/api/params.md
+++ b/docs/src/api/params.md
@@ -781,6 +781,16 @@ Whether to allow sites to register Service workers. Defaults to `'allow'`.
* `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be registered.
* `'block'`: Playwright will block all registration of Service Workers.
+## remove-all-listeners-options-behavior
+* langs: js
+* since: v1.47
+- `behavior` <[RemoveAllListenersBehavior]<"wait"|"ignoreErrors"|"default">>
+
+Specifies whether to wait for already running listeners and what to do if they throw errors:
+* `'default'` - do not wait for current listener calls (if any) to finish, if the listener throws, it may result in unhandled error
+* `'wait'` - wait for current listener calls (if any) to finish
+* `'ignoreErrors'` - do not wait for current listener calls (if any) to finish, all errors thrown by the listeners after removal are silently caught
+
## unroute-all-options-behavior
* langs: js, csharp, python
* since: v1.41
@@ -791,6 +801,7 @@ Specifies whether to wait for already running handlers and what to do if they th
* `'wait'` - wait for current handler calls (if any) to finish
* `'ignoreErrors'` - do not wait for current handler calls (if any) to finish, all errors thrown by the handlers after unrouting are silently caught
+
## select-options-values
* langs: java, js, csharp
- `values` <[null]|[string]|[ElementHandle]|[Array]<[string]>|[Object]|[Array]<[ElementHandle]>|[Array]<[Object]>>
diff --git a/packages/playwright-core/src/client/eventEmitter.ts b/packages/playwright-core/src/client/eventEmitter.ts
index 6de8ca3a31..c0375a70dc 100644
--- a/packages/playwright-core/src/client/eventEmitter.ts
+++ b/packages/playwright-core/src/client/eventEmitter.ts
@@ -23,7 +23,7 @@
*/
type EventType = string | symbol;
-type Listener = (...args: any[]) => void;
+type Listener = (...args: any[]) => any;
type EventMap = Record<EventType, Listener | Listener[]>;
import { EventEmitter as OriginalEventEmitter } from 'events';
import type { EventEmitter as EventEmitterType } from 'events';
@@ -34,6 +34,8 @@ export class EventEmitter implements EventEmitterType {
private _events: EventMap | undefined = undefined;
private _eventsCount = 0;
private _maxListeners: number | undefined = undefined;
+ readonly _pendingHandlers = new Map<EventType, Set<Promise<void>>>();
+ private _rejectionHandler: ((error: Error) => void) | undefined;
constructor() {
if (this._events === undefined || this._events === Object.getPrototypeOf(this)._events) {
@@ -66,17 +68,34 @@ export class EventEmitter implements EventEmitterType {
return false;
if (typeof handler === 'function') {
- Reflect.apply(handler, this, args);
+ this._callHandler(type, handler, args);
} else {
const len = handler.length;
const listeners = handler.slice();
for (let i = 0; i < len; ++i)
- Reflect.apply(listeners[i], this, args);
+ this._callHandler(type, listeners[i], args);
}
-
return true;
}
+ private _callHandler(type: EventType, handler: Listener, args: any[]): void {
+ const promise = Reflect.apply(handler, this, args);
+ if (!(promise instanceof Promise))
+ return;
+ let set = this._pendingHandlers.get(type);
+ if (!set) {
+ set = new Set();
+ this._pendingHandlers.set(type, set);
+ }
+ set.add(promise);
+ promise.catch(e => {
+ if (this._rejectionHandler)
+ this._rejectionHandler(e);
+ else
+ throw e;
+ }).finally(() => set.delete(promise));
+ }
+
addListener(type: EventType, listener: Listener): this {
return this._addListener(type, listener, false);
}
@@ -214,10 +233,34 @@ export class EventEmitter implements EventEmitterType {
return this.removeListener(type, listener);
}
- removeAllListeners(type?: string): this {
+ removeAllListeners(type?: EventType): this;
+ removeAllListeners(type: EventType | undefined, options: { behavior?: 'wait'|'ignoreErrors'|'default' }): Promise<void>;
+ removeAllListeners(type?: string, options?: { behavior?: 'wait'|'ignoreErrors'|'default' }): this | Promise<void> {
+ this._removeAllListeners(type);
+ if (!options)
+ return this;
+
+ if (options.behavior === 'wait') {
+ const errors: Error[] = [];
+ this._rejectionHandler = error => errors.push(error);
+ // eslint-disable-next-line internal-playwright/await-promise-in-class-returns
+ return this._waitFor(type).then(() => {
+ if (errors.length)
+ throw errors[0];
+ });
+ }
+
+ if (options.behavior === 'ignoreErrors')
+ this._rejectionHandler = () => {};
+
+ // eslint-disable-next-line internal-playwright/await-promise-in-class-returns
+ return Promise.resolve();
+ }
+
+ private _removeAllListeners(type?: string) {
const events = this._events;
if (!events)
- return this;
+ return;
// not listening for removeListener, no need to emit
if (!events.removeListener) {
@@ -230,7 +273,7 @@ export class EventEmitter implements EventEmitterType {
else
delete events[type];
}
- return this;
+ return;
}
// emit removeListener for all listeners on all events
@@ -241,12 +284,12 @@ export class EventEmitter implements EventEmitterType {
key = keys[i];
if (key === 'removeListener')
continue;
- this.removeAllListeners(key);
+ this._removeAllListeners(key);
}
- this.removeAllListeners('removeListener');
+ this._removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
- return this;
+ return;
}
const listeners = events[type];
@@ -258,8 +301,6 @@ export class EventEmitter implements EventEmitterType {
for (let i = listeners.length - 1; i >= 0; i--)
this.removeListener(type, listeners[i]);
}
-
- return this;
}
listeners(type: EventType): Listener[] {
@@ -286,6 +327,18 @@ export class EventEmitter implements EventEmitterType {
return this._eventsCount > 0 && this._events ? Reflect.ownKeys(this._events) : [];
}
+ private async _waitFor(type?: EventType) {
+ let promises: Promise<void>[] = [];
+ if (type) {
+ promises = [...(this._pendingHandlers.get(type) || [])];
+ } else {
+ promises = [];
+ for (const [, pending] of this._pendingHandlers)
+ promises.push(...pending);
+ }
+ await Promise.all(promises);
+ }
+
private _listeners(target: EventEmitter, type: EventType, unwrap: boolean): Listener[] {
const events = target._events;
@@ -310,7 +363,7 @@ function checkListener(listener: any) {
class OnceWrapper {
private _fired = false;
- readonly wrapperFunction: (...args: any[]) => void;
+ readonly wrapperFunction: (...args: any[]) => Promise<void> | void;
readonly _listener: Listener;
private _eventEmitter: EventEmitter;
private _eventType: EventType;
diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.ts
index 94ebd513da..8e818983c9 100644
--- a/packages/playwright-core/types/types.d.ts
+++ b/packages/playwright-core/types/types.d.ts
@@ -865,6 +865,19 @@ export interface Page {
* @param options
*/
exposeBinding(name: string, playwrightBinding: (source: BindingSource, ...args: any[]) => any, options?: { handle?: boolean }): Promise<void>;
+
+ /**
+ * Removes all the listeners of the given type if the type is given. Otherwise removes all the listeners.
+ * @param type
+ * @param options
+ */
+ removeAllListeners(type?: string): this;
+ /**
+ * Removes all the listeners of the given type if the type is given. Otherwise removes all the listeners.
+ * @param type
+ * @param options
+ */
+ removeAllListeners(type: string | undefined, options: { behavior?: 'wait'|'ignoreErrors'|'default' }): Promise<void>;
/**
* Emitted when the page closes.
*/
@@ -7661,6 +7674,19 @@ export interface BrowserContext {
* @param arg Optional argument to pass to `script` (only supported when passing a function).
*/
addInitScript<Arg>(script: PageFunction<Arg, any> | { path?: string, content?: string }, arg?: Arg): Promise<void>;
+
+ /**
+ * Removes all the listeners of the given type if the type is given. Otherwise removes all the listeners.
+ * @param type
+ * @param options
+ */
+ removeAllListeners(type?: string): this;
+ /**
+ * Removes all the listeners of the given type if the type is given. Otherwise removes all the listeners.
+ * @param type
+ * @param options
+ */
+ removeAllListeners(type: string | undefined, options: { behavior?: 'wait'|'ignoreErrors'|'default' }): Promise<void>;
/**
* **NOTE** Only works with Chromium browser's persistent context.
*
@@ -8916,2085 +8942,1384 @@ export interface BrowserContext {
}
/**
- * The Worker class represents a [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API).
- * `worker` event is emitted on the page object to signal a worker creation. `close` event is emitted on the worker
- * object when the worker is gone.
+ * - 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 {@link Browser} to create a {@link Page}:
*
* ```js
- * page.on('worker', worker => {
- * console.log('Worker created: ' + worker.url());
- * worker.on('close', worker => console.log('Worker destroyed: ' + worker.url()));
- * });
+ * const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
*
- * console.log('Current workers:');
- * for (const worker of page.workers())
- * console.log(' ' + worker.url());
+ * (async () => {
+ * const browser = await firefox.launch();
+ * const page = await browser.newPage();
+ * await page.goto('https://example.com');
+ * await browser.close();
+ * })();
* ```
*
*/
-export interface Worker {
- /**
- * Returns the return value of `pageFunction`.
- *
- * If the function passed to the
- * [worker.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate) returns a
- * [Promise], then
- * [worker.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate) would wait for
- * the promise to resolve and return its value.
- *
- * If the function passed to the
- * [worker.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate) returns a
- * non-[Serializable] value, then
- * [worker.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate) returns
- * `undefined`. Playwright also supports transferring some additional values that are not serializable by `JSON`:
- * `-0`, `NaN`, `Infinity`, `-Infinity`.
- * @param pageFunction Function to be evaluated in the worker context.
- * @param arg Optional argument to pass to `pageFunction`.
- */
- evaluate<R, Arg>(pageFunction: PageFunction<Arg, R>, arg: Arg): Promise<R>;
- /**
- * Returns the return value of `pageFunction`.
- *
- * If the function passed to the
- * [worker.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate) returns a
- * [Promise], then
- * [worker.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate) would wait for
- * the promise to resolve and return its value.
- *
- * If the function passed to the
- * [worker.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate) returns a
- * non-[Serializable] value, then
- * [worker.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate) returns
- * `undefined`. Playwright also supports transferring some additional values that are not serializable by `JSON`:
- * `-0`, `NaN`, `Infinity`, `-Infinity`.
- * @param pageFunction Function to be evaluated in the worker context.
- * @param arg Optional argument to pass to `pageFunction`.
- */
- evaluate<R>(pageFunction: PageFunction<void, R>, arg?: any): Promise<R>;
-
+export interface Browser {
/**
- * Returns the return value of `pageFunction` as a {@link JSHandle}.
- *
- * The only difference between
- * [worker.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate) and
- * [worker.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate-handle)
- * is that
- * [worker.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate-handle)
- * returns {@link JSHandle}.
- *
- * If the function passed to the
- * [worker.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate-handle)
- * returns a [Promise], then
- * [worker.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate-handle)
- * would wait for the promise to resolve and return its value.
- * @param pageFunction Function to be evaluated in the worker context.
- * @param arg Optional argument to pass to `pageFunction`.
+ * Removes all the listeners of the given type if the type is given. Otherwise removes all the listeners.
+ * @param type
+ * @param options
*/
- evaluateHandle<R, Arg>(pageFunction: PageFunction<Arg, R>, arg: Arg): Promise<SmartHandle<R>>;
+ removeAllListeners(type?: string): this;
/**
- * Returns the return value of `pageFunction` as a {@link JSHandle}.
- *
- * The only difference between
- * [worker.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate) and
- * [worker.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate-handle)
- * is that
- * [worker.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate-handle)
- * returns {@link JSHandle}.
- *
- * If the function passed to the
- * [worker.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate-handle)
- * returns a [Promise], then
- * [worker.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate-handle)
- * would wait for the promise to resolve and return its value.
- * @param pageFunction Function to be evaluated in the worker context.
- * @param arg Optional argument to pass to `pageFunction`.
+ * Removes all the listeners of the given type if the type is given. Otherwise removes all the listeners.
+ * @param type
+ * @param options
*/
- evaluateHandle<R>(pageFunction: PageFunction<void, R>, arg?: any): Promise<SmartHandle<R>>;
+ removeAllListeners(type: string | undefined, options: { behavior?: 'wait'|'ignoreErrors'|'default' }): Promise<void>;
/**
- * Emitted when this dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is
- * terminated.
+ * 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([options])](https://playwright.dev/docs/api/class-browser#browser-close) method was called.
*/
- on(event: 'close', listener: (worker: Worker) => any): this;
+ on(event: 'disconnected', listener: (browser: Browser) => any): this;
/**
* Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.
*/
- once(event: 'close', listener: (worker: Worker) => any): this;
+ once(event: 'disconnected', listener: (browser: Browser) => any): this;
/**
- * Emitted when this dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is
- * terminated.
+ * 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([options])](https://playwright.dev/docs/api/class-browser#browser-close) method was called.
*/
- addListener(event: 'close', listener: (worker: Worker) => any): this;
+ addListener(event: 'disconnected', listener: (browser: Browser) => any): this;
/**
* Removes an event listener added by `on` or `addListener`.
*/
- removeListener(event: 'close', listener: (worker: Worker) => any): this;
+ removeListener(event: 'disconnected', listener: (browser: Browser) => any): this;
/**
* Removes an event listener added by `on` or `addListener`.
*/
- off(event: 'close', listener: (worker: Worker) => any): this;
+ off(event: 'disconnected', listener: (browser: Browser) => any): this;
/**
- * Emitted when this dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is
- * terminated.
+ * 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([options])](https://playwright.dev/docs/api/class-browser#browser-close) method was called.
*/
- prependListener(event: 'close', listener: (worker: Worker) => any): this;
+ prependListener(event: 'disconnected', listener: (browser: Browser) => any): this;
- url(): string;
-}
+ /**
+ * Get the browser type (chromium, firefox or webkit) that the browser belongs to.
+ */
+ browserType(): BrowserType;
-/**
- * JSHandle represents an in-page JavaScript object. JSHandles can be created with the
- * [page.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-page#page-evaluate-handle) method.
- *
- * ```js
- * const windowHandle = await page.evaluateHandle(() => window);
- * // ...
- * ```
- *
- * JSHandle prevents the referenced JavaScript object being garbage collected unless the handle is exposed with
- * [jsHandle.dispose()](https://playwright.dev/docs/api/class-jshandle#js-handle-dispose). JSHandles are auto-disposed
- * when their origin frame gets navigated or the parent context gets destroyed.
- *
- * JSHandle instances can be used as an argument in
- * [page.$eval(selector, pageFunction[, arg, options])](https://playwright.dev/docs/api/class-page#page-eval-on-selector),
- * [page.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-page#page-evaluate) and
- * [page.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-page#page-evaluate-handle)
- * methods.
- */
-export interface JSHandle<T = any> {
/**
- * Returns the return value of `pageFunction`.
+ * 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).
*
- * This method passes this handle as the first argument to `pageFunction`.
+ * In case this browser is connected to, clears all created contexts belonging to this browser and disconnects from
+ * the browser server.
*
- * If `pageFunction` returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return its
- * value.
+ * **NOTE** This is similar to force quitting the browser. Therefore, you should call
+ * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) on
+ * any {@link BrowserContext}'s you explicitly created earlier with
+ * [browser.newContext([options])](https://playwright.dev/docs/api/class-browser#browser-new-context) **before**
+ * calling [browser.close([options])](https://playwright.dev/docs/api/class-browser#browser-close).
+ *
+ * The {@link Browser} object itself is considered to be disposed and cannot be used anymore.
+ * @param options
+ */
+ close(options?: {
+ /**
+ * The reason to be reported to the operations interrupted by the browser closure.
+ */
+ reason?: string;
+ }): Promise<void>;
+
+ /**
+ * Returns an array of all open browser contexts. In a newly created browser, this will return zero browser contexts.
*
* **Usage**
*
* ```js
- * const tweetHandle = await page.$('.tweet .retweets');
- * expect(await tweetHandle.evaluate(node => node.innerText)).toBe('10 retweets');
+ * 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`
* ```
*
- * @param pageFunction Function to be evaluated in the page context.
- * @param arg Optional argument to pass to `pageFunction`.
*/
- evaluate<R, Arg, O extends T = T>(pageFunction: PageFunctionOn<O, Arg, R>, arg: Arg): Promise<R>;
+ contexts(): Array<BrowserContext>;
+
/**
- * Returns the return value of `pageFunction`.
+ * Indicates that the browser is connected.
+ */
+ isConnected(): boolean;
+
+ /**
+ * **NOTE** CDP Sessions are only supported on Chromium-based browsers.
*
- * This method passes this handle as the first argument to `pageFunction`.
+ * Returns the newly created browser session.
+ */
+ newBrowserCDPSession(): Promise<CDPSession>;
+
+ /**
+ * Creates a new browser context. It won't share cookies/cache with other browser contexts.
*
- * If `pageFunction` returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return its
- * value.
+ * **NOTE** If directly using this method to create {@link BrowserContext}s, it is best practice to explicitly close
+ * the returned context via
+ * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) when
+ * your code is done with the {@link BrowserContext}, and before calling
+ * [browser.close([options])](https://playwright.dev/docs/api/class-browser#browser-close). This will ensure the
+ * `context` is closed gracefully and any artifacts—like HARs and videos—are fully flushed and saved.
*
* **Usage**
*
* ```js
- * const tweetHandle = await page.$('.tweet .retweets');
- * expect(await tweetHandle.evaluate(node => node.innerText)).toBe('10 retweets');
+ * (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');
+ *
+ * // Gracefully close up everything
+ * await context.close();
+ * await browser.close();
+ * })();
* ```
*
- * @param pageFunction Function to be evaluated in the page context.
- * @param arg Optional argument to pass to `pageFunction`.
+ * @param options
*/
- evaluate<R, O extends T = T>(pageFunction: PageFunctionOn<O, void, R>, arg?: any): Promise<R>;
+ newContext(options?: BrowserContextOptions): Promise<BrowserContext>;
/**
- * Returns the return value of `pageFunction` as a {@link JSHandle}.
- *
- * This method passes this handle as the first argument to `pageFunction`.
- *
- * The only difference between `jsHandle.evaluate` and `jsHandle.evaluateHandle` is that `jsHandle.evaluateHandle`
- * returns {@link JSHandle}.
- *
- * If the function passed to the `jsHandle.evaluateHandle` returns a [Promise], then `jsHandle.evaluateHandle` would
- * wait for the promise to resolve and return its value.
- *
- * See [page.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-page#page-evaluate-handle) for
- * more details.
- * @param pageFunction Function to be evaluated in the page context.
- * @param arg Optional argument to pass to `pageFunction`.
- */
- evaluateHandle<R, Arg, O extends T = T>(pageFunction: PageFunctionOn<O, Arg, R>, arg: Arg): Promise<SmartHandle<R>>;
- /**
- * Returns the return value of `pageFunction` as a {@link JSHandle}.
- *
- * This method passes this handle as the first argument to `pageFunction`.
- *
- * The only difference between `jsHandle.evaluate` and `jsHandle.evaluateHandle` is that `jsHandle.evaluateHandle`
- * returns {@link JSHandle}.
- *
- * If the function passed to the `jsHandle.evaluateHandle` returns a [Promise], then `jsHandle.evaluateHandle` would
- * wait for the promise to resolve and return its value.
- *
- * See [page.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-page#page-evaluate-handle) for
- * more details.
- * @param pageFunction Function to be evaluated in the page context.
- * @param arg Optional argument to pass to `pageFunction`.
- */
- evaluateHandle<R, O extends T = T>(pageFunction: PageFunctionOn<O, void, R>, arg?: any): Promise<SmartHandle<R>>;
-
- /**
- * Returns a JSON representation of the object. If the object has a `toJSON` function, it **will not be called**.
- *
- * **NOTE** The method will return an empty JSON object if the referenced object is not stringifiable. It will throw
- * an error if the object has circular references.
- */
- jsonValue(): Promise<T>;
- /**
- * Returns either `null` or the object handle itself, if the object handle is an instance of {@link ElementHandle}.
- */
- asElement(): T extends Node ? ElementHandle<T> : null;
- /**
- * The `jsHandle.dispose` method stops referencing the element handle.
- */
- dispose(): Promise<void>;
-
- /**
- * The method returns a map with **own property names** as keys and JSHandle instances for the property values.
- *
- * **Usage**
- *
- * ```js
- * const handle = await page.evaluateHandle(() => ({ window, document }));
- * const properties = await handle.getProperties();
- * const windowHandle = properties.get('window');
- * const documentHandle = properties.get('document');
- * await handle.dispose();
- * ```
- *
- */
- getProperties(): Promise<Map<string, JSHandle>>;
-
- /**
- * Fetches a single property from the referenced object.
- * @param propertyName property to get
- */
- getProperty(propertyName: string): Promise<JSHandle>;
-
- [Symbol.asyncDispose](): Promise<void>;
-}
-
-/**
- * - extends: {@link JSHandle}
- *
- * ElementHandle represents an in-page DOM element. ElementHandles can be created with the
- * [page.$(selector[, options])](https://playwright.dev/docs/api/class-page#page-query-selector) method.
- *
- * **NOTE** The use of ElementHandle is discouraged, use {@link Locator} objects and web-first assertions instead.
- *
- * ```js
- * const hrefElement = await page.$('a');
- * await hrefElement.click();
- * ```
- *
- * ElementHandle prevents DOM element from garbage collection unless the handle is disposed with
- * [jsHandle.dispose()](https://playwright.dev/docs/api/class-jshandle#js-handle-dispose). ElementHandles are
- * auto-disposed when their origin frame gets navigated.
- *
- * ElementHandle instances can be used as an argument in
- * [page.$eval(selector, pageFunction[, arg, options])](https://playwright.dev/docs/api/class-page#page-eval-on-selector)
- * and [page.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-page#page-evaluate) methods.
- *
- * The difference between the {@link Locator} and ElementHandle is that the ElementHandle points to a particular
- * element, while {@link Locator} captures the logic of how to retrieve an element.
- *
- * In the example below, handle points to a particular DOM element on page. If that element changes text or is used by
- * React to render an entirely different component, handle is still pointing to that very DOM element. This can lead
- * to unexpected behaviors.
- *
- * ```js
- * const handle = await page.$('text=Submit');
- * // ...
- * await handle.hover();
- * await handle.click();
- * ```
- *
- * With the locator, every time the `element` is used, up-to-date DOM element is located in the page using the
- * selector. So in the snippet below, underlying DOM element is going to be located twice.
- *
- * ```js
- * const locator = page.getByText('Submit');
- * // ...
- * await locator.hover();
- * await locator.click();
- * ```
- *
- */
-export interface ElementHandle<T=Node> extends JSHandle<T> {
- /**
- * **NOTE** Use locator-based [page.locator(selector[, options])](https://playwright.dev/docs/api/class-page#page-locator)
- * instead. Read more about [locators](https://playwright.dev/docs/locators).
- *
- * The method finds an element matching the specified selector in the `ElementHandle`'s subtree. If no elements match
- * the selector, returns `null`.
- * @param selector A selector to query for.
- */
- $<K extends keyof HTMLElementTagNameMap>(selector: K, options?: { strict: boolean }): Promise<ElementHandleForTag<K> | null>;
- /**
- * **NOTE** Use locator-based [page.locator(selector[, options])](https://playwright.dev/docs/api/class-page#page-locator)
- * instead. Read more about [locators](https://playwright.dev/docs/locators).
- *
- * The method finds an element matching the specified selector in the `ElementHandle`'s subtree. If no elements match
- * the selector, returns `null`.
- * @param selector A selector to query for.
- */
- $(selector: string, options?: { strict: boolean }): Promise<ElementHandle<SVGElement | HTMLElement> | null>;
-
- /**
- * **NOTE** Use locator-based [page.locator(selector[, options])](https://playwright.dev/docs/api/class-page#page-locator)
- * instead. Read more about [locators](https://playwright.dev/docs/locators).
- *
- * The method finds all elements matching the specified selector in the `ElementHandle`s subtree. If no elements match
- * the selector, returns empty array.
- * @param selector A selector to query for.
- */
- $$<K extends keyof HTMLElementTagNameMap>(selector: K): Promise<ElementHandleForTag<K>[]>;
- /**
- * **NOTE** Use locator-based [page.locator(selector[, options])](https://playwright.dev/docs/api/class-page#page-locator)
- * instead. Read more about [locators](https://playwright.dev/docs/locators).
- *
- * The method finds all elements matching the specified selector in the `ElementHandle`s subtree. If no elements match
- * the selector, returns empty array.
- * @param selector A selector to query for.
- */
- $$(selector: string): Promise<ElementHandle<SVGElement | HTMLElement>[]>;
-
- /**
- * **NOTE** This method does not wait for the element to pass actionability checks and therefore can lead to the flaky tests.
- * Use
- * [locator.evaluate(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate),
- * other {@link Locator} helper methods or web-first assertions instead.
- *
- * Returns the return value of `pageFunction`.
- *
- * The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a
- * first argument to `pageFunction`. If no elements match the selector, the method throws an error.
- *
- * If `pageFunction` returns a [Promise], then
- * [elementHandle.$eval(selector, pageFunction[, arg])](https://playwright.dev/docs/api/class-elementhandle#element-handle-eval-on-selector)
- * would wait for the promise to resolve and return its value.
- *
- * **Usage**
- *
- * ```js
- * const tweetHandle = await page.$('.tweet');
- * expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');
- * expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');
- * ```
- *
- * @param selector A selector to query for.
- * @param pageFunction Function to be evaluated in the page context.
- * @param arg Optional argument to pass to `pageFunction`.
- */
- $eval<K extends keyof HTMLElementTagNameMap, R, Arg>(selector: K, pageFunction: PageFunctionOn<HTMLElementTagNameMap[K], Arg, R>, arg: Arg): Promise<R>;
- /**
- * **NOTE** This method does not wait for the element to pass actionability checks and therefore can lead to the flaky tests.
- * Use
- * [locator.evaluate(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate),
- * other {@link Locator} helper methods or web-first assertions instead.
- *
- * Returns the return value of `pageFunction`.
- *
- * The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a
- * first argument to `pageFunction`. If no elements match the selector, the method throws an error.
- *
- * If `pageFunction` returns a [Promise], then
- * [elementHandle.$eval(selector, pageFunction[, arg])](https://playwright.dev/docs/api/class-elementhandle#element-handle-eval-on-selector)
- * would wait for the promise to resolve and return its value.
- *
- * **Usage**
- *
- * ```js
- * const tweetHandle = await page.$('.tweet');
- * expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');
- * expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');
- * ```
- *
- * @param selector A selector to query for.
- * @param pageFunction Function to be evaluated in the page context.
- * @param arg Optional argument to pass to `pageFunction`.
- */
- $eval<R, Arg, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(selector: string, pageFunction: PageFunctionOn<E, Arg, R>, arg: Arg): Promise<R>;
- /**
- * **NOTE** This method does not wait for the element to pass actionability checks and therefore can lead to the flaky tests.
- * Use
- * [locator.evaluate(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate),
- * other {@link Locator} helper methods or web-first assertions instead.
- *
- * Returns the return value of `pageFunction`.
- *
- * The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a
- * first argument to `pageFunction`. If no elements match the selector, the method throws an error.
- *
- * If `pageFunction` returns a [Promise], then
- * [elementHandle.$eval(selector, pageFunction[, arg])](https://playwright.dev/docs/api/class-elementhandle#element-handle-eval-on-selector)
- * would wait for the promise to resolve and return its value.
- *
- * **Usage**
- *
- * ```js
- * const tweetHandle = await page.$('.tweet');
- * expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');
- * expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');
- * ```
- *
- * @param selector A selector to query for.
- * @param pageFunction Function to be evaluated in the page context.
- * @param arg Optional argument to pass to `pageFunction`.
- */
- $eval<K extends keyof HTMLElementTagNameMap, R>(selector: K, pageFunction: PageFunctionOn<HTMLElementTagNameMap[K], void, R>, arg?: any): Promise<R>;
- /**
- * **NOTE** This method does not wait for the element to pass actionability checks and therefore can lead to the flaky tests.
- * Use
- * [locator.evaluate(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate),
- * other {@link Locator} helper methods or web-first assertions instead.
- *
- * Returns the return value of `pageFunction`.
- *
- * The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a
- * first argument to `pageFunction`. If no elements match the selector, the method throws an error.
- *
- * If `pageFunction` returns a [Promise], then
- * [elementHandle.$eval(selector, pageFunction[, arg])](https://playwright.dev/docs/api/class-elementhandle#element-handle-eval-on-selector)
- * would wait for the promise to resolve and return its value.
- *
- * **Usage**
- *
- * ```js
- * const tweetHandle = await page.$('.tweet');
- * expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');
- * expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');
- * ```
- *
- * @param selector A selector to query for.
- * @param pageFunction Function to be evaluated in the page context.
- * @param arg Optional argument to pass to `pageFunction`.
- */
- $eval<R, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(selector: string, pageFunction: PageFunctionOn<E, void, R>, arg?: any): Promise<R>;
-
- /**
- * **NOTE** In most cases,
- * [locator.evaluateAll(pageFunction[, arg])](https://playwright.dev/docs/api/class-locator#locator-evaluate-all),
- * other {@link Locator} helper methods and web-first assertions do a better job.
- *
- * Returns the return value of `pageFunction`.
- *
- * The method finds all elements matching the specified selector in the `ElementHandle`'s subtree and passes an array
- * of matched elements as a first argument to `pageFunction`.
- *
- * If `pageFunction` returns a [Promise], then
- * [elementHandle.$$eval(selector, pageFunction[, arg])](https://playwright.dev/docs/api/class-elementhandle#element-handle-eval-on-selector-all)
- * would wait for the promise to resolve and return its value.
- *
- * **Usage**
- *
- * ```html
- * <div class="feed">
- * <div class="tweet">Hello!</div>
- * <div class="tweet">Hi!</div>
- * </div>
- * ```
- *
- * ```js
- * const feedHandle = await page.$('.feed');
- * expect(await feedHandle.$$eval('.tweet', nodes =>
- * nodes.map(n => n.innerText))).toEqual(['Hello!', 'Hi!'],
- * );
- * ```
- *
- * @param selector A selector to query for.
- * @param pageFunction Function to be evaluated in the page context.
- * @param arg Optional argument to pass to `pageFunction`.
- */
- $$eval<K extends keyof HTMLElementTagNameMap, R, Arg>(selector: K, pageFunction: PageFunctionOn<HTMLElementTagNameMap[K][], Arg, R>, arg: Arg): Promise<R>;
- /**
- * **NOTE** In most cases,
- * [locator.evaluateAll(pageFunction[, arg])](https://playwright.dev/docs/api/class-locator#locator-evaluate-all),
- * other {@link Locator} helper methods and web-first assertions do a better job.
- *
- * Returns the return value of `pageFunction`.
- *
- * The method finds all elements matching the specified selector in the `ElementHandle`'s subtree and passes an array
- * of matched elements as a first argument to `pageFunction`.
- *
- * If `pageFunction` returns a [Promise], then
- * [elementHandle.$$eval(selector, pageFunction[, arg])](https://playwright.dev/docs/api/class-elementhandle#element-handle-eval-on-selector-all)
- * would wait for the promise to resolve and return its value.
- *
- * **Usage**
- *
- * ```html
- * <div class="feed">
- * <div class="tweet">Hello!</div>
- * <div class="tweet">Hi!</div>
- * </div>
- * ```
- *
- * ```js
- * const feedHandle = await page.$('.feed');
- * expect(await feedHandle.$$eval('.tweet', nodes =>
- * nodes.map(n => n.innerText))).toEqual(['Hello!', 'Hi!'],
- * );
- * ```
- *
- * @param selector A selector to query for.
- * @param pageFunction Function to be evaluated in the page context.
- * @param arg Optional argument to pass to `pageFunction`.
- */
- $$eval<R, Arg, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(selector: string, pageFunction: PageFunctionOn<E[], Arg, R>, arg: Arg): Promise<R>;
- /**
- * **NOTE** In most cases,
- * [locator.evaluateAll(pageFunction[, arg])](https://playwright.dev/docs/api/class-locator#locator-evaluate-all),
- * other {@link Locator} helper methods and web-first assertions do a better job.
- *
- * Returns the return value of `pageFunction`.
- *
- * The method finds all elements matching the specified selector in the `ElementHandle`'s subtree and passes an array
- * of matched elements as a first argument to `pageFunction`.
- *
- * If `pageFunction` returns a [Promise], then
- * [elementHandle.$$eval(selector, pageFunction[, arg])](https://playwright.dev/docs/api/class-elementhandle#element-handle-eval-on-selector-all)
- * would wait for the promise to resolve and return its value.
- *
- * **Usage**
- *
- * ```html
- * <div class="feed">
- * <div class="tweet">Hello!</div>
- * <div class="tweet">Hi!</div>
- * </div>
- * ```
- *
- * ```js
- * const feedHandle = await page.$('.feed');
- * expect(await feedHandle.$$eval('.tweet', nodes =>
- * nodes.map(n => n.innerText))).toEqual(['Hello!', 'Hi!'],
- * );
- * ```
- *
- * @param selector A selector to query for.
- * @param pageFunction Function to be evaluated in the page context.
- * @param arg Optional argument to pass to `pageFunction`.
- */
- $$eval<K extends keyof HTMLElementTagNameMap, R>(selector: K, pageFunction: PageFunctionOn<HTMLElementTagNameMap[K][], void, R>, arg?: any): Promise<R>;
- /**
- * **NOTE** In most cases,
- * [locator.evaluateAll(pageFunction[, arg])](https://playwright.dev/docs/api/class-locator#locator-evaluate-all),
- * other {@link Locator} helper methods and web-first assertions do a better job.
- *
- * Returns the return value of `pageFunction`.
- *
- * The method finds all elements matching the specified selector in the `ElementHandle`'s subtree and passes an array
- * of matched elements as a first argument to `pageFunction`.
- *
- * If `pageFunction` returns a [Promise], then
- * [elementHandle.$$eval(selector, pageFunction[, arg])](https://playwright.dev/docs/api/class-elementhandle#element-handle-eval-on-selector-all)
- * would wait for the promise to resolve and return its value.
- *
- * **Usage**
- *
- * ```html
- * <div class="feed">
- * <div class="tweet">Hello!</div>
- * <div class="tweet">Hi!</div>
- * </div>
- * ```
- *
- * ```js
- * const feedHandle = await page.$('.feed');
- * expect(await feedHandle.$$eval('.tweet', nodes =>
- * nodes.map(n => n.innerText))).toEqual(['Hello!', 'Hi!'],
- * );
- * ```
- *
- * @param selector A selector to query for.
- * @param pageFunction Function to be evaluated in the page context.
- * @param arg Optional argument to pass to `pageFunction`.
- */
- $$eval<R, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(selector: string, pageFunction: PageFunctionOn<E[], void, R>, arg?: any): Promise<R>;
-
- /**
- * **NOTE** Use web assertions that assert visibility or a locator-based
- * [locator.waitFor([options])](https://playwright.dev/docs/api/class-locator#locator-wait-for) instead.
- *
- * Returns element specified by selector when it satisfies `state` option. Returns `null` if waiting for `hidden` or
- * `detached`.
- *
- * Wait for the `selector` relative to the element handle to satisfy `state` option (either appear/disappear from dom,
- * or become visible/hidden). If at the moment of calling the method `selector` already satisfies the condition, the
- * method will return immediately. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the
- * function will throw.
- *
- * **Usage**
- *
- * ```js
- * await page.setContent(`<div><span></span></div>`);
- * const div = await page.$('div');
- * // Waiting for the 'span' selector relative to the div.
- * const span = await div.waitForSelector('span', { state: 'attached' });
- * ```
- *
- * **NOTE** This method does not work across navigations, use
- * [page.waitForSelector(selector[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-selector)
- * instead.
- * @param selector A selector to query for.
- * @param options
- */
- waitForSelector<K extends keyof HTMLElementTagNameMap>(selector: K, options?: ElementHandleWaitForSelectorOptionsNotHidden): Promise<ElementHandleForTag<K>>;
- /**
- * **NOTE** Use web assertions that assert visibility or a locator-based
- * [locator.waitFor([options])](https://playwright.dev/docs/api/class-locator#locator-wait-for) instead.
- *
- * Returns element specified by selector when it satisfies `state` option. Returns `null` if waiting for `hidden` or
- * `detached`.
- *
- * Wait for the `selector` relative to the element handle to satisfy `state` option (either appear/disappear from dom,
- * or become visible/hidden). If at the moment of calling the method `selector` already satisfies the condition, the
- * method will return immediately. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the
- * function will throw.
- *
- * **Usage**
- *
- * ```js
- * await page.setContent(`<div><span></span></div>`);
- * const div = await page.$('div');
- * // Waiting for the 'span' selector relative to the div.
- * const span = await div.waitForSelector('span', { state: 'attached' });
- * ```
- *
- * **NOTE** This method does not work across navigations, use
- * [page.waitForSelector(selector[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-selector)
- * instead.
- * @param selector A selector to query for.
- * @param options
- */
- waitForSelector(selector: string, options?: ElementHandleWaitForSelectorOptionsNotHidden): Promise<ElementHandle<SVGElement | HTMLElement>>;
- /**
- * **NOTE** Use web assertions that assert visibility or a locator-based
- * [locator.waitFor([options])](https://playwright.dev/docs/api/class-locator#locator-wait-for) instead.
- *
- * Returns element specified by selector when it satisfies `state` option. Returns `null` if waiting for `hidden` or
- * `detached`.
- *
- * Wait for the `selector` relative to the element handle to satisfy `state` option (either appear/disappear from dom,
- * or become visible/hidden). If at the moment of calling the method `selector` already satisfies the condition, the
- * method will return immediately. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the
- * function will throw.
- *
- * **Usage**
- *
- * ```js
- * await page.setContent(`<div><span></span></div>`);
- * const div = await page.$('div');
- * // Waiting for the 'span' selector relative to the div.
- * const span = await div.waitForSelector('span', { state: 'attached' });
- * ```
- *
- * **NOTE** This method does not work across navigations, use
- * [page.waitForSelector(selector[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-selector)
- * instead.
- * @param selector A selector to query for.
- * @param options
- */
- waitForSelector<K extends keyof HTMLElementTagNameMap>(selector: K, options: ElementHandleWaitForSelectorOptions): Promise<ElementHandleForTag<K> | null>;
- /**
- * **NOTE** Use web assertions that assert visibility or a locator-based
- * [locator.waitFor([options])](https://playwright.dev/docs/api/class-locator#locator-wait-for) instead.
- *
- * Returns element specified by selector when it satisfies `state` option. Returns `null` if waiting for `hidden` or
- * `detached`.
- *
- * Wait for the `selector` relative to the element handle to satisfy `state` option (either appear/disappear from dom,
- * or become visible/hidden). If at the moment of calling the method `selector` already satisfies the condition, the
- * method will return immediately. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the
- * function will throw.
- *
- * **Usage**
- *
- * ```js
- * await page.setContent(`<div><span></span></div>`);
- * const div = await page.$('div');
- * // Waiting for the 'span' selector relative to the div.
- * const span = await div.waitForSelector('span', { state: 'attached' });
- * ```
- *
- * **NOTE** This method does not work across navigations, use
- * [page.waitForSelector(selector[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-selector)
- * instead.
- * @param selector A selector to query for.
- * @param options
- */
- waitForSelector(selector: string, options: ElementHandleWaitForSelectorOptions): Promise<null|ElementHandle<SVGElement | HTMLElement>>;
- /**
- * This method returns the bounding box of the element, or `null` if the element is not visible. The bounding box is
- * calculated relative to the main frame viewport - which is usually the same as the browser window.
- *
- * Scrolling affects the returned bounding box, similarly to
- * [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
- * That means `x` and/or `y` may be negative.
- *
- * Elements from child frames return the bounding box relative to the main frame, unlike the
- * [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
- *
- * Assuming the page is static, it is safe to use bounding box coordinates to perform input. For example, the
- * following snippet should click the center of the element.
- *
- * **Usage**
- *
- * ```js
- * const box = await elementHandle.boundingBox();
- * await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
- * ```
+ * 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
*/
- boundingBox(): Promise<null|{
+ newPage(options?: {
/**
- * the x coordinate of the element in pixels.
+ * Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.
*/
- x: number;
+ acceptDownloads?: boolean;
/**
- * the y coordinate of the element in pixels.
+ * When using [page.goto(url[, options])](https://playwright.dev/docs/api/class-page#page-goto),
+ * [page.route(url, handler[, options])](https://playwright.dev/docs/api/class-page#page-route),
+ * [page.waitForURL(url[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-url),
+ * [page.waitForRequest(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-request),
+ * or
+ * [page.waitForResponse(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-response)
+ * it takes the base URL in consideration by using the
+ * [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL.
+ * Unset by default. Examples:
+ * - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`
+ * - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in
+ * `http://localhost:3000/foo/bar.html`
+ * - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
+ * `http://localhost:3000/bar.html`
*/
- y: number;
+ baseURL?: string;
/**
- * the width of the element in pixels.
+ * Toggles bypassing page's Content-Security-Policy. Defaults to `false`.
*/
- width: number;
+ bypassCSP?: boolean;
/**
- * the height of the element in pixels.
+ * TLS Client Authentication allows the server to request a client certificate and verify it.
+ *
+ * **Details**
+ *
+ * An array of client certificates to be used. Each certificate object must have both `certPath` and `keyPath` or a
+ * single `pfxPath` to load the client certificate. Optionally, `passphrase` property should be provided if the
+ * certficiate is encrypted. The `origin` property should be provided with an exact match to the request origin that
+ * the certificate is valid for.
+ *
+ * **NOTE** Using Client Certificates in combination with Proxy Servers is not supported.
+ *
+ * **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
+ * work by replacing `localhost` with `local.playwright`.
*/
- height: number;
- }>;
+ clientCertificates?: Array<{
+ /**
+ * Exact origin that the certificate is valid for. Origin includes `https` protocol, a hostname and optionally a port.
+ */
+ origin: string;
- /**
- * **NOTE** Use locator-based [locator.check([options])](https://playwright.dev/docs/api/class-locator#locator-check) instead.
- * Read more about [locators](https://playwright.dev/docs/locators).
- *
- * This method checks the element by performing the following steps:
- * 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
- * checked, this method returns immediately.
- * 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
- * 1. Scroll the element into view if needed.
- * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to click in the center of the
- * element.
- * 1. Ensure that the element is now checked. If not, this method throws.
- *
- * If the element is detached from the DOM at any moment during the action, this method throws.
- *
- * When all steps combined have not finished during the specified `timeout`, this method throws a {@link
- * TimeoutError}. Passing zero timeout disables this.
- * @param options
- */
- check(options?: {
- /**
- * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
- */
- force?: boolean;
+ /**
+ * Path to the file with the certificate in PEM format.
+ */
+ certPath?: string;
- /**
- * This option has no effect.
- * @deprecated This option has no effect.
- */
- noWaitAfter?: boolean;
+ /**
+ * Path to the file with the private key in PEM format.
+ */
+ keyPath?: string;
- /**
- * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- * the element.
- */
- position?: {
- x: number;
+ /**
+ * Path to the PFX or PKCS12 encoded private key and certificate chain.
+ */
+ pfxPath?: string;
- y: number;
- };
+ /**
+ * Passphrase for the private key (PEM or PFX).
+ */
+ passphrase?: string;
+ }>;
/**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
+ * 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.
+ * Passing `null` resets emulation to system defaults. Defaults to `'light'`.
*/
- timeout?: number;
+ colorScheme?: null|"light"|"dark"|"no-preference";
/**
- * When set, this method only performs the [actionability](https://playwright.dev/docs/actionability) checks and skips the action. Defaults
- * to `false`. Useful to wait until the element is ready for the action without performing it.
+ * Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about
+ * [emulating devices with device scale factor](https://playwright.dev/docs/emulation#devices).
*/
- trial?: boolean;
- }): Promise<void>;
+ deviceScaleFactor?: number;
- /**
- * **NOTE** Use locator-based [locator.click([options])](https://playwright.dev/docs/api/class-locator#locator-click) instead.
- * Read more about [locators](https://playwright.dev/docs/locators).
- *
- * This method clicks the element by performing the following steps:
- * 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
- * 1. Scroll the element into view if needed.
- * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to click in the center of the
- * element, or the specified `position`.
- * 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
- *
- * If the element is detached from the DOM at any moment during the action, this method throws.
- *
- * When all steps combined have not finished during the specified `timeout`, this method throws a {@link
- * TimeoutError}. Passing zero timeout disables this.
- * @param options
- */
- click(options?: {
/**
- * Defaults to `left`.
+ * An object containing additional HTTP headers to be sent with every request. Defaults to none.
*/
- button?: "left"|"right"|"middle";
+ extraHTTPHeaders?: { [key: string]: string; };
/**
- * defaults to 1. See [UIEvent.detail].
+ * Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See
+ * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.
+ * Passing `null` resets emulation to system defaults. Defaults to `'none'`.
*/
- clickCount?: number;
+ forcedColors?: null|"active"|"none";
- /**
- * Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
- */
- delay?: number;
+ geolocation?: {
+ /**
+ * Latitude between -90 and 90.
+ */
+ latitude: number;
- /**
- * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
- */
- force?: boolean;
+ /**
+ * Longitude between -180 and 180.
+ */
+ longitude: number;
- /**
- * Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- * current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- * "Control" on Windows and Linux and to "Meta" on macOS.
- */
- modifiers?: Array<"Alt"|"Control"|"ControlOrMeta"|"Meta"|"Shift">;
+ /**
+ * Non-negative accuracy value. Defaults to `0`.
+ */
+ accuracy?: number;
+ };
/**
- * Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
- * can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
- * navigating to inaccessible pages. Defaults to `false`.
- * @deprecated This option will default to `true` in the future.
+ * Specifies if viewport supports touch events. Defaults to false. Learn more about
+ * [mobile emulation](https://playwright.dev/docs/emulation#devices).
*/
- noWaitAfter?: boolean;
+ hasTouch?: boolean;
/**
- * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- * the element.
+ * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
+ * origin is specified, the username and password are sent to any servers upon unauthorized responses.
*/
- position?: {
- x: number;
+ httpCredentials?: {
+ username: string;
- y: number;
+ password: string;
+
+ /**
+ * Restrain sending http credentials on specific origin (scheme://host:port).
+ */
+ origin?: string;
+
+ /**
+ * This option only applies to the requests sent from corresponding {@link APIRequestContext} and does not affect
+ * requests sent from the browser. `'always'` - `Authorization` header with basic authentication credentials will be
+ * sent with the each API request. `'unauthorized` - the credentials are only sent when 401 (Unauthorized) response
+ * with `WWW-Authenticate` header is received. Defaults to `'unauthorized'`.
+ */
+ send?: "unauthorized"|"always";
};
/**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
*/
- timeout?: number;
+ ignoreHTTPSErrors?: boolean;
/**
- * When set, this method only performs the [actionability](https://playwright.dev/docs/actionability) checks and skips the action. Defaults
- * to `false`. Useful to wait until the element is ready for the action without performing it.
+ * Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,
+ * so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more
+ * about [mobile emulation](https://playwright.dev/docs/emulation#ismobile).
*/
- trial?: boolean;
- }): Promise<void>;
+ isMobile?: boolean;
- /**
- * Returns the content frame for element handles referencing iframe nodes, or `null` otherwise
- */
- contentFrame(): Promise<null|Frame>;
+ /**
+ * Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about
+ * [disabling JavaScript](https://playwright.dev/docs/emulation#javascript-enabled).
+ */
+ 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. Defaults to the system default
+ * locale. Learn more about emulation in our [emulation guide](https://playwright.dev/docs/emulation#locale--timezone).
+ */
+ locale?: string;
- /**
- * **NOTE** Use locator-based [locator.dblclick([options])](https://playwright.dev/docs/api/class-locator#locator-dblclick)
- * instead. Read more about [locators](https://playwright.dev/docs/locators).
- *
- * This method double clicks the element by performing the following steps:
- * 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
- * 1. Scroll the element into view if needed.
- * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to double click in the center of the
- * element, or the specified `position`.
- *
- * If the element is detached from the DOM at any moment during the action, this method throws.
- *
- * When all steps combined have not finished during the specified `timeout`, this method throws a {@link
- * TimeoutError}. Passing zero timeout disables this.
- *
- * **NOTE** `elementHandle.dblclick()` dispatches two `click` events and a single `dblclick` event.
- * @param options
- */
- dblclick(options?: {
/**
- * Defaults to `left`.
+ * Logger sink for Playwright logging.
*/
- button?: "left"|"right"|"middle";
+ logger?: Logger;
/**
- * Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
+ * Whether to emulate network being offline. Defaults to `false`. Learn more about
+ * [network emulation](https://playwright.dev/docs/emulation#offline).
*/
- delay?: number;
+ offline?: boolean;
/**
- * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
+ * A list of permissions to grant to all pages in this context. See
+ * [browserContext.grantPermissions(permissions[, options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-grant-permissions)
+ * for more details. Defaults to none.
*/
- force?: boolean;
+ permissions?: Array<string>;
/**
- * Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- * current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- * "Control" on Windows and Linux and to "Meta" on macOS.
+ * Network proxy settings to use with this context. Defaults to none.
+ *
+ * **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' } })`.
*/
- modifiers?: Array<"Alt"|"Control"|"ControlOrMeta"|"Meta"|"Shift">;
+ 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 comma-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;
+ };
/**
- * This option has no effect.
- * @deprecated This option has no effect.
+ * Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into `recordHar.path` file.
+ * If not specified, the HAR is not recorded. Make sure to await
+ * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for
+ * the HAR to be saved.
*/
- noWaitAfter?: boolean;
+ recordHar?: {
+ /**
+ * Optional setting to control whether to omit request content from the HAR. Defaults to `false`. Deprecated, use
+ * `content` policy instead.
+ */
+ omitContent?: boolean;
+
+ /**
+ * Optional setting to control resource content management. If `omit` is specified, content is not persisted. If
+ * `attach` is specified, resources are persisted as separate files or entries in the ZIP archive. If `embed` is
+ * specified, content is stored inline the HAR file as per HAR specification. Defaults to `attach` for `.zip` output
+ * files and to `embed` for all other file extensions.
+ */
+ content?: "omit"|"embed"|"attach";
+
+ /**
+ * Path on the filesystem to write the HAR file to. If the file name ends with `.zip`, `content: 'attach'` is used by
+ * default.
+ */
+ path: string;
+
+ /**
+ * When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
+ * cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.
+ */
+ mode?: "full"|"minimal";
+
+ /**
+ * A glob or regex pattern to filter requests that are stored in the HAR. When a `baseURL` via the context options was
+ * provided and the passed URL is a path, it gets merged via the
+ * [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor. Defaults to none.
+ */
+ urlFilter?: string|RegExp;
+ };
/**
- * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- * the element.
+ * Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded.
+ * Make sure to await
+ * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for
+ * videos to be saved.
*/
- position?: {
- x: number;
+ recordVideo?: {
+ /**
+ * Path to the directory to put videos into.
+ */
+ dir: string;
- y: 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;
+
+ /**
+ * Video frame height.
+ */
+ height: number;
+ };
};
/**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
+ * Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See
+ * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.
+ * Passing `null` resets emulation to system defaults. Defaults to `'no-preference'`.
*/
- timeout?: number;
+ reducedMotion?: null|"reduce"|"no-preference";
/**
- * When set, this method only performs the [actionability](https://playwright.dev/docs/actionability) checks and skips the action. Defaults
- * to `false`. Useful to wait until the element is ready for the action without performing it.
+ * Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the
+ * `viewport` is set.
*/
- trial?: boolean;
- }): Promise<void>;
+ screen?: {
+ /**
+ * page width in pixels.
+ */
+ width: number;
- /**
- * **NOTE** Use locator-based
- * [locator.dispatchEvent(type[, eventInit, options])](https://playwright.dev/docs/api/class-locator#locator-dispatch-event)
- * instead. Read more about [locators](https://playwright.dev/docs/locators).
- *
- * The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the element,
- * `click` is dispatched. This is equivalent to calling
- * [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
- *
- * **Usage**
- *
- * ```js
- * await elementHandle.dispatchEvent('click');
- * ```
- *
- * Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit`
- * properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
- *
- * Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
- * - [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent)
- * - [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent)
- * - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
- * - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
- * - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
- * - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
- * - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
- * - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
- * - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
- * - [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent)
- *
- * You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
- *
- * ```js
- * // Note you can only create DataTransfer in Chromium and Firefox
- * const dataTransfer = await page.evaluateHandle(() => new DataTransfer());
- * await elementHandle.dispatchEvent('dragstart', { dataTransfer });
- * ```
- *
- * @param type DOM event type: `"click"`, `"dragstart"`, etc.
- * @param eventInit Optional event-specific initialization properties.
- */
- dispatchEvent(type: string, eventInit?: EvaluationArgument): Promise<void>;
+ /**
+ * page height in pixels.
+ */
+ height: number;
+ };
- /**
- * **NOTE** Use locator-based [locator.fill(value[, options])](https://playwright.dev/docs/api/class-locator#locator-fill)
- * instead. Read more about [locators](https://playwright.dev/docs/locators).
- *
- * This method waits for [actionability](https://playwright.dev/docs/actionability) checks, focuses the element, fills it and triggers an
- * `input` event after filling. Note that you can pass an empty string to clear the input field.
- *
- * If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
- * error. However, if the element is inside the `<label>` element that has an associated
- * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled
- * instead.
- *
- * To send fine-grained keyboard events, use
- * [locator.pressSequentially(text[, options])](https://playwright.dev/docs/api/class-locator#locator-press-sequentially).
- * @param value Value to set for the `<input>`, `<textarea>` or `[contenteditable]` element.
- * @param options
- */
- fill(value: string, options?: {
/**
- * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
+ * Whether to allow sites to register Service workers. Defaults to `'allow'`.
+ * - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be
+ * registered.
+ * - `'block'`: Playwright will block all registration of Service Workers.
*/
- force?: boolean;
+ serviceWorkers?: "allow"|"block";
+
+ /**
+ * Learn more about [storage state and auth](https://playwright.dev/docs/auth).
+ *
+ * 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).
+ */
+ storageState?: string|{
+ /**
+ * Cookies to set for context
+ */
+ cookies: Array<{
+ name: string;
+
+ value: string;
+
+ /**
+ * Domain and path are required. For the cookie to apply to all subdomains as well, prefix domain with a dot, like
+ * this: ".example.com"
+ */
+ domain: string;
+
+ /**
+ * Domain and path are required
+ */
+ path: string;
+
+ /**
+ * Unix time in seconds.
+ */
+ expires: number;
+
+ httpOnly: boolean;
+
+ secure: boolean;
+
+ /**
+ * sameSite flag
+ */
+ sameSite: "Strict"|"Lax"|"None";
+ }>;
+
+ /**
+ * localStorage to set for context
+ */
+ origins: Array<{
+ origin: string;
+
+ localStorage: Array<{
+ name: string;
+
+ value: string;
+ }>;
+ }>;
+ };
/**
- * This option has no effect.
- * @deprecated This option has no effect.
+ * If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on
+ * selectors that imply single target DOM element will throw when more than one element matches the selector. This
+ * option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See {@link Locator} to
+ * learn more about the strict mode.
*/
- noWaitAfter?: boolean;
+ strictSelectors?: boolean;
/**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
+ * Changes the timezone of the context. See
+ * [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)
+ * for a list of supported timezone IDs. Defaults to the system timezone.
*/
- timeout?: number;
- }): Promise<void>;
-
- /**
- * **NOTE** Use locator-based [locator.focus([options])](https://playwright.dev/docs/api/class-locator#locator-focus) instead.
- * Read more about [locators](https://playwright.dev/docs/locators).
- *
- * Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the element.
- */
- focus(): Promise<void>;
-
- /**
- * **NOTE** Use locator-based
- * [locator.getAttribute(name[, options])](https://playwright.dev/docs/api/class-locator#locator-get-attribute)
- * instead. Read more about [locators](https://playwright.dev/docs/locators).
- *
- * Returns element attribute value.
- * @param name Attribute name to get the value for.
- */
- getAttribute(name: string): Promise<null|string>;
+ timezoneId?: string;
- /**
- * **NOTE** Use locator-based [locator.hover([options])](https://playwright.dev/docs/api/class-locator#locator-hover) instead.
- * Read more about [locators](https://playwright.dev/docs/locators).
- *
- * This method hovers over the element by performing the following steps:
- * 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
- * 1. Scroll the element into view if needed.
- * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to hover over the center of the
- * element, or the specified `position`.
- *
- * If the element is detached from the DOM at any moment during the action, this method throws.
- *
- * When all steps combined have not finished during the specified `timeout`, this method throws a {@link
- * TimeoutError}. Passing zero timeout disables this.
- * @param options
- */
- hover(options?: {
/**
- * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
+ * Specific user agent to use in this context.
*/
- force?: boolean;
+ userAgent?: string;
/**
- * Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- * current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- * "Control" on Windows and Linux and to "Meta" on macOS.
+ * @deprecated Use `recordVideo` instead.
*/
- modifiers?: Array<"Alt"|"Control"|"ControlOrMeta"|"Meta"|"Shift">;
+ videoSize?: {
+ /**
+ * Video frame width.
+ */
+ width: number;
+
+ /**
+ * Video frame height.
+ */
+ height: number;
+ };
/**
- * This option has no effect.
- * @deprecated This option has no effect.
+ * @deprecated Use `recordVideo` instead.
*/
- noWaitAfter?: boolean;
+ videosPath?: string;
/**
- * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- * the element.
+ * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use `null` to disable the consistent
+ * viewport emulation. Learn more about [viewport emulation](https://playwright.dev/docs/emulation#viewport).
+ *
+ * **NOTE** The `null` value opts out from the default presets, makes viewport depend on the host window size defined
+ * by the operating system. It makes the execution of the tests non-deterministic.
*/
- position?: {
- x: number;
+ viewport?: null|{
+ /**
+ * page width in pixels.
+ */
+ width: number;
- y: number;
+ /**
+ * page height in pixels.
+ */
+ height: number;
};
+ }): Promise<Page>;
+
+ /**
+ * **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](https://playwright.dev/docs/trace-viewer) could be found
+ * [here](https://playwright.dev/docs/api/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.
+ *
+ * **Usage**
+ *
+ * ```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
+ */
+ startTracing(page?: Page, options?: {
+ /**
+ * specify custom categories to use instead of default.
+ */
+ categories?: Array<string>;
/**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
+ * A path to write the trace file to.
*/
- timeout?: number;
+ path?: string;
/**
- * When set, this method only performs the [actionability](https://playwright.dev/docs/actionability) checks and skips the action. Defaults
- * to `false`. Useful to wait until the element is ready for the action without performing it.
+ * captures screenshots in the trace.
*/
- trial?: boolean;
+ screenshots?: boolean;
}): Promise<void>;
/**
- * **NOTE** Use locator-based [locator.innerHTML([options])](https://playwright.dev/docs/api/class-locator#locator-inner-html)
- * instead. Read more about [locators](https://playwright.dev/docs/locators).
+ * **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](https://playwright.dev/docs/trace-viewer) could be found
+ * [here](https://playwright.dev/docs/api/class-tracing).
*
- * Returns the `element.innerHTML`.
+ * Returns the buffer with trace data.
*/
- innerHTML(): Promise<string>;
+ stopTracing(): Promise<Buffer>;
/**
- * **NOTE** Use locator-based [locator.innerText([options])](https://playwright.dev/docs/api/class-locator#locator-inner-text)
- * instead. Read more about [locators](https://playwright.dev/docs/locators).
- *
- * Returns the `element.innerText`.
+ * Returns the browser version.
*/
- innerText(): Promise<string>;
+ version(): string;
+ [Symbol.asyncDispose](): Promise<void>;
+}
+
+/**
+ * The Worker class represents a [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API).
+ * `worker` event is emitted on the page object to signal a worker creation. `close` event is emitted on the worker
+ * object when the worker is gone.
+ *
+ * ```js
+ * page.on('worker', worker => {
+ * console.log('Worker created: ' + worker.url());
+ * worker.on('close', worker => console.log('Worker destroyed: ' + worker.url()));
+ * });
+ *
+ * console.log('Current workers:');
+ * for (const worker of page.workers())
+ * console.log(' ' + worker.url());
+ * ```
+ *
+ */
+export interface Worker {
/**
- * **NOTE** Use locator-based
- * [locator.inputValue([options])](https://playwright.dev/docs/api/class-locator#locator-input-value) instead. Read
- * more about [locators](https://playwright.dev/docs/locators).
+ * Returns the return value of `pageFunction`.
*
- * Returns `input.value` for the selected `<input>` or `<textarea>` or `<select>` element.
+ * If the function passed to the
+ * [worker.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate) returns a
+ * [Promise], then
+ * [worker.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate) would wait for
+ * the promise to resolve and return its value.
*
- * Throws for non-input elements. However, if the element is inside the `<label>` element that has an associated
- * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the
- * control.
- * @param options
+ * If the function passed to the
+ * [worker.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate) returns a
+ * non-[Serializable] value, then
+ * [worker.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate) returns
+ * `undefined`. Playwright also supports transferring some additional values that are not serializable by `JSON`:
+ * `-0`, `NaN`, `Infinity`, `-Infinity`.
+ * @param pageFunction Function to be evaluated in the worker context.
+ * @param arg Optional argument to pass to `pageFunction`.
*/
- inputValue(options?: {
- /**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
- */
- timeout?: number;
- }): Promise<string>;
-
+ evaluate<R, Arg>(pageFunction: PageFunction<Arg, R>, arg: Arg): Promise<R>;
/**
- * **NOTE** Use locator-based [locator.isChecked([options])](https://playwright.dev/docs/api/class-locator#locator-is-checked)
- * instead. Read more about [locators](https://playwright.dev/docs/locators).
+ * Returns the return value of `pageFunction`.
*
- * Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
+ * If the function passed to the
+ * [worker.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate) returns a
+ * [Promise], then
+ * [worker.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate) would wait for
+ * the promise to resolve and return its value.
+ *
+ * If the function passed to the
+ * [worker.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate) returns a
+ * non-[Serializable] value, then
+ * [worker.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate) returns
+ * `undefined`. Playwright also supports transferring some additional values that are not serializable by `JSON`:
+ * `-0`, `NaN`, `Infinity`, `-Infinity`.
+ * @param pageFunction Function to be evaluated in the worker context.
+ * @param arg Optional argument to pass to `pageFunction`.
*/
- isChecked(): Promise<boolean>;
+ evaluate<R>(pageFunction: PageFunction<void, R>, arg?: any): Promise<R>;
/**
- * **NOTE** Use locator-based
- * [locator.isDisabled([options])](https://playwright.dev/docs/api/class-locator#locator-is-disabled) instead. Read
- * more about [locators](https://playwright.dev/docs/locators).
+ * Returns the return value of `pageFunction` as a {@link JSHandle}.
*
- * Returns whether the element is disabled, the opposite of [enabled](https://playwright.dev/docs/actionability#enabled).
+ * The only difference between
+ * [worker.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate) and
+ * [worker.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate-handle)
+ * is that
+ * [worker.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate-handle)
+ * returns {@link JSHandle}.
+ *
+ * If the function passed to the
+ * [worker.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate-handle)
+ * returns a [Promise], then
+ * [worker.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate-handle)
+ * would wait for the promise to resolve and return its value.
+ * @param pageFunction Function to be evaluated in the worker context.
+ * @param arg Optional argument to pass to `pageFunction`.
*/
- isDisabled(): Promise<boolean>;
-
+ evaluateHandle<R, Arg>(pageFunction: PageFunction<Arg, R>, arg: Arg): Promise<SmartHandle<R>>;
/**
- * **NOTE** Use locator-based
- * [locator.isEditable([options])](https://playwright.dev/docs/api/class-locator#locator-is-editable) instead. Read
- * more about [locators](https://playwright.dev/docs/locators).
+ * Returns the return value of `pageFunction` as a {@link JSHandle}.
*
- * Returns whether the element is [editable](https://playwright.dev/docs/actionability#editable).
+ * The only difference between
+ * [worker.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate) and
+ * [worker.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate-handle)
+ * is that
+ * [worker.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate-handle)
+ * returns {@link JSHandle}.
+ *
+ * If the function passed to the
+ * [worker.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate-handle)
+ * returns a [Promise], then
+ * [worker.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-worker#worker-evaluate-handle)
+ * would wait for the promise to resolve and return its value.
+ * @param pageFunction Function to be evaluated in the worker context.
+ * @param arg Optional argument to pass to `pageFunction`.
*/
- isEditable(): Promise<boolean>;
-
+ evaluateHandle<R>(pageFunction: PageFunction<void, R>, arg?: any): Promise<SmartHandle<R>>;
/**
- * **NOTE** Use locator-based [locator.isEnabled([options])](https://playwright.dev/docs/api/class-locator#locator-is-enabled)
- * instead. Read more about [locators](https://playwright.dev/docs/locators).
- *
- * Returns whether the element is [enabled](https://playwright.dev/docs/actionability#enabled).
+ * Emitted when this dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is
+ * terminated.
*/
- isEnabled(): Promise<boolean>;
+ on(event: 'close', listener: (worker: Worker) => any): this;
/**
- * **NOTE** Use locator-based [locator.isHidden([options])](https://playwright.dev/docs/api/class-locator#locator-is-hidden)
- * instead. Read more about [locators](https://playwright.dev/docs/locators).
- *
- * Returns whether the element is hidden, the opposite of [visible](https://playwright.dev/docs/actionability#visible).
+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.
*/
- isHidden(): Promise<boolean>;
+ once(event: 'close', listener: (worker: Worker) => any): this;
/**
- * **NOTE** Use locator-based [locator.isVisible([options])](https://playwright.dev/docs/api/class-locator#locator-is-visible)
- * instead. Read more about [locators](https://playwright.dev/docs/locators).
- *
- * Returns whether the element is [visible](https://playwright.dev/docs/actionability#visible).
+ * Emitted when this dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is
+ * terminated.
*/
- isVisible(): Promise<boolean>;
+ addListener(event: 'close', listener: (worker: Worker) => any): this;
/**
- * Returns the frame containing the given element.
+ * Removes an event listener added by `on` or `addListener`.
*/
- ownerFrame(): Promise<null|Frame>;
+ removeListener(event: 'close', listener: (worker: Worker) => any): this;
/**
- * **NOTE** Use locator-based [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press)
- * instead. Read more about [locators](https://playwright.dev/docs/locators).
- *
- * Focuses the element, and then uses
- * [keyboard.down(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-down) and
- * [keyboard.up(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-up).
- *
- * `key` can specify the intended
- * [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
- * to generate the text for. A superset of the `key` values can be found
- * [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
- *
- * `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
- * `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
- * etc.
- *
- * Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
- * `ControlOrMeta`.
- *
- * Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
- *
- * If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
- * texts.
- *
- * Shortcuts such as `key: "Control+o"`, `key: "Control++` or `key: "Control+Shift+T"` are supported as well. When
- * specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
- * @param key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
- * @param options
+ * Removes an event listener added by `on` or `addListener`.
*/
- press(key: string, options?: {
- /**
- * Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
- */
- delay?: number;
-
- /**
- * Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
- * can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
- * navigating to inaccessible pages. Defaults to `false`.
- * @deprecated This option will default to `true` in the future.
- */
- noWaitAfter?: boolean;
-
- /**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
- */
- timeout?: number;
- }): Promise<void>;
+ off(event: 'close', listener: (worker: Worker) => any): this;
/**
- * **NOTE** Use locator-based [locator.screenshot([options])](https://playwright.dev/docs/api/class-locator#locator-screenshot)
- * instead. Read more about [locators](https://playwright.dev/docs/locators).
- *
- * This method captures a screenshot of the page, clipped to the size and position of this particular element. If the
- * element is covered by other elements, it will not be actually visible on the screenshot. If the element is a
- * scrollable container, only the currently scrolled content will be visible on the screenshot.
- *
- * This method waits for the [actionability](https://playwright.dev/docs/actionability) checks, then scrolls element into view before taking
- * a screenshot. If the element is detached from DOM, the method throws an error.
- *
- * Returns the buffer with the captured screenshot.
- * @param options
+ * Emitted when this dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is
+ * terminated.
*/
- screenshot(options?: {
- /**
- * When set to `"disabled"`, stops CSS animations, CSS transitions and Web Animations. Animations get different
- * treatment depending on their duration:
- * - finite animations are fast-forwarded to completion, so they'll fire `transitionend` event.
- * - infinite animations are canceled to initial state, and then played over after the screenshot.
- *
- * Defaults to `"allow"` that leaves animations untouched.
- */
- animations?: "disabled"|"allow";
-
- /**
- * When set to `"hide"`, screenshot will hide text caret. When set to `"initial"`, text caret behavior will not be
- * changed. Defaults to `"hide"`.
- */
- caret?: "hide"|"initial";
-
- /**
- * Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink
- * box `#FF00FF` (customized by `maskColor`) that completely covers its bounding box.
- */
- mask?: Array<Locator>;
-
- /**
- * Specify the color of the overlay box for masked elements, in
- * [CSS color format](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). Default color is pink `#FF00FF`.
- */
- maskColor?: string;
-
- /**
- * Hides default white background and allows capturing screenshots with transparency. Not applicable to `jpeg` images.
- * Defaults to `false`.
- */
- omitBackground?: boolean;
-
- /**
- * The file path to save the image to. The screenshot type will be inferred from file extension. If `path` is a
- * relative path, then it is resolved relative to the current working directory. If no path is provided, the image
- * won't be saved to the disk.
- */
- path?: string;
-
- /**
- * The quality of the image, between 0-100. Not applicable to `png` images.
- */
- quality?: number;
-
- /**
- * When set to `"css"`, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this
- * will keep screenshots small. Using `"device"` option will produce a single pixel per each device pixel, so
- * screenshots of high-dpi devices will be twice as large or even larger.
- *
- * Defaults to `"device"`.
- */
- scale?: "css"|"device";
-
- /**
- * Text of the stylesheet to apply while making the screenshot. This is where you can hide dynamic elements, make
- * elements invisible or change their properties to help you creating repeatable screenshots. This stylesheet pierces
- * the Shadow DOM and applies to the inner frames.
- */
- style?: string;
-
- /**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
- */
- timeout?: number;
+ prependListener(event: 'close', listener: (worker: Worker) => any): this;
- /**
- * Specify screenshot type, defaults to `png`.
- */
- type?: "png"|"jpeg";
- }): Promise<Buffer>;
+ url(): string;
+}
+/**
+ * JSHandle represents an in-page JavaScript object. JSHandles can be created with the
+ * [page.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-page#page-evaluate-handle) method.
+ *
+ * ```js
+ * const windowHandle = await page.evaluateHandle(() => window);
+ * // ...
+ * ```
+ *
+ * JSHandle prevents the referenced JavaScript object being garbage collected unless the handle is exposed with
+ * [jsHandle.dispose()](https://playwright.dev/docs/api/class-jshandle#js-handle-dispose). JSHandles are auto-disposed
+ * when their origin frame gets navigated or the parent context gets destroyed.
+ *
+ * JSHandle instances can be used as an argument in
+ * [page.$eval(selector, pageFunction[, arg, options])](https://playwright.dev/docs/api/class-page#page-eval-on-selector),
+ * [page.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-page#page-evaluate) and
+ * [page.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-page#page-evaluate-handle)
+ * methods.
+ */
+export interface JSHandle<T = any> {
/**
- * **NOTE** Use locator-based
- * [locator.scrollIntoViewIfNeeded([options])](https://playwright.dev/docs/api/class-locator#locator-scroll-into-view-if-needed)
- * instead. Read more about [locators](https://playwright.dev/docs/locators).
+ * Returns the return value of `pageFunction`.
*
- * This method waits for [actionability](https://playwright.dev/docs/actionability) checks, then tries to scroll element into view, unless
- * it is completely visible as defined by
- * [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)'s `ratio`.
+ * This method passes this handle as the first argument to `pageFunction`.
*
- * Throws when `elementHandle` does not point to an element
- * [connected](https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected) to a Document or a ShadowRoot.
+ * If `pageFunction` returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return its
+ * value.
*
- * See [scrolling](https://playwright.dev/docs/input#scrolling) for alternative ways to scroll.
- * @param options
- */
- scrollIntoViewIfNeeded(options?: {
- /**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
- */
- timeout?: number;
- }): Promise<void>;
-
- /**
- * **NOTE** Use locator-based
- * [locator.selectOption(values[, options])](https://playwright.dev/docs/api/class-locator#locator-select-option)
- * instead. Read more about [locators](https://playwright.dev/docs/locators).
+ * **Usage**
*
- * This method waits for [actionability](https://playwright.dev/docs/actionability) checks, waits until all specified options are present in
- * the `<select>` element and selects these options.
+ * ```js
+ * const tweetHandle = await page.$('.tweet .retweets');
+ * expect(await tweetHandle.evaluate(node => node.innerText)).toBe('10 retweets');
+ * ```
*
- * If the target element is not a `<select>` element, this method throws an error. However, if the element is inside
- * the `<label>` element that has an associated
- * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be used
- * instead.
+ * @param pageFunction Function to be evaluated in the page context.
+ * @param arg Optional argument to pass to `pageFunction`.
+ */
+ evaluate<R, Arg, O extends T = T>(pageFunction: PageFunctionOn<O, Arg, R>, arg: Arg): Promise<R>;
+ /**
+ * Returns the return value of `pageFunction`.
*
- * Returns the array of option values that have been successfully selected.
+ * This method passes this handle as the first argument to `pageFunction`.
*
- * Triggers a `change` and `input` event once all the provided options have been selected.
+ * If `pageFunction` returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return its
+ * value.
*
* **Usage**
*
* ```js
- * // Single selection matching the value or label
- * handle.selectOption('blue');
- *
- * // single selection matching the label
- * handle.selectOption({ label: 'Blue' });
- *
- * // multiple selection
- * handle.selectOption(['red', 'green', 'blue']);
+ * const tweetHandle = await page.$('.tweet .retweets');
+ * expect(await tweetHandle.evaluate(node => node.innerText)).toBe('10 retweets');
* ```
*
- * @param values Options to select. If the `<select>` has the `multiple` attribute, all matching options are selected, otherwise
- * only the first option matching one of the passed options is selected. String values are matching both values and
- * labels. Option is considered matching if all specified properties match.
- * @param options
+ * @param pageFunction Function to be evaluated in the page context.
+ * @param arg Optional argument to pass to `pageFunction`.
*/
- selectOption(values: null|string|ElementHandle|ReadonlyArray<string>|{
- /**
- * Matches by `option.value`. Optional.
- */
- value?: string;
-
- /**
- * Matches by `option.label`. Optional.
- */
- label?: string;
-
- /**
- * Matches by the index. Optional.
- */
- index?: number;
- }|ReadonlyArray<ElementHandle>|ReadonlyArray<{
- /**
- * Matches by `option.value`. Optional.
- */
- value?: string;
-
- /**
- * Matches by `option.label`. Optional.
- */
- label?: string;
-
- /**
- * Matches by the index. Optional.
- */
- index?: number;
- }>, options?: {
- /**
- * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
- */
- force?: boolean;
-
- /**
- * Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
- * can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
- * navigating to inaccessible pages. Defaults to `false`.
- * @deprecated This option will default to `true` in the future.
- */
- noWaitAfter?: boolean;
-
- /**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
- */
- timeout?: number;
- }): Promise<Array<string>>;
+ evaluate<R, O extends T = T>(pageFunction: PageFunctionOn<O, void, R>, arg?: any): Promise<R>;
/**
- * **NOTE** Use locator-based
- * [locator.selectText([options])](https://playwright.dev/docs/api/class-locator#locator-select-text) instead. Read
- * more about [locators](https://playwright.dev/docs/locators).
+ * Returns the return value of `pageFunction` as a {@link JSHandle}.
*
- * This method waits for [actionability](https://playwright.dev/docs/actionability) checks, then focuses the element and selects all its
- * text content.
+ * This method passes this handle as the first argument to `pageFunction`.
*
- * If the element is inside the `<label>` element that has an associated
- * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), focuses and selects text in
- * the control instead.
- * @param options
+ * The only difference between `jsHandle.evaluate` and `jsHandle.evaluateHandle` is that `jsHandle.evaluateHandle`
+ * returns {@link JSHandle}.
+ *
+ * If the function passed to the `jsHandle.evaluateHandle` returns a [Promise], then `jsHandle.evaluateHandle` would
+ * wait for the promise to resolve and return its value.
+ *
+ * See [page.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-page#page-evaluate-handle) for
+ * more details.
+ * @param pageFunction Function to be evaluated in the page context.
+ * @param arg Optional argument to pass to `pageFunction`.
*/
- selectText(options?: {
- /**
- * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
- */
- force?: boolean;
-
- /**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
- */
- timeout?: number;
- }): Promise<void>;
-
+ evaluateHandle<R, Arg, O extends T = T>(pageFunction: PageFunctionOn<O, Arg, R>, arg: Arg): Promise<SmartHandle<R>>;
/**
- * **NOTE** Use locator-based
- * [locator.setChecked(checked[, options])](https://playwright.dev/docs/api/class-locator#locator-set-checked)
- * instead. Read more about [locators](https://playwright.dev/docs/locators).
+ * Returns the return value of `pageFunction` as a {@link JSHandle}.
*
- * This method checks or unchecks an element by performing the following steps:
- * 1. Ensure that element is a checkbox or a radio input. If not, this method throws.
- * 1. If the element already has the right checked state, this method returns immediately.
- * 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the matched element, unless `force` option is set. If
- * the element is detached during the checks, the whole action is retried.
- * 1. Scroll the element into view if needed.
- * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to click in the center of the
- * element.
- * 1. Ensure that the element is now checked or unchecked. If not, this method throws.
+ * This method passes this handle as the first argument to `pageFunction`.
*
- * When all steps combined have not finished during the specified `timeout`, this method throws a {@link
- * TimeoutError}. Passing zero timeout disables this.
- * @param checked Whether to check or uncheck the checkbox.
- * @param options
+ * The only difference between `jsHandle.evaluate` and `jsHandle.evaluateHandle` is that `jsHandle.evaluateHandle`
+ * returns {@link JSHandle}.
+ *
+ * If the function passed to the `jsHandle.evaluateHandle` returns a [Promise], then `jsHandle.evaluateHandle` would
+ * wait for the promise to resolve and return its value.
+ *
+ * See [page.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-page#page-evaluate-handle) for
+ * more details.
+ * @param pageFunction Function to be evaluated in the page context.
+ * @param arg Optional argument to pass to `pageFunction`.
*/
- setChecked(checked: boolean, options?: {
- /**
- * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
- */
- force?: boolean;
-
- /**
- * This option has no effect.
- * @deprecated This option has no effect.
- */
- noWaitAfter?: boolean;
-
- /**
- * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- * the element.
- */
- position?: {
- x: number;
-
- y: number;
- };
-
- /**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
- */
- timeout?: number;
-
- /**
- * When set, this method only performs the [actionability](https://playwright.dev/docs/actionability) checks and skips the action. Defaults
- * to `false`. Useful to wait until the element is ready for the action without performing it.
- */
- trial?: boolean;
- }): Promise<void>;
+ evaluateHandle<R, O extends T = T>(pageFunction: PageFunctionOn<O, void, R>, arg?: any): Promise<SmartHandle<R>>;
/**
- * **NOTE** Use locator-based
- * [locator.setInputFiles(files[, options])](https://playwright.dev/docs/api/class-locator#locator-set-input-files)
- * instead. Read more about [locators](https://playwright.dev/docs/locators).
- *
- * Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then
- * they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs
- * with a `[webkitdirectory]` attribute, only a single directory path is supported.
+ * Returns a JSON representation of the object. If the object has a `toJSON` function, it **will not be called**.
*
- * This method expects {@link ElementHandle} to point to an
- * [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). However, if the element is inside
- * the `<label>` element that has an associated
- * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), targets the control instead.
- * @param files
- * @param options
+ * **NOTE** The method will return an empty JSON object if the referenced object is not stringifiable. It will throw
+ * an error if the object has circular references.
*/
- setInputFiles(files: string|ReadonlyArray<string>|{
- /**
- * File name
- */
- name: string;
-
- /**
- * File type
- */
- mimeType: string;
-
- /**
- * File content
- */
- buffer: Buffer;
- }|ReadonlyArray<{
- /**
- * File name
- */
- name: string;
-
- /**
- * File type
- */
- mimeType: string;
-
- /**
- * File content
- */
- buffer: Buffer;
- }>, options?: {
- /**
- * This option has no effect.
- * @deprecated This option has no effect.
- */
- noWaitAfter?: boolean;
-
- /**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
- */
- timeout?: number;
- }): Promise<void>;
+ jsonValue(): Promise<T>;
+ /**
+ * Returns either `null` or the object handle itself, if the object handle is an instance of {@link ElementHandle}.
+ */
+ asElement(): T extends Node ? ElementHandle<T> : null;
+ /**
+ * The `jsHandle.dispose` method stops referencing the element handle.
+ */
+ dispose(): Promise<void>;
/**
- * **NOTE** Use locator-based [locator.tap([options])](https://playwright.dev/docs/api/class-locator#locator-tap) instead. Read
- * more about [locators](https://playwright.dev/docs/locators).
- *
- * This method taps the element by performing the following steps:
- * 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
- * 1. Scroll the element into view if needed.
- * 1. Use [page.touchscreen](https://playwright.dev/docs/api/class-page#page-touchscreen) to tap the center of the
- * element, or the specified `position`.
+ * The method returns a map with **own property names** as keys and JSHandle instances for the property values.
*
- * If the element is detached from the DOM at any moment during the action, this method throws.
+ * **Usage**
*
- * When all steps combined have not finished during the specified `timeout`, this method throws a {@link
- * TimeoutError}. Passing zero timeout disables this.
+ * ```js
+ * const handle = await page.evaluateHandle(() => ({ window, document }));
+ * const properties = await handle.getProperties();
+ * const windowHandle = properties.get('window');
+ * const documentHandle = properties.get('document');
+ * await handle.dispose();
+ * ```
*
- * **NOTE** `elementHandle.tap()` requires that the `hasTouch` option of the browser context be set to true.
- * @param options
*/
- tap(options?: {
- /**
- * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
- */
- force?: boolean;
-
- /**
- * Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- * current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- * "Control" on Windows and Linux and to "Meta" on macOS.
- */
- modifiers?: Array<"Alt"|"Control"|"ControlOrMeta"|"Meta"|"Shift">;
-
- /**
- * This option has no effect.
- * @deprecated This option has no effect.
- */
- noWaitAfter?: boolean;
-
- /**
- * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- * the element.
- */
- position?: {
- x: number;
-
- y: number;
- };
+ getProperties(): Promise<Map<string, JSHandle>>;
- /**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
- */
- timeout?: number;
+ /**
+ * Fetches a single property from the referenced object.
+ * @param propertyName property to get
+ */
+ getProperty(propertyName: string): Promise<JSHandle>;
- /**
- * When set, this method only performs the [actionability](https://playwright.dev/docs/actionability) checks and skips the action. Defaults
- * to `false`. Useful to wait until the element is ready for the action without performing it.
- */
- trial?: boolean;
- }): Promise<void>;
+ [Symbol.asyncDispose](): Promise<void>;
+}
+/**
+ * - extends: {@link JSHandle}
+ *
+ * ElementHandle represents an in-page DOM element. ElementHandles can be created with the
+ * [page.$(selector[, options])](https://playwright.dev/docs/api/class-page#page-query-selector) method.
+ *
+ * **NOTE** The use of ElementHandle is discouraged, use {@link Locator} objects and web-first assertions instead.
+ *
+ * ```js
+ * const hrefElement = await page.$('a');
+ * await hrefElement.click();
+ * ```
+ *
+ * ElementHandle prevents DOM element from garbage collection unless the handle is disposed with
+ * [jsHandle.dispose()](https://playwright.dev/docs/api/class-jshandle#js-handle-dispose). ElementHandles are
+ * auto-disposed when their origin frame gets navigated.
+ *
+ * ElementHandle instances can be used as an argument in
+ * [page.$eval(selector, pageFunction[, arg, options])](https://playwright.dev/docs/api/class-page#page-eval-on-selector)
+ * and [page.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-page#page-evaluate) methods.
+ *
+ * The difference between the {@link Locator} and ElementHandle is that the ElementHandle points to a particular
+ * element, while {@link Locator} captures the logic of how to retrieve an element.
+ *
+ * In the example below, handle points to a particular DOM element on page. If that element changes text or is used by
+ * React to render an entirely different component, handle is still pointing to that very DOM element. This can lead
+ * to unexpected behaviors.
+ *
+ * ```js
+ * const handle = await page.$('text=Submit');
+ * // ...
+ * await handle.hover();
+ * await handle.click();
+ * ```
+ *
+ * With the locator, every time the `element` is used, up-to-date DOM element is located in the page using the
+ * selector. So in the snippet below, underlying DOM element is going to be located twice.
+ *
+ * ```js
+ * const locator = page.getByText('Submit');
+ * // ...
+ * await locator.hover();
+ * await locator.click();
+ * ```
+ *
+ */
+export interface ElementHandle<T=Node> extends JSHandle<T> {
/**
- * **NOTE** Use locator-based
- * [locator.textContent([options])](https://playwright.dev/docs/api/class-locator#locator-text-content) instead. Read
- * more about [locators](https://playwright.dev/docs/locators).
+ * **NOTE** Use locator-based [page.locator(selector[, options])](https://playwright.dev/docs/api/class-page#page-locator)
+ * instead. Read more about [locators](https://playwright.dev/docs/locators).
*
- * Returns the `node.textContent`.
+ * The method finds an element matching the specified selector in the `ElementHandle`'s subtree. If no elements match
+ * the selector, returns `null`.
+ * @param selector A selector to query for.
*/
- textContent(): Promise<null|string>;
-
+ $<K extends keyof HTMLElementTagNameMap>(selector: K, options?: { strict: boolean }): Promise<ElementHandleForTag<K> | null>;
/**
- * Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the
- * text.
- *
- * To press a special key, like `Control` or `ArrowDown`, use
- * [elementHandle.press(key[, options])](https://playwright.dev/docs/api/class-elementhandle#element-handle-press).
+ * **NOTE** Use locator-based [page.locator(selector[, options])](https://playwright.dev/docs/api/class-page#page-locator)
+ * instead. Read more about [locators](https://playwright.dev/docs/locators).
*
- * **Usage**
- * @deprecated In most cases, you should use
- * [locator.fill(value[, options])](https://playwright.dev/docs/api/class-locator#locator-fill) instead. You only need
- * to press keys one by one if there is special keyboard handling on the page - in this case use
- * [locator.pressSequentially(text[, options])](https://playwright.dev/docs/api/class-locator#locator-press-sequentially).
- * @param text A text to type into a focused element.
- * @param options
+ * The method finds an element matching the specified selector in the `ElementHandle`'s subtree. If no elements match
+ * the selector, returns `null`.
+ * @param selector A selector to query for.
*/
- type(text: string, options?: {
- /**
- * Time to wait between key presses in milliseconds. Defaults to 0.
- */
- delay?: number;
-
- /**
- * This option has no effect.
- * @deprecated This option has no effect.
- */
- noWaitAfter?: boolean;
-
- /**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
- */
- timeout?: number;
- }): Promise<void>;
+ $(selector: string, options?: { strict: boolean }): Promise<ElementHandle<SVGElement | HTMLElement> | null>;
/**
- * **NOTE** Use locator-based [locator.uncheck([options])](https://playwright.dev/docs/api/class-locator#locator-uncheck)
+ * **NOTE** Use locator-based [page.locator(selector[, options])](https://playwright.dev/docs/api/class-page#page-locator)
* instead. Read more about [locators](https://playwright.dev/docs/locators).
*
- * This method checks the element by performing the following steps:
- * 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
- * unchecked, this method returns immediately.
- * 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
- * 1. Scroll the element into view if needed.
- * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to click in the center of the
- * element.
- * 1. Ensure that the element is now unchecked. If not, this method throws.
- *
- * If the element is detached from the DOM at any moment during the action, this method throws.
+ * The method finds all elements matching the specified selector in the `ElementHandle`s subtree. If no elements match
+ * the selector, returns empty array.
+ * @param selector A selector to query for.
+ */
+ $$<K extends keyof HTMLElementTagNameMap>(selector: K): Promise<ElementHandleForTag<K>[]>;
+ /**
+ * **NOTE** Use locator-based [page.locator(selector[, options])](https://playwright.dev/docs/api/class-page#page-locator)
+ * instead. Read more about [locators](https://playwright.dev/docs/locators).
*
- * When all steps combined have not finished during the specified `timeout`, this method throws a {@link
- * TimeoutError}. Passing zero timeout disables this.
- * @param options
+ * The method finds all elements matching the specified selector in the `ElementHandle`s subtree. If no elements match
+ * the selector, returns empty array.
+ * @param selector A selector to query for.
*/
- uncheck(options?: {
- /**
- * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
- */
- force?: boolean;
-
- /**
- * This option has no effect.
- * @deprecated This option has no effect.
- */
- noWaitAfter?: boolean;
-
- /**
- * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- * the element.
- */
- position?: {
- x: number;
-
- y: number;
- };
-
- /**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
- */
- timeout?: number;
-
- /**
- * When set, this method only performs the [actionability](https://playwright.dev/docs/actionability) checks and skips the action. Defaults
- * to `false`. Useful to wait until the element is ready for the action without performing it.
- */
- trial?: boolean;
- }): Promise<void>;
+ $$(selector: string): Promise<ElementHandle<SVGElement | HTMLElement>[]>;
/**
- * Returns when the element satisfies the `state`.
+ * **NOTE** This method does not wait for the element to pass actionability checks and therefore can lead to the flaky tests.
+ * Use
+ * [locator.evaluate(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate),
+ * other {@link Locator} helper methods or web-first assertions instead.
+ *
+ * Returns the return value of `pageFunction`.
+ *
+ * The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a
+ * first argument to `pageFunction`. If no elements match the selector, the method throws an error.
+ *
+ * If `pageFunction` returns a [Promise], then
+ * [elementHandle.$eval(selector, pageFunction[, arg])](https://playwright.dev/docs/api/class-elementhandle#element-handle-eval-on-selector)
+ * would wait for the promise to resolve and return its value.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const tweetHandle = await page.$('.tweet');
+ * expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');
+ * expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');
+ * ```
+ *
+ * @param selector A selector to query for.
+ * @param pageFunction Function to be evaluated in the page context.
+ * @param arg Optional argument to pass to `pageFunction`.
+ */
+ $eval<K extends keyof HTMLElementTagNameMap, R, Arg>(selector: K, pageFunction: PageFunctionOn<HTMLElementTagNameMap[K], Arg, R>, arg: Arg): Promise<R>;
+ /**
+ * **NOTE** This method does not wait for the element to pass actionability checks and therefore can lead to the flaky tests.
+ * Use
+ * [locator.evaluate(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate),
+ * other {@link Locator} helper methods or web-first assertions instead.
*
- * Depending on the `state` parameter, this method waits for one of the [actionability](https://playwright.dev/docs/actionability) checks to
- * pass. This method throws when the element is detached while waiting, unless waiting for the `"hidden"` state.
- * - `"visible"` Wait until the element is [visible](https://playwright.dev/docs/actionability#visible).
- * - `"hidden"` Wait until the element is [not visible](https://playwright.dev/docs/actionability#visible) or not attached. Note that
- * waiting for hidden does not throw when the element detaches.
- * - `"stable"` Wait until the element is both [visible](https://playwright.dev/docs/actionability#visible) and
- * [stable](https://playwright.dev/docs/actionability#stable).
- * - `"enabled"` Wait until the element is [enabled](https://playwright.dev/docs/actionability#enabled).
- * - `"disabled"` Wait until the element is [not enabled](https://playwright.dev/docs/actionability#enabled).
- * - `"editable"` Wait until the element is [editable](https://playwright.dev/docs/actionability#editable).
+ * Returns the return value of `pageFunction`.
*
- * If the element does not satisfy the condition for the `timeout` milliseconds, this method will throw.
- * @param state A state to wait for, see below for more details.
- * @param options
+ * The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a
+ * first argument to `pageFunction`. If no elements match the selector, the method throws an error.
+ *
+ * If `pageFunction` returns a [Promise], then
+ * [elementHandle.$eval(selector, pageFunction[, arg])](https://playwright.dev/docs/api/class-elementhandle#element-handle-eval-on-selector)
+ * would wait for the promise to resolve and return its value.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const tweetHandle = await page.$('.tweet');
+ * expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');
+ * expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');
+ * ```
+ *
+ * @param selector A selector to query for.
+ * @param pageFunction Function to be evaluated in the page context.
+ * @param arg Optional argument to pass to `pageFunction`.
*/
- waitForElementState(state: "visible"|"hidden"|"stable"|"enabled"|"disabled"|"editable", options?: {
- /**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
- */
- timeout?: number;
- }): Promise<void>;
-}
-
-/**
- * Locators are the central piece of Playwright's auto-waiting and retry-ability. In a nutshell, locators represent a
- * way to find element(s) on the page at any moment. A locator can be created with the
- * [page.locator(selector[, options])](https://playwright.dev/docs/api/class-page#page-locator) method.
- *
- * [Learn more about locators](https://playwright.dev/docs/locators).
- */
-export interface Locator {
+ $eval<R, Arg, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(selector: string, pageFunction: PageFunctionOn<E, Arg, R>, arg: Arg): Promise<R>;
/**
- * Execute JavaScript code in the page, taking the matching element as an argument.
- *
- * **Details**
+ * **NOTE** This method does not wait for the element to pass actionability checks and therefore can lead to the flaky tests.
+ * Use
+ * [locator.evaluate(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate),
+ * other {@link Locator} helper methods or web-first assertions instead.
*
- * Returns the return value of `pageFunction`, called with the matching element as a first argument, and `arg` as a
- * second argument.
+ * Returns the return value of `pageFunction`.
*
- * If `pageFunction` returns a [Promise], this method will wait for the promise to resolve and return its value.
+ * The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a
+ * first argument to `pageFunction`. If no elements match the selector, the method throws an error.
*
- * If `pageFunction` throws or rejects, this method throws.
+ * If `pageFunction` returns a [Promise], then
+ * [elementHandle.$eval(selector, pageFunction[, arg])](https://playwright.dev/docs/api/class-elementhandle#element-handle-eval-on-selector)
+ * would wait for the promise to resolve and return its value.
*
* **Usage**
*
* ```js
- * const tweets = page.locator('.tweet .retweets');
- * expect(await tweets.evaluate(node => node.innerText)).toBe('10 retweets');
+ * const tweetHandle = await page.$('.tweet');
+ * expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');
+ * expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');
* ```
*
+ * @param selector A selector to query for.
* @param pageFunction Function to be evaluated in the page context.
* @param arg Optional argument to pass to `pageFunction`.
- * @param options
*/
- evaluate<R, Arg, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(pageFunction: PageFunctionOn<E, Arg, R>, arg: Arg, options?: {
- timeout?: number;
- }): Promise<R>;
+ $eval<K extends keyof HTMLElementTagNameMap, R>(selector: K, pageFunction: PageFunctionOn<HTMLElementTagNameMap[K], void, R>, arg?: any): Promise<R>;
/**
- * Execute JavaScript code in the page, taking the matching element as an argument.
- *
- * **Details**
+ * **NOTE** This method does not wait for the element to pass actionability checks and therefore can lead to the flaky tests.
+ * Use
+ * [locator.evaluate(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate),
+ * other {@link Locator} helper methods or web-first assertions instead.
*
- * Returns the return value of `pageFunction`, called with the matching element as a first argument, and `arg` as a
- * second argument.
+ * Returns the return value of `pageFunction`.
*
- * If `pageFunction` returns a [Promise], this method will wait for the promise to resolve and return its value.
+ * The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a
+ * first argument to `pageFunction`. If no elements match the selector, the method throws an error.
*
- * If `pageFunction` throws or rejects, this method throws.
+ * If `pageFunction` returns a [Promise], then
+ * [elementHandle.$eval(selector, pageFunction[, arg])](https://playwright.dev/docs/api/class-elementhandle#element-handle-eval-on-selector)
+ * would wait for the promise to resolve and return its value.
*
* **Usage**
*
* ```js
- * const tweets = page.locator('.tweet .retweets');
- * expect(await tweets.evaluate(node => node.innerText)).toBe('10 retweets');
+ * const tweetHandle = await page.$('.tweet');
+ * expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');
+ * expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');
* ```
*
+ * @param selector A selector to query for.
* @param pageFunction Function to be evaluated in the page context.
* @param arg Optional argument to pass to `pageFunction`.
- * @param options
*/
- evaluate<R, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(pageFunction: PageFunctionOn<E, void, R>, options?: {
- timeout?: number;
- }): Promise<R>;
+ $eval<R, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(selector: string, pageFunction: PageFunctionOn<E, void, R>, arg?: any): Promise<R>;
+
/**
- * Execute JavaScript code in the page, taking the matching element as an argument, and return a {@link JSHandle} with
- * the result.
+ * **NOTE** In most cases,
+ * [locator.evaluateAll(pageFunction[, arg])](https://playwright.dev/docs/api/class-locator#locator-evaluate-all),
+ * other {@link Locator} helper methods and web-first assertions do a better job.
*
- * **Details**
+ * Returns the return value of `pageFunction`.
*
- * Returns the return value of `pageFunction` as a{@link JSHandle}, called with the matching element as a first
- * argument, and `arg` as a second argument.
+ * The method finds all elements matching the specified selector in the `ElementHandle`'s subtree and passes an array
+ * of matched elements as a first argument to `pageFunction`.
*
- * The only difference between
- * [locator.evaluate(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate)
- * and
- * [locator.evaluateHandle(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate-handle)
- * is that
- * [locator.evaluateHandle(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate-handle)
- * returns {@link JSHandle}.
+ * If `pageFunction` returns a [Promise], then
+ * [elementHandle.$$eval(selector, pageFunction[, arg])](https://playwright.dev/docs/api/class-elementhandle#element-handle-eval-on-selector-all)
+ * would wait for the promise to resolve and return its value.
*
- * If `pageFunction` returns a [Promise], this method will wait for the promise to resolve and return its value.
+ * **Usage**
*
- * If `pageFunction` throws or rejects, this method throws.
+ * ```html
+ * <div class="feed">
+ * <div class="tweet">Hello!</div>
+ * <div class="tweet">Hi!</div>
+ * </div>
+ * ```
*
- * See [page.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-page#page-evaluate-handle) for
- * more details.
+ * ```js
+ * const feedHandle = await page.$('.feed');
+ * expect(await feedHandle.$$eval('.tweet', nodes =>
+ * nodes.map(n => n.innerText))).toEqual(['Hello!', 'Hi!'],
+ * );
+ * ```
+ *
+ * @param selector A selector to query for.
* @param pageFunction Function to be evaluated in the page context.
* @param arg Optional argument to pass to `pageFunction`.
- * @param options
*/
- evaluateHandle<R, Arg, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(pageFunction: PageFunctionOn<E, Arg, R>, arg: Arg): Promise<SmartHandle<R>>;
+ $$eval<K extends keyof HTMLElementTagNameMap, R, Arg>(selector: K, pageFunction: PageFunctionOn<HTMLElementTagNameMap[K][], Arg, R>, arg: Arg): Promise<R>;
/**
- * Execute JavaScript code in the page, taking the matching element as an argument, and return a {@link JSHandle} with
- * the result.
+ * **NOTE** In most cases,
+ * [locator.evaluateAll(pageFunction[, arg])](https://playwright.dev/docs/api/class-locator#locator-evaluate-all),
+ * other {@link Locator} helper methods and web-first assertions do a better job.
*
- * **Details**
+ * Returns the return value of `pageFunction`.
*
- * Returns the return value of `pageFunction` as a{@link JSHandle}, called with the matching element as a first
- * argument, and `arg` as a second argument.
+ * The method finds all elements matching the specified selector in the `ElementHandle`'s subtree and passes an array
+ * of matched elements as a first argument to `pageFunction`.
*
- * The only difference between
- * [locator.evaluate(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate)
- * and
- * [locator.evaluateHandle(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate-handle)
- * is that
- * [locator.evaluateHandle(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate-handle)
- * returns {@link JSHandle}.
+ * If `pageFunction` returns a [Promise], then
+ * [elementHandle.$$eval(selector, pageFunction[, arg])](https://playwright.dev/docs/api/class-elementhandle#element-handle-eval-on-selector-all)
+ * would wait for the promise to resolve and return its value.
*
- * If `pageFunction` returns a [Promise], this method will wait for the promise to resolve and return its value.
+ * **Usage**
*
- * If `pageFunction` throws or rejects, this method throws.
+ * ```html
+ * <div class="feed">
+ * <div class="tweet">Hello!</div>
+ * <div class="tweet">Hi!</div>
+ * </div>
+ * ```
*
- * See [page.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-page#page-evaluate-handle) for
- * more details.
+ * ```js
+ * const feedHandle = await page.$('.feed');
+ * expect(await feedHandle.$$eval('.tweet', nodes =>
+ * nodes.map(n => n.innerText))).toEqual(['Hello!', 'Hi!'],
+ * );
+ * ```
+ *
+ * @param selector A selector to query for.
* @param pageFunction Function to be evaluated in the page context.
* @param arg Optional argument to pass to `pageFunction`.
- * @param options
*/
- evaluateHandle<R, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(pageFunction: PageFunctionOn<E, void, R>): Promise<SmartHandle<R>>;
+ $$eval<R, Arg, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(selector: string, pageFunction: PageFunctionOn<E[], Arg, R>, arg: Arg): Promise<R>;
/**
- * Execute JavaScript code in the page, taking all matching elements as an argument.
- *
- * **Details**
+ * **NOTE** In most cases,
+ * [locator.evaluateAll(pageFunction[, arg])](https://playwright.dev/docs/api/class-locator#locator-evaluate-all),
+ * other {@link Locator} helper methods and web-first assertions do a better job.
*
- * Returns the return value of `pageFunction`, called with an array of all matching elements as a first argument, and
- * `arg` as a second argument.
+ * Returns the return value of `pageFunction`.
*
- * If `pageFunction` returns a [Promise], this method will wait for the promise to resolve and return its value.
+ * The method finds all elements matching the specified selector in the `ElementHandle`'s subtree and passes an array
+ * of matched elements as a first argument to `pageFunction`.
*
- * If `pageFunction` throws or rejects, this method throws.
+ * If `pageFunction` returns a [Promise], then
+ * [elementHandle.$$eval(selector, pageFunction[, arg])](https://playwright.dev/docs/api/class-elementhandle#element-handle-eval-on-selector-all)
+ * would wait for the promise to resolve and return its value.
*
* **Usage**
*
+ * ```html
+ * <div class="feed">
+ * <div class="tweet">Hello!</div>
+ * <div class="tweet">Hi!</div>
+ * </div>
+ * ```
+ *
* ```js
- * const locator = page.locator('div');
- * const moreThanTen = await locator.evaluateAll((divs, min) => divs.length > min, 10);
+ * const feedHandle = await page.$('.feed');
+ * expect(await feedHandle.$$eval('.tweet', nodes =>
+ * nodes.map(n => n.innerText))).toEqual(['Hello!', 'Hi!'],
+ * );
* ```
*
+ * @param selector A selector to query for.
* @param pageFunction Function to be evaluated in the page context.
* @param arg Optional argument to pass to `pageFunction`.
*/
- evaluateAll<R, Arg, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(pageFunction: PageFunctionOn<E[], Arg, R>, arg: Arg): Promise<R>;
+ $$eval<K extends keyof HTMLElementTagNameMap, R>(selector: K, pageFunction: PageFunctionOn<HTMLElementTagNameMap[K][], void, R>, arg?: any): Promise<R>;
/**
- * Execute JavaScript code in the page, taking all matching elements as an argument.
- *
- * **Details**
+ * **NOTE** In most cases,
+ * [locator.evaluateAll(pageFunction[, arg])](https://playwright.dev/docs/api/class-locator#locator-evaluate-all),
+ * other {@link Locator} helper methods and web-first assertions do a better job.
*
- * Returns the return value of `pageFunction`, called with an array of all matching elements as a first argument, and
- * `arg` as a second argument.
+ * Returns the return value of `pageFunction`.
*
- * If `pageFunction` returns a [Promise], this method will wait for the promise to resolve and return its value.
+ * The method finds all elements matching the specified selector in the `ElementHandle`'s subtree and passes an array
+ * of matched elements as a first argument to `pageFunction`.
*
- * If `pageFunction` throws or rejects, this method throws.
+ * If `pageFunction` returns a [Promise], then
+ * [elementHandle.$$eval(selector, pageFunction[, arg])](https://playwright.dev/docs/api/class-elementhandle#element-handle-eval-on-selector-all)
+ * would wait for the promise to resolve and return its value.
*
* **Usage**
*
+ * ```html
+ * <div class="feed">
+ * <div class="tweet">Hello!</div>
+ * <div class="tweet">Hi!</div>
+ * </div>
+ * ```
+ *
* ```js
- * const locator = page.locator('div');
- * const moreThanTen = await locator.evaluateAll((divs, min) => divs.length > min, 10);
+ * const feedHandle = await page.$('.feed');
+ * expect(await feedHandle.$$eval('.tweet', nodes =>
+ * nodes.map(n => n.innerText))).toEqual(['Hello!', 'Hi!'],
+ * );
* ```
*
+ * @param selector A selector to query for.
* @param pageFunction Function to be evaluated in the page context.
* @param arg Optional argument to pass to `pageFunction`.
*/
- evaluateAll<R, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(pageFunction: PageFunctionOn<E[], void, R>): Promise<R>;
+ $$eval<R, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(selector: string, pageFunction: PageFunctionOn<E[], void, R>, arg?: any): Promise<R>;
+
/**
- * **NOTE** Always prefer using {@link Locator}s and web assertions over {@link ElementHandle}s because latter are inherently
- * racy.
+ * **NOTE** Use web assertions that assert visibility or a locator-based
+ * [locator.waitFor([options])](https://playwright.dev/docs/api/class-locator#locator-wait-for) instead.
*
- * Resolves given locator to the first matching DOM element. If there are no matching elements, waits for one. If
- * multiple elements match the locator, throws.
- * @param options
- */
- elementHandle(options?: {
- timeout?: number;
- }): Promise<null|ElementHandle<SVGElement | HTMLElement>>;
- /**
- * When the locator points to a list of elements, this returns an array of locators, pointing to their respective
- * elements.
+ * Returns element specified by selector when it satisfies `state` option. Returns `null` if waiting for `hidden` or
+ * `detached`.
*
- * **NOTE** [locator.all()](https://playwright.dev/docs/api/class-locator#locator-all) does not wait for elements to
- * match the locator, and instead immediately returns whatever is present in the page. When the list of elements
- * changes dynamically, [locator.all()](https://playwright.dev/docs/api/class-locator#locator-all) will produce
- * unpredictable and flaky results. When the list of elements is stable, but loaded dynamically, wait for the full
- * list to finish loading before calling [locator.all()](https://playwright.dev/docs/api/class-locator#locator-all).
+ * Wait for the `selector` relative to the element handle to satisfy `state` option (either appear/disappear from dom,
+ * or become visible/hidden). If at the moment of calling the method `selector` already satisfies the condition, the
+ * method will return immediately. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the
+ * function will throw.
*
* **Usage**
*
* ```js
- * for (const li of await page.getByRole('listitem').all())
- * await li.click();
+ * await page.setContent(`<div><span></span></div>`);
+ * const div = await page.$('div');
+ * // Waiting for the 'span' selector relative to the div.
+ * const span = await div.waitForSelector('span', { state: 'attached' });
* ```
*
+ * **NOTE** This method does not work across navigations, use
+ * [page.waitForSelector(selector[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-selector)
+ * instead.
+ * @param selector A selector to query for.
+ * @param options
*/
- all(): Promise<Array<Locator>>;
-
+ waitForSelector<K extends keyof HTMLElementTagNameMap>(selector: K, options?: ElementHandleWaitForSelectorOptionsNotHidden): Promise<ElementHandleForTag<K>>;
/**
- * Returns an array of `node.innerText` values for all matching nodes.
+ * **NOTE** Use web assertions that assert visibility or a locator-based
+ * [locator.waitFor([options])](https://playwright.dev/docs/api/class-locator#locator-wait-for) instead.
*
- * **NOTE** If you need to assert text on the page, prefer
- * [expect(locator).toHaveText(expected[, options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-have-text)
- * with `useInnerText` option to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
+ * Returns element specified by selector when it satisfies `state` option. Returns `null` if waiting for `hidden` or
+ * `detached`.
+ *
+ * Wait for the `selector` relative to the element handle to satisfy `state` option (either appear/disappear from dom,
+ * or become visible/hidden). If at the moment of calling the method `selector` already satisfies the condition, the
+ * method will return immediately. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the
+ * function will throw.
*
* **Usage**
*
* ```js
- * const texts = await page.getByRole('link').allInnerTexts();
+ * await page.setContent(`<div><span></span></div>`);
+ * const div = await page.$('div');
+ * // Waiting for the 'span' selector relative to the div.
+ * const span = await div.waitForSelector('span', { state: 'attached' });
* ```
*
+ * **NOTE** This method does not work across navigations, use
+ * [page.waitForSelector(selector[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-selector)
+ * instead.
+ * @param selector A selector to query for.
+ * @param options
*/
- allInnerTexts(): Promise<Array<string>>;
-
+ waitForSelector(selector: string, options?: ElementHandleWaitForSelectorOptionsNotHidden): Promise<ElementHandle<SVGElement | HTMLElement>>;
/**
- * Returns an array of `node.textContent` values for all matching nodes.
+ * **NOTE** Use web assertions that assert visibility or a locator-based
+ * [locator.waitFor([options])](https://playwright.dev/docs/api/class-locator#locator-wait-for) instead.
*
- * **NOTE** If you need to assert text on the page, prefer
- * [expect(locator).toHaveText(expected[, options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-have-text)
- * to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
+ * Returns element specified by selector when it satisfies `state` option. Returns `null` if waiting for `hidden` or
+ * `detached`.
+ *
+ * Wait for the `selector` relative to the element handle to satisfy `state` option (either appear/disappear from dom,
+ * or become visible/hidden). If at the moment of calling the method `selector` already satisfies the condition, the
+ * method will return immediately. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the
+ * function will throw.
*
* **Usage**
*
* ```js
- * const texts = await page.getByRole('link').allTextContents();
+ * await page.setContent(`<div><span></span></div>`);
+ * const div = await page.$('div');
+ * // Waiting for the 'span' selector relative to the div.
+ * const span = await div.waitForSelector('span', { state: 'attached' });
* ```
*
+ * **NOTE** This method does not work across navigations, use
+ * [page.waitForSelector(selector[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-selector)
+ * instead.
+ * @param selector A selector to query for.
+ * @param options
*/
- allTextContents(): Promise<Array<string>>;
-
+ waitForSelector<K extends keyof HTMLElementTagNameMap>(selector: K, options: ElementHandleWaitForSelectorOptions): Promise<ElementHandleForTag<K> | null>;
/**
- * Creates a locator that matches both this locator and the argument locator.
+ * **NOTE** Use web assertions that assert visibility or a locator-based
+ * [locator.waitFor([options])](https://playwright.dev/docs/api/class-locator#locator-wait-for) instead.
*
- * **Usage**
+ * Returns element specified by selector when it satisfies `state` option. Returns `null` if waiting for `hidden` or
+ * `detached`.
*
- * The following example finds a button with a specific title.
+ * Wait for the `selector` relative to the element handle to satisfy `state` option (either appear/disappear from dom,
+ * or become visible/hidden). If at the moment of calling the method `selector` already satisfies the condition, the
+ * method will return immediately. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the
+ * function will throw.
+ *
+ * **Usage**
*
* ```js
- * const button = page.getByRole('button').and(page.getByTitle('Subscribe'));
+ * await page.setContent(`<div><span></span></div>`);
+ * const div = await page.$('div');
+ * // Waiting for the 'span' selector relative to the div.
+ * const span = await div.waitForSelector('span', { state: 'attached' });
* ```
*
- * @param locator Additional locator to match.
- */
- and(locator: Locator): Locator;
-
- /**
- * Calls [blur](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/blur) on the element.
+ * **NOTE** This method does not work across navigations, use
+ * [page.waitForSelector(selector[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-selector)
+ * instead.
+ * @param selector A selector to query for.
* @param options
*/
- blur(options?: {
- /**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
- */
- timeout?: number;
- }): Promise<void>;
-
+ waitForSelector(selector: string, options: ElementHandleWaitForSelectorOptions): Promise<null|ElementHandle<SVGElement | HTMLElement>>;
/**
- * This method returns the bounding box of the element matching the locator, or `null` if the element is not visible.
- * The bounding box is calculated relative to the main frame viewport - which is usually the same as the browser
- * window.
- *
- * **Details**
+ * This method returns the bounding box of the element, or `null` if the element is not visible. The bounding box is
+ * calculated relative to the main frame viewport - which is usually the same as the browser window.
*
* Scrolling affects the returned bounding box, similarly to
* [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
@@ -11009,21 +10334,12 @@ export interface Locator {
* **Usage**
*
* ```js
- * const box = await page.getByRole('button').boundingBox();
+ * const box = await elementHandle.boundingBox();
* await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
* ```
*
- * @param options
*/
- boundingBox(options?: {
- /**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
- */
- timeout?: number;
- }): Promise<null|{
+ boundingBox(): Promise<null|{
/**
* the x coordinate of the element in pixels.
*/
@@ -11046,11 +10362,10 @@ export interface Locator {
}>;
/**
- * Ensure that checkbox or radio element is checked.
- *
- * **Details**
+ * **NOTE** Use locator-based [locator.check([options])](https://playwright.dev/docs/api/class-locator#locator-check) instead.
+ * Read more about [locators](https://playwright.dev/docs/locators).
*
- * Performs the following steps:
+ * This method checks the element by performing the following steps:
* 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
* checked, this method returns immediately.
* 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
@@ -11063,13 +10378,6 @@ export interface Locator {
*
* When all steps combined have not finished during the specified `timeout`, this method throws a {@link
* TimeoutError}. Passing zero timeout disables this.
- *
- * **Usage**
- *
- * ```js
- * await page.getByRole('checkbox').check();
- * ```
- *
* @param options
*/
check(options?: {
@@ -11110,38 +10418,68 @@ export interface Locator {
}): Promise<void>;
/**
- * Clear the input field.
- *
- * **Details**
- *
- * This method waits for [actionability](https://playwright.dev/docs/actionability) checks, focuses the element, clears it and triggers an
- * `input` event after clearing.
- *
- * If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
- * error. However, if the element is inside the `<label>` element that has an associated
- * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be cleared
- * instead.
+ * **NOTE** Use locator-based [locator.click([options])](https://playwright.dev/docs/api/class-locator#locator-click) instead.
+ * Read more about [locators](https://playwright.dev/docs/locators).
*
- * **Usage**
+ * This method clicks the element by performing the following steps:
+ * 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
+ * 1. Scroll the element into view if needed.
+ * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to click in the center of the
+ * element, or the specified `position`.
+ * 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
*
- * ```js
- * await page.getByRole('textbox').clear();
- * ```
+ * If the element is detached from the DOM at any moment during the action, this method throws.
*
+ * When all steps combined have not finished during the specified `timeout`, this method throws a {@link
+ * TimeoutError}. Passing zero timeout disables this.
* @param options
*/
- clear(options?: {
+ click(options?: {
+ /**
+ * Defaults to `left`.
+ */
+ button?: "left"|"right"|"middle";
+
+ /**
+ * defaults to 1. See [UIEvent.detail].
+ */
+ clickCount?: number;
+
+ /**
+ * Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
+ */
+ delay?: number;
+
/**
* Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
*/
force?: boolean;
/**
- * This option has no effect.
- * @deprecated This option has no effect.
+ * Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
+ * current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
+ * "Control" on Windows and Linux and to "Meta" on macOS.
+ */
+ modifiers?: Array<"Alt"|"Control"|"ControlOrMeta"|"Meta"|"Shift">;
+
+ /**
+ * Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
+ * can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
+ * navigating to inaccessible pages. Defaults to `false`.
+ * @deprecated This option will default to `true` in the future.
*/
noWaitAfter?: boolean;
+ /**
+ * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
+ * the element.
+ */
+ position?: {
+ x: number;
+
+ y: number;
+ };
+
/**
* Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
* option in the config, or by using the
@@ -11149,56 +10487,43 @@ export interface Locator {
* or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
timeout?: number;
+
+ /**
+ * When set, this method only performs the [actionability](https://playwright.dev/docs/actionability) checks and skips the action. Defaults
+ * to `false`. Useful to wait until the element is ready for the action without performing it.
+ */
+ trial?: boolean;
}): Promise<void>;
/**
- * Click an element.
- *
- * **Details**
+ * Returns the content frame for element handles referencing iframe nodes, or `null` otherwise
+ */
+ contentFrame(): Promise<null|Frame>;
+
+ /**
+ * **NOTE** Use locator-based [locator.dblclick([options])](https://playwright.dev/docs/api/class-locator#locator-dblclick)
+ * instead. Read more about [locators](https://playwright.dev/docs/locators).
*
- * This method clicks the element by performing the following steps:
+ * This method double clicks the element by performing the following steps:
* 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
* 1. Scroll the element into view if needed.
- * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to click in the center of the
+ * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to double click in the center of the
* element, or the specified `position`.
- * 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
*
* If the element is detached from the DOM at any moment during the action, this method throws.
*
* When all steps combined have not finished during the specified `timeout`, this method throws a {@link
* TimeoutError}. Passing zero timeout disables this.
*
- * **Usage**
- *
- * Click a button:
- *
- * ```js
- * await page.getByRole('button').click();
- * ```
- *
- * Shift-right-click at a specific position on a canvas:
- *
- * ```js
- * await page.locator('canvas').click({
- * button: 'right',
- * modifiers: ['Shift'],
- * position: { x: 23, y: 32 },
- * });
- * ```
- *
+ * **NOTE** `elementHandle.dblclick()` dispatches two `click` events and a single `dblclick` event.
* @param options
*/
- click(options?: {
+ dblclick(options?: {
/**
* Defaults to `left`.
*/
button?: "left"|"right"|"middle";
- /**
- * defaults to 1. See [UIEvent.detail].
- */
- clickCount?: number;
-
/**
* Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
*/
@@ -11217,10 +10542,8 @@ export interface Locator {
modifiers?: Array<"Alt"|"Control"|"ControlOrMeta"|"Meta"|"Shift">;
/**
- * Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
- * can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
- * navigating to inaccessible pages. Defaults to `false`.
- * @deprecated This option will default to `true` in the future.
+ * This option has no effect.
+ * @deprecated This option has no effect.
*/
noWaitAfter?: boolean;
@@ -11250,72 +10573,121 @@ export interface Locator {
}): Promise<void>;
/**
- * Returns a {@link FrameLocator} object pointing to the same `iframe` as this locator.
- *
- * Useful when you have a {@link Locator} object obtained somewhere, and later on would like to interact with the
- * content inside the frame.
+ * **NOTE** Use locator-based
+ * [locator.dispatchEvent(type[, eventInit, options])](https://playwright.dev/docs/api/class-locator#locator-dispatch-event)
+ * instead. Read more about [locators](https://playwright.dev/docs/locators).
*
- * For a reverse operation, use
- * [frameLocator.owner()](https://playwright.dev/docs/api/class-framelocator#frame-locator-owner).
+ * The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the element,
+ * `click` is dispatched. This is equivalent to calling
+ * [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
*
* **Usage**
*
* ```js
- * const locator = page.locator('iframe[name="embedded"]');
- * // ...
- * const frameLocator = locator.contentFrame();
- * await frameLocator.getByRole('button').click();
+ * await elementHandle.dispatchEvent('click');
+ * ```
+ *
+ * Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit`
+ * properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
+ *
+ * Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
+ * - [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent)
+ * - [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent)
+ * - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
+ * - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
+ * - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
+ * - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
+ * - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
+ * - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
+ * - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
+ * - [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent)
+ *
+ * You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
+ *
+ * ```js
+ * // Note you can only create DataTransfer in Chromium and Firefox
+ * const dataTransfer = await page.evaluateHandle(() => new DataTransfer());
+ * await elementHandle.dispatchEvent('dragstart', { dataTransfer });
* ```
*
+ * @param type DOM event type: `"click"`, `"dragstart"`, etc.
+ * @param eventInit Optional event-specific initialization properties.
*/
- contentFrame(): FrameLocator;
+ dispatchEvent(type: string, eventInit?: EvaluationArgument): Promise<void>;
/**
- * Returns the number of elements matching the locator.
+ * **NOTE** Use locator-based [locator.fill(value[, options])](https://playwright.dev/docs/api/class-locator#locator-fill)
+ * instead. Read more about [locators](https://playwright.dev/docs/locators).
*
- * **NOTE** If you need to assert the number of elements on the page, prefer
- * [expect(locator).toHaveCount(count[, options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-have-count)
- * to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
+ * This method waits for [actionability](https://playwright.dev/docs/actionability) checks, focuses the element, fills it and triggers an
+ * `input` event after filling. Note that you can pass an empty string to clear the input field.
*
- * **Usage**
+ * If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
+ * error. However, if the element is inside the `<label>` element that has an associated
+ * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled
+ * instead.
*
- * ```js
- * const count = await page.getByRole('listitem').count();
- * ```
+ * To send fine-grained keyboard events, use
+ * [locator.pressSequentially(text[, options])](https://playwright.dev/docs/api/class-locator#locator-press-sequentially).
+ * @param value Value to set for the `<input>`, `<textarea>` or `[contenteditable]` element.
+ * @param options
+ */
+ fill(value: string, options?: {
+ /**
+ * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
+ */
+ force?: boolean;
+
+ /**
+ * This option has no effect.
+ * @deprecated This option has no effect.
+ */
+ noWaitAfter?: boolean;
+
+ /**
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
+ */
+ timeout?: number;
+ }): Promise<void>;
+
+ /**
+ * **NOTE** Use locator-based [locator.focus([options])](https://playwright.dev/docs/api/class-locator#locator-focus) instead.
+ * Read more about [locators](https://playwright.dev/docs/locators).
*
+ * Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the element.
*/
- count(): Promise<number>;
+ focus(): Promise<void>;
/**
- * Double-click an element.
+ * **NOTE** Use locator-based
+ * [locator.getAttribute(name[, options])](https://playwright.dev/docs/api/class-locator#locator-get-attribute)
+ * instead. Read more about [locators](https://playwright.dev/docs/locators).
*
- * **Details**
+ * Returns element attribute value.
+ * @param name Attribute name to get the value for.
+ */
+ getAttribute(name: string): Promise<null|string>;
+
+ /**
+ * **NOTE** Use locator-based [locator.hover([options])](https://playwright.dev/docs/api/class-locator#locator-hover) instead.
+ * Read more about [locators](https://playwright.dev/docs/locators).
*
- * This method double clicks the element by performing the following steps:
+ * This method hovers over the element by performing the following steps:
* 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
* 1. Scroll the element into view if needed.
- * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to double click in the center of the
+ * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to hover over the center of the
* element, or the specified `position`.
*
* If the element is detached from the DOM at any moment during the action, this method throws.
*
* When all steps combined have not finished during the specified `timeout`, this method throws a {@link
* TimeoutError}. Passing zero timeout disables this.
- *
- * **NOTE** `element.dblclick()` dispatches two `click` events and a single `dblclick` event.
* @param options
*/
- dblclick(options?: {
- /**
- * Defaults to `left`.
- */
- button?: "left"|"right"|"middle";
-
- /**
- * Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
- */
- delay?: number;
-
+ hover(options?: {
/**
* Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
*/
@@ -11360,48 +10732,142 @@ export interface Locator {
}): Promise<void>;
/**
- * Programmatically dispatch an event on the matching element.
- *
- * **Usage**
- *
- * ```js
- * await locator.dispatchEvent('click');
- * ```
+ * **NOTE** Use locator-based [locator.innerHTML([options])](https://playwright.dev/docs/api/class-locator#locator-inner-html)
+ * instead. Read more about [locators](https://playwright.dev/docs/locators).
+ *
+ * Returns the `element.innerHTML`.
+ */
+ innerHTML(): Promise<string>;
+
+ /**
+ * **NOTE** Use locator-based [locator.innerText([options])](https://playwright.dev/docs/api/class-locator#locator-inner-text)
+ * instead. Read more about [locators](https://playwright.dev/docs/locators).
+ *
+ * Returns the `element.innerText`.
+ */
+ innerText(): Promise<string>;
+
+ /**
+ * **NOTE** Use locator-based
+ * [locator.inputValue([options])](https://playwright.dev/docs/api/class-locator#locator-input-value) instead. Read
+ * more about [locators](https://playwright.dev/docs/locators).
+ *
+ * Returns `input.value` for the selected `<input>` or `<textarea>` or `<select>` element.
+ *
+ * Throws for non-input elements. However, if the element is inside the `<label>` element that has an associated
+ * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the
+ * control.
+ * @param options
+ */
+ inputValue(options?: {
+ /**
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
+ */
+ timeout?: number;
+ }): Promise<string>;
+
+ /**
+ * **NOTE** Use locator-based [locator.isChecked([options])](https://playwright.dev/docs/api/class-locator#locator-is-checked)
+ * instead. Read more about [locators](https://playwright.dev/docs/locators).
+ *
+ * Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
+ */
+ isChecked(): Promise<boolean>;
+
+ /**
+ * **NOTE** Use locator-based
+ * [locator.isDisabled([options])](https://playwright.dev/docs/api/class-locator#locator-is-disabled) instead. Read
+ * more about [locators](https://playwright.dev/docs/locators).
+ *
+ * Returns whether the element is disabled, the opposite of [enabled](https://playwright.dev/docs/actionability#enabled).
+ */
+ isDisabled(): Promise<boolean>;
+
+ /**
+ * **NOTE** Use locator-based
+ * [locator.isEditable([options])](https://playwright.dev/docs/api/class-locator#locator-is-editable) instead. Read
+ * more about [locators](https://playwright.dev/docs/locators).
+ *
+ * Returns whether the element is [editable](https://playwright.dev/docs/actionability#editable).
+ */
+ isEditable(): Promise<boolean>;
+
+ /**
+ * **NOTE** Use locator-based [locator.isEnabled([options])](https://playwright.dev/docs/api/class-locator#locator-is-enabled)
+ * instead. Read more about [locators](https://playwright.dev/docs/locators).
+ *
+ * Returns whether the element is [enabled](https://playwright.dev/docs/actionability#enabled).
+ */
+ isEnabled(): Promise<boolean>;
+
+ /**
+ * **NOTE** Use locator-based [locator.isHidden([options])](https://playwright.dev/docs/api/class-locator#locator-is-hidden)
+ * instead. Read more about [locators](https://playwright.dev/docs/locators).
+ *
+ * Returns whether the element is hidden, the opposite of [visible](https://playwright.dev/docs/actionability#visible).
+ */
+ isHidden(): Promise<boolean>;
+
+ /**
+ * **NOTE** Use locator-based [locator.isVisible([options])](https://playwright.dev/docs/api/class-locator#locator-is-visible)
+ * instead. Read more about [locators](https://playwright.dev/docs/locators).
+ *
+ * Returns whether the element is [visible](https://playwright.dev/docs/actionability#visible).
+ */
+ isVisible(): Promise<boolean>;
+
+ /**
+ * Returns the frame containing the given element.
+ */
+ ownerFrame(): Promise<null|Frame>;
+
+ /**
+ * **NOTE** Use locator-based [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press)
+ * instead. Read more about [locators](https://playwright.dev/docs/locators).
*
- * **Details**
+ * Focuses the element, and then uses
+ * [keyboard.down(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-down) and
+ * [keyboard.up(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-up).
*
- * The snippet above dispatches the `click` event on the element. Regardless of the visibility state of the element,
- * `click` is dispatched. This is equivalent to calling
- * [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
+ * `key` can specify the intended
+ * [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
+ * to generate the text for. A superset of the `key` values can be found
+ * [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
*
- * Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit`
- * properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
+ * `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
+ * `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
+ * etc.
*
- * Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
- * - [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent)
- * - [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent)
- * - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
- * - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
- * - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
- * - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
- * - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
- * - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
- * - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
- * - [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent)
+ * Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
+ * `ControlOrMeta`.
*
- * You can also specify {@link JSHandle} as the property value if you want live objects to be passed into the event:
+ * Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
*
- * ```js
- * // Note you can only create DataTransfer in Chromium and Firefox
- * const dataTransfer = await page.evaluateHandle(() => new DataTransfer());
- * await locator.dispatchEvent('dragstart', { dataTransfer });
- * ```
+ * If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
+ * texts.
*
- * @param type DOM event type: `"click"`, `"dragstart"`, etc.
- * @param eventInit Optional event-specific initialization properties.
+ * Shortcuts such as `key: "Control+o"`, `key: "Control++` or `key: "Control+Shift+T"` are supported as well. When
+ * specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
+ * @param key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
* @param options
*/
- dispatchEvent(type: string, eventInit?: EvaluationArgument, options?: {
+ press(key: string, options?: {
+ /**
+ * Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
+ */
+ delay?: number;
+
+ /**
+ * Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
+ * can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
+ * navigating to inaccessible pages. Defaults to `false`.
+ * @deprecated This option will default to `true` in the future.
+ */
+ noWaitAfter?: boolean;
+
/**
* Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
* option in the config, or by using the
@@ -11412,61 +10878,81 @@ export interface Locator {
}): Promise<void>;
/**
- * Drag the source element towards the target element and drop it.
- *
- * **Details**
- *
- * This method drags the locator to another target locator or target position. It will first move to the source
- * element, perform a `mousedown`, then move to the target element or position and perform a `mouseup`.
- *
- * **Usage**
+ * **NOTE** Use locator-based [locator.screenshot([options])](https://playwright.dev/docs/api/class-locator#locator-screenshot)
+ * instead. Read more about [locators](https://playwright.dev/docs/locators).
*
- * ```js
- * const source = page.locator('#source');
- * const target = page.locator('#target');
+ * This method captures a screenshot of the page, clipped to the size and position of this particular element. If the
+ * element is covered by other elements, it will not be actually visible on the screenshot. If the element is a
+ * scrollable container, only the currently scrolled content will be visible on the screenshot.
*
- * await source.dragTo(target);
- * // or specify exact positions relative to the top-left corners of the elements:
- * await source.dragTo(target, {
- * sourcePosition: { x: 34, y: 7 },
- * targetPosition: { x: 10, y: 20 },
- * });
- * ```
+ * This method waits for the [actionability](https://playwright.dev/docs/actionability) checks, then scrolls element into view before taking
+ * a screenshot. If the element is detached from DOM, the method throws an error.
*
- * @param target Locator of the element to drag to.
+ * Returns the buffer with the captured screenshot.
* @param options
*/
- dragTo(target: Locator, options?: {
+ screenshot(options?: {
/**
- * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
+ * When set to `"disabled"`, stops CSS animations, CSS transitions and Web Animations. Animations get different
+ * treatment depending on their duration:
+ * - finite animations are fast-forwarded to completion, so they'll fire `transitionend` event.
+ * - infinite animations are canceled to initial state, and then played over after the screenshot.
+ *
+ * Defaults to `"allow"` that leaves animations untouched.
*/
- force?: boolean;
+ animations?: "disabled"|"allow";
/**
- * This option has no effect.
- * @deprecated This option has no effect.
+ * When set to `"hide"`, screenshot will hide text caret. When set to `"initial"`, text caret behavior will not be
+ * changed. Defaults to `"hide"`.
*/
- noWaitAfter?: boolean;
+ caret?: "hide"|"initial";
/**
- * Clicks on the source element at this point relative to the top-left corner of the element's padding box. If not
- * specified, some visible point of the element is used.
+ * Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink
+ * box `#FF00FF` (customized by `maskColor`) that completely covers its bounding box.
*/
- sourcePosition?: {
- x: number;
+ mask?: Array<Locator>;
- y: number;
- };
+ /**
+ * Specify the color of the overlay box for masked elements, in
+ * [CSS color format](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). Default color is pink `#FF00FF`.
+ */
+ maskColor?: string;
/**
- * Drops on the target element at this point relative to the top-left corner of the element's padding box. If not
- * specified, some visible point of the element is used.
+ * Hides default white background and allows capturing screenshots with transparency. Not applicable to `jpeg` images.
+ * Defaults to `false`.
*/
- targetPosition?: {
- x: number;
+ omitBackground?: boolean;
- y: number;
- };
+ /**
+ * The file path to save the image to. The screenshot type will be inferred from file extension. If `path` is a
+ * relative path, then it is resolved relative to the current working directory. If no path is provided, the image
+ * won't be saved to the disk.
+ */
+ path?: string;
+
+ /**
+ * The quality of the image, between 0-100. Not applicable to `png` images.
+ */
+ quality?: number;
+
+ /**
+ * When set to `"css"`, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this
+ * will keep screenshots small. Using `"device"` option will produce a single pixel per each device pixel, so
+ * screenshots of high-dpi devices will be twice as large or even larger.
+ *
+ * Defaults to `"device"`.
+ */
+ scale?: "css"|"device";
+
+ /**
+ * Text of the stylesheet to apply while making the screenshot. This is where you can hide dynamic elements, make
+ * elements invisible or change their properties to help you creating repeatable screenshots. This stylesheet pierces
+ * the Shadow DOM and applies to the inner frames.
+ */
+ style?: string;
/**
* Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
@@ -11477,56 +10963,27 @@ export interface Locator {
timeout?: number;
/**
- * When set, this method only performs the [actionability](https://playwright.dev/docs/actionability) checks and skips the action. Defaults
- * to `false`. Useful to wait until the element is ready for the action without performing it.
+ * Specify screenshot type, defaults to `png`.
*/
- trial?: boolean;
- }): Promise<void>;
-
- /**
- * **NOTE** Always prefer using {@link Locator}s and web assertions over {@link ElementHandle}s because latter are inherently
- * racy.
- *
- * Resolves given locator to all matching DOM elements. If there are no matching elements, returns an empty list.
- */
- elementHandles(): Promise<Array<ElementHandle>>;
+ type?: "png"|"jpeg";
+ }): Promise<Buffer>;
/**
- * Set a value to the input field.
- *
- * **Usage**
- *
- * ```js
- * await page.getByRole('textbox').fill('example value');
- * ```
- *
- * **Details**
+ * **NOTE** Use locator-based
+ * [locator.scrollIntoViewIfNeeded([options])](https://playwright.dev/docs/api/class-locator#locator-scroll-into-view-if-needed)
+ * instead. Read more about [locators](https://playwright.dev/docs/locators).
*
- * This method waits for [actionability](https://playwright.dev/docs/actionability) checks, focuses the element, fills it and triggers an
- * `input` event after filling. Note that you can pass an empty string to clear the input field.
+ * This method waits for [actionability](https://playwright.dev/docs/actionability) checks, then tries to scroll element into view, unless
+ * it is completely visible as defined by
+ * [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)'s `ratio`.
*
- * If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
- * error. However, if the element is inside the `<label>` element that has an associated
- * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled
- * instead.
+ * Throws when `elementHandle` does not point to an element
+ * [connected](https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected) to a Document or a ShadowRoot.
*
- * To send fine-grained keyboard events, use
- * [locator.pressSequentially(text[, options])](https://playwright.dev/docs/api/class-locator#locator-press-sequentially).
- * @param value Value to set for the `<input>`, `<textarea>` or `[contenteditable]` element.
+ * See [scrolling](https://playwright.dev/docs/input#scrolling) for alternative ways to scroll.
* @param options
*/
- fill(value: string, options?: {
- /**
- * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
- */
- force?: boolean;
-
- /**
- * This option has no effect.
- * @deprecated This option has no effect.
- */
- noWaitAfter?: boolean;
-
+ scrollIntoViewIfNeeded(options?: {
/**
* Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
* option in the config, or by using the
@@ -11537,70 +10994,84 @@ export interface Locator {
}): Promise<void>;
/**
- * This method narrows existing locator according to the options, for example filters by text. It can be chained to
- * filter multiple times.
+ * **NOTE** Use locator-based
+ * [locator.selectOption(values[, options])](https://playwright.dev/docs/api/class-locator#locator-select-option)
+ * instead. Read more about [locators](https://playwright.dev/docs/locators).
+ *
+ * This method waits for [actionability](https://playwright.dev/docs/actionability) checks, waits until all specified options are present in
+ * the `<select>` element and selects these options.
+ *
+ * If the target element is not a `<select>` element, this method throws an error. However, if the element is inside
+ * the `<label>` element that has an associated
+ * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be used
+ * instead.
+ *
+ * Returns the array of option values that have been successfully selected.
+ *
+ * Triggers a `change` and `input` event once all the provided options have been selected.
*
* **Usage**
*
* ```js
- * const rowLocator = page.locator('tr');
- * // ...
- * await rowLocator
- * .filter({ hasText: 'text in column 1' })
- * .filter({ has: page.getByRole('button', { name: 'column 2 button' }) })
- * .screenshot();
+ * // Single selection matching the value or label
+ * handle.selectOption('blue');
+ *
+ * // single selection matching the label
+ * handle.selectOption({ label: 'Blue' });
+ *
+ * // multiple selection
+ * handle.selectOption(['red', 'green', 'blue']);
* ```
*
+ * @param values Options to select. If the `<select>` has the `multiple` attribute, all matching options are selected, otherwise
+ * only the first option matching one of the passed options is selected. String values are matching both values and
+ * labels. Option is considered matching if all specified properties match.
* @param options
*/
- filter(options?: {
+ selectOption(values: null|string|ElementHandle|ReadonlyArray<string>|{
+ /**
+ * Matches by `option.value`. Optional.
+ */
+ value?: string;
+
/**
- * Narrows down the results of the method to those which contain elements matching this relative locator. For example,
- * `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
- *
- * Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
- * the document root. For example, you can find `content` that has `div` in
- * `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
- * div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
- *
- * Note that outer and inner locators must belong to the same frame. Inner locator must not contain {@link
- * FrameLocator}s.
+ * Matches by `option.label`. Optional.
*/
- has?: Locator;
+ label?: string;
/**
- * Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
- * outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
- *
- * Note that outer and inner locators must belong to the same frame. Inner locator must not contain {@link
- * FrameLocator}s.
+ * Matches by the index. Optional.
*/
- hasNot?: Locator;
+ index?: number;
+ }|ReadonlyArray<ElementHandle>|ReadonlyArray<{
+ /**
+ * Matches by `option.value`. Optional.
+ */
+ value?: string;
/**
- * Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
- * When passed a [string], matching is case-insensitive and searches for a substring.
+ * Matches by `option.label`. Optional.
*/
- hasNotText?: string|RegExp;
+ label?: string;
/**
- * Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
- * passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
- * `<article><div>Playwright</div></article>`.
+ * Matches by the index. Optional.
*/
- hasText?: string|RegExp;
- }): Locator;
+ index?: number;
+ }>, options?: {
+ /**
+ * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
+ */
+ force?: boolean;
- /**
- * Returns locator to the first matching element.
- */
- first(): Locator;
+ /**
+ * Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
+ * can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
+ * navigating to inaccessible pages. Defaults to `false`.
+ * @deprecated This option will default to `true` in the future.
+ */
+ noWaitAfter?: boolean;
- /**
- * Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the matching element.
- * @param options
- */
- focus(options?: {
/**
* Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
* option in the config, or by using the
@@ -11608,33 +11079,27 @@ export interface Locator {
* or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
timeout?: number;
- }): Promise<void>;
+ }): Promise<Array<string>>;
/**
- * When working with iframes, you can create a frame locator that will enter the iframe and allow locating elements in
- * that iframe:
- *
- * **Usage**
- *
- * ```js
- * const locator = page.frameLocator('iframe').getByText('Submit');
- * await locator.click();
- * ```
+ * **NOTE** Use locator-based
+ * [locator.selectText([options])](https://playwright.dev/docs/api/class-locator#locator-select-text) instead. Read
+ * more about [locators](https://playwright.dev/docs/locators).
*
- * @param selector A selector to use when resolving DOM element.
- */
- frameLocator(selector: string): FrameLocator;
-
- /**
- * Returns the matching element's attribute value.
+ * This method waits for [actionability](https://playwright.dev/docs/actionability) checks, then focuses the element and selects all its
+ * text content.
*
- * **NOTE** If you need to assert an element's attribute, prefer
- * [expect(locator).toHaveAttribute(name, value[, options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-have-attribute)
- * to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
- * @param name Attribute name to get the value for.
+ * If the element is inside the `<label>` element that has an associated
+ * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), focuses and selects text in
+ * the control instead.
* @param options
*/
- getAttribute(name: string, options?: {
+ selectText(options?: {
+ /**
+ * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
+ */
+ force?: boolean;
+
/**
* Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
* option in the config, or by using the
@@ -11642,342 +11107,246 @@ export interface Locator {
* or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
timeout?: number;
- }): Promise<null|string>;
+ }): Promise<void>;
/**
- * Allows locating elements by their alt text.
- *
- * **Usage**
- *
- * For example, this method will find the image by alt text "Playwright logo":
- *
- * ```html
- * <img alt='Playwright logo'>
- * ```
+ * **NOTE** Use locator-based
+ * [locator.setChecked(checked[, options])](https://playwright.dev/docs/api/class-locator#locator-set-checked)
+ * instead. Read more about [locators](https://playwright.dev/docs/locators).
*
- * ```js
- * await page.getByAltText('Playwright logo').click();
- * ```
+ * This method checks or unchecks an element by performing the following steps:
+ * 1. Ensure that element is a checkbox or a radio input. If not, this method throws.
+ * 1. If the element already has the right checked state, this method returns immediately.
+ * 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the matched element, unless `force` option is set. If
+ * the element is detached during the checks, the whole action is retried.
+ * 1. Scroll the element into view if needed.
+ * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to click in the center of the
+ * element.
+ * 1. Ensure that the element is now checked or unchecked. If not, this method throws.
*
- * @param text Text to locate the element for.
+ * When all steps combined have not finished during the specified `timeout`, this method throws a {@link
+ * TimeoutError}. Passing zero timeout disables this.
+ * @param checked Whether to check or uncheck the checkbox.
* @param options
*/
- getByAltText(text: string|RegExp, options?: {
+ setChecked(checked: boolean, options?: {
/**
- * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- * regular expression. Note that exact match still trims whitespace.
+ * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
*/
- exact?: boolean;
- }): Locator;
+ force?: boolean;
- /**
- * Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
- * `aria-label` attribute.
- *
- * **Usage**
- *
- * For example, this method will find inputs by label "Username" and "Password" in the following DOM:
- *
- * ```html
- * <input aria-label="Username">
- * <label for="password-input">Password:</label>
- * <input id="password-input">
- * ```
- *
- * ```js
- * await page.getByLabel('Username').fill('john');
- * await page.getByLabel('Password').fill('secret');
- * ```
- *
- * @param text Text to locate the element for.
- * @param options
- */
- getByLabel(text: string|RegExp, options?: {
/**
- * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- * regular expression. Note that exact match still trims whitespace.
+ * This option has no effect.
+ * @deprecated This option has no effect.
*/
- exact?: boolean;
- }): Locator;
+ noWaitAfter?: boolean;
- /**
- * Allows locating input elements by the placeholder text.
- *
- * **Usage**
- *
- * For example, consider the following DOM structure.
- *
- * ```html
- * <input type="email" placeholder="[email protected]" />
- * ```
- *
- * You can fill the input after locating it by the placeholder text:
- *
- * ```js
- * await page
- * .getByPlaceholder('[email protected]')
- * .fill('[email protected]');
- * ```
- *
- * @param text Text to locate the element for.
- * @param options
- */
- getByPlaceholder(text: string|RegExp, options?: {
/**
- * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- * regular expression. Note that exact match still trims whitespace.
+ * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
+ * the element.
*/
- exact?: boolean;
- }): Locator;
+ position?: {
+ x: number;
+
+ y: number;
+ };
+
+ /**
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
+ */
+ timeout?: number;
+
+ /**
+ * When set, this method only performs the [actionability](https://playwright.dev/docs/actionability) checks and skips the action. Defaults
+ * to `false`. Useful to wait until the element is ready for the action without performing it.
+ */
+ trial?: boolean;
+ }): Promise<void>;
/**
- * Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
- * [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
- * [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
- *
- * **Usage**
- *
- * Consider the following DOM structure.
- *
- * ```html
- * <h3>Sign up</h3>
- * <label>
- * <input type="checkbox" /> Subscribe
- * </label>
- * <br/>
- * <button>Submit</button>
- * ```
- *
- * You can locate each element by it's implicit role:
- *
- * ```js
- * await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible();
- *
- * await page.getByRole('checkbox', { name: 'Subscribe' }).check();
- *
- * await page.getByRole('button', { name: /submit/i }).click();
- * ```
- *
- * **Details**
+ * **NOTE** Use locator-based
+ * [locator.setInputFiles(files[, options])](https://playwright.dev/docs/api/class-locator#locator-set-input-files)
+ * instead. Read more about [locators](https://playwright.dev/docs/locators).
*
- * Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
- * about the ARIA guidelines.
+ * Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then
+ * they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs
+ * with a `[webkitdirectory]` attribute, only a single directory path is supported.
*
- * Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
- * that is recognized by the role selector. You can find all the
- * [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
- * duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
- * @param role Required aria role.
+ * This method expects {@link ElementHandle} to point to an
+ * [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). However, if the element is inside
+ * the `<label>` element that has an associated
+ * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), targets the control instead.
+ * @param files
* @param options
*/
- getByRole(role: "alert"|"alertdialog"|"application"|"article"|"banner"|"blockquote"|"button"|"caption"|"cell"|"checkbox"|"code"|"columnheader"|"combobox"|"complementary"|"contentinfo"|"definition"|"deletion"|"dialog"|"directory"|"document"|"emphasis"|"feed"|"figure"|"form"|"generic"|"grid"|"gridcell"|"group"|"heading"|"img"|"insertion"|"link"|"list"|"listbox"|"listitem"|"log"|"main"|"marquee"|"math"|"meter"|"menu"|"menubar"|"menuitem"|"menuitemcheckbox"|"menuitemradio"|"navigation"|"none"|"note"|"option"|"paragraph"|"presentation"|"progressbar"|"radio"|"radiogroup"|"region"|"row"|"rowgroup"|"rowheader"|"scrollbar"|"search"|"searchbox"|"separator"|"slider"|"spinbutton"|"status"|"strong"|"subscript"|"superscript"|"switch"|"tab"|"table"|"tablist"|"tabpanel"|"term"|"textbox"|"time"|"timer"|"toolbar"|"tooltip"|"tree"|"treegrid"|"treeitem", options?: {
+ setInputFiles(files: string|ReadonlyArray<string>|{
/**
- * An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.
- *
- * Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).
+ * File name
*/
- checked?: boolean;
+ name: string;
/**
- * An attribute that is usually set by `aria-disabled` or `disabled`.
- *
- * **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about
- * [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).
+ * File type
*/
- disabled?: boolean;
+ mimeType: string;
/**
- * Whether `name` is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when `name` is a
- * regular expression. Note that exact match still trims whitespace.
+ * File content
*/
- exact?: boolean;
+ buffer: Buffer;
+ }|ReadonlyArray<{
+ /**
+ * File name
+ */
+ name: string;
/**
- * An attribute that is usually set by `aria-expanded`.
- *
- * Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).
+ * File type
*/
- expanded?: boolean;
+ mimeType: string;
/**
- * Option that controls whether hidden elements are matched. By default, only non-hidden elements, as
- * [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.
- *
- * Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).
+ * File content
*/
- includeHidden?: boolean;
+ buffer: Buffer;
+ }>, options?: {
+ /**
+ * This option has no effect.
+ * @deprecated This option has no effect.
+ */
+ noWaitAfter?: boolean;
/**
- * A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values
- * for `<h1>-<h6>` elements.
- *
- * Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
- level?: number;
+ timeout?: number;
+ }): Promise<void>;
+
+ /**
+ * **NOTE** Use locator-based [locator.tap([options])](https://playwright.dev/docs/api/class-locator#locator-tap) instead. Read
+ * more about [locators](https://playwright.dev/docs/locators).
+ *
+ * This method taps the element by performing the following steps:
+ * 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
+ * 1. Scroll the element into view if needed.
+ * 1. Use [page.touchscreen](https://playwright.dev/docs/api/class-page#page-touchscreen) to tap the center of the
+ * element, or the specified `position`.
+ *
+ * If the element is detached from the DOM at any moment during the action, this method throws.
+ *
+ * When all steps combined have not finished during the specified `timeout`, this method throws a {@link
+ * TimeoutError}. Passing zero timeout disables this.
+ *
+ * **NOTE** `elementHandle.tap()` requires that the `hasTouch` option of the browser context be set to true.
+ * @param options
+ */
+ tap(options?: {
+ /**
+ * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
+ */
+ force?: boolean;
/**
- * Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is
- * case-insensitive and searches for a substring, use `exact` to control this behavior.
- *
- * Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
+ * Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
+ * current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
+ * "Control" on Windows and Linux and to "Meta" on macOS.
*/
- name?: string|RegExp;
+ modifiers?: Array<"Alt"|"Control"|"ControlOrMeta"|"Meta"|"Shift">;
/**
- * An attribute that is usually set by `aria-pressed`.
- *
- * Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).
+ * This option has no effect.
+ * @deprecated This option has no effect.
*/
- pressed?: boolean;
+ noWaitAfter?: boolean;
/**
- * An attribute that is usually set by `aria-selected`.
- *
- * Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).
+ * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
+ * the element.
*/
- selected?: boolean;
- }): Locator;
+ position?: {
+ x: number;
+
+ y: number;
+ };
+
+ /**
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
+ */
+ timeout?: number;
+
+ /**
+ * When set, this method only performs the [actionability](https://playwright.dev/docs/actionability) checks and skips the action. Defaults
+ * to `false`. Useful to wait until the element is ready for the action without performing it.
+ */
+ trial?: boolean;
+ }): Promise<void>;
/**
- * Locate element by the test id.
- *
- * **Usage**
- *
- * Consider the following DOM structure.
- *
- * ```html
- * <button data-testid="directions">Itinéraire</button>
- * ```
- *
- * You can locate the element by it's test id:
- *
- * ```js
- * await page.getByTestId('directions').click();
- * ```
- *
- * **Details**
- *
- * By default, the `data-testid` attribute is used as a test id. Use
- * [selectors.setTestIdAttribute(attributeName)](https://playwright.dev/docs/api/class-selectors#selectors-set-test-id-attribute)
- * to configure a different test id attribute if necessary.
- *
- * ```js
- * // Set custom test id attribute from @playwright/test config:
- * import { defineConfig } from '@playwright/test';
- *
- * export default defineConfig({
- * use: {
- * testIdAttribute: 'data-pw'
- * },
- * });
- * ```
+ * **NOTE** Use locator-based
+ * [locator.textContent([options])](https://playwright.dev/docs/api/class-locator#locator-text-content) instead. Read
+ * more about [locators](https://playwright.dev/docs/locators).
*
- * @param testId Id to locate the element by.
+ * Returns the `node.textContent`.
*/
- getByTestId(testId: string|RegExp): Locator;
+ textContent(): Promise<null|string>;
/**
- * Allows locating elements that contain given text.
+ * Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the
+ * text.
*
- * See also [locator.filter([options])](https://playwright.dev/docs/api/class-locator#locator-filter) that allows to
- * match by another criteria, like an accessible role, and then filter by the text content.
+ * To press a special key, like `Control` or `ArrowDown`, use
+ * [elementHandle.press(key[, options])](https://playwright.dev/docs/api/class-elementhandle#element-handle-press).
*
* **Usage**
- *
- * Consider the following DOM structure:
- *
- * ```html
- * <div>Hello <span>world</span></div>
- * <div>Hello</div>
- * ```
- *
- * You can locate by text substring, exact string, or a regular expression:
- *
- * ```js
- * // Matches <span>
- * page.getByText('world');
- *
- * // Matches first <div>
- * page.getByText('Hello world');
- *
- * // Matches second <div>
- * page.getByText('Hello', { exact: true });
- *
- * // Matches both <div>s
- * page.getByText(/Hello/);
- *
- * // Matches second <div>
- * page.getByText(/^hello$/i);
- * ```
- *
- * **Details**
- *
- * Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
- * one, turns line breaks into spaces and ignores leading and trailing whitespace.
- *
- * Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
- * example, locating by text `"Log in"` matches `<input type=button value="Log in">`.
- * @param text Text to locate the element for.
+ * @deprecated In most cases, you should use
+ * [locator.fill(value[, options])](https://playwright.dev/docs/api/class-locator#locator-fill) instead. You only need
+ * to press keys one by one if there is special keyboard handling on the page - in this case use
+ * [locator.pressSequentially(text[, options])](https://playwright.dev/docs/api/class-locator#locator-press-sequentially).
+ * @param text A text to type into a focused element.
* @param options
*/
- getByText(text: string|RegExp, options?: {
+ type(text: string, options?: {
/**
- * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- * regular expression. Note that exact match still trims whitespace.
+ * Time to wait between key presses in milliseconds. Defaults to 0.
*/
- exact?: boolean;
- }): Locator;
+ delay?: number;
- /**
- * Allows locating elements by their title attribute.
- *
- * **Usage**
- *
- * Consider the following DOM structure.
- *
- * ```html
- * <span title='Issues count'>25 issues</span>
- * ```
- *
- * You can check the issues count after locating it by the title text:
- *
- * ```js
- * await expect(page.getByTitle('Issues count')).toHaveText('25 issues');
- * ```
- *
- * @param text Text to locate the element for.
- * @param options
- */
- getByTitle(text: string|RegExp, options?: {
/**
- * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
- * regular expression. Note that exact match still trims whitespace.
+ * This option has no effect.
+ * @deprecated This option has no effect.
*/
- exact?: boolean;
- }): Locator;
+ noWaitAfter?: boolean;
- /**
- * Highlight the corresponding element(s) on the screen. Useful for debugging, don't commit the code that uses
- * [locator.highlight()](https://playwright.dev/docs/api/class-locator#locator-highlight).
- */
- highlight(): Promise<void>;
+ /**
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
+ */
+ timeout?: number;
+ }): Promise<void>;
/**
- * Hover over the matching element.
- *
- * **Usage**
- *
- * ```js
- * await page.getByRole('link').hover();
- * ```
- *
- * **Details**
+ * **NOTE** Use locator-based [locator.uncheck([options])](https://playwright.dev/docs/api/class-locator#locator-uncheck)
+ * instead. Read more about [locators](https://playwright.dev/docs/locators).
*
- * This method hovers over the element by performing the following steps:
+ * This method checks the element by performing the following steps:
+ * 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
+ * unchecked, this method returns immediately.
* 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
* 1. Scroll the element into view if needed.
- * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to hover over the center of the
- * element, or the specified `position`.
+ * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to click in the center of the
+ * element.
+ * 1. Ensure that the element is now unchecked. If not, this method throws.
*
* If the element is detached from the DOM at any moment during the action, this method throws.
*
@@ -11985,19 +11354,12 @@ export interface Locator {
* TimeoutError}. Passing zero timeout disables this.
* @param options
*/
- hover(options?: {
+ uncheck(options?: {
/**
* Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
*/
force?: boolean;
- /**
- * Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- * current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- * "Control" on Windows and Linux and to "Meta" on macOS.
- */
- modifiers?: Array<"Alt"|"Control"|"ControlOrMeta"|"Meta"|"Shift">;
-
/**
* This option has no effect.
* @deprecated This option has no effect.
@@ -12030,10 +11392,24 @@ export interface Locator {
}): Promise<void>;
/**
- * Returns the [`element.innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML).
+ * Returns when the element satisfies the `state`.
+ *
+ * Depending on the `state` parameter, this method waits for one of the [actionability](https://playwright.dev/docs/actionability) checks to
+ * pass. This method throws when the element is detached while waiting, unless waiting for the `"hidden"` state.
+ * - `"visible"` Wait until the element is [visible](https://playwright.dev/docs/actionability#visible).
+ * - `"hidden"` Wait until the element is [not visible](https://playwright.dev/docs/actionability#visible) or not attached. Note that
+ * waiting for hidden does not throw when the element detaches.
+ * - `"stable"` Wait until the element is both [visible](https://playwright.dev/docs/actionability#visible) and
+ * [stable](https://playwright.dev/docs/actionability#stable).
+ * - `"enabled"` Wait until the element is [enabled](https://playwright.dev/docs/actionability#enabled).
+ * - `"disabled"` Wait until the element is [not enabled](https://playwright.dev/docs/actionability#enabled).
+ * - `"editable"` Wait until the element is [editable](https://playwright.dev/docs/actionability#editable).
+ *
+ * If the element does not satisfy the condition for the `timeout` milliseconds, this method will throw.
+ * @param state A state to wait for, see below for more details.
* @param options
*/
- innerHTML(options?: {
+ waitForElementState(state: "visible"|"hidden"|"stable"|"enabled"|"disabled"|"editable", options?: {
/**
* Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
* option in the config, or by using the
@@ -12041,353 +11417,367 @@ export interface Locator {
* or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
timeout?: number;
- }): Promise<string>;
+ }): Promise<void>;
+}
+/**
+ * Locators are the central piece of Playwright's auto-waiting and retry-ability. In a nutshell, locators represent a
+ * way to find element(s) on the page at any moment. A locator can be created with the
+ * [page.locator(selector[, options])](https://playwright.dev/docs/api/class-page#page-locator) method.
+ *
+ * [Learn more about locators](https://playwright.dev/docs/locators).
+ */
+export interface Locator {
/**
- * Returns the [`element.innerText`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText).
+ * Execute JavaScript code in the page, taking the matching element as an argument.
*
- * **NOTE** If you need to assert text on the page, prefer
- * [expect(locator).toHaveText(expected[, options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-have-text)
- * with `useInnerText` option to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
+ * **Details**
+ *
+ * Returns the return value of `pageFunction`, called with the matching element as a first argument, and `arg` as a
+ * second argument.
+ *
+ * If `pageFunction` returns a [Promise], this method will wait for the promise to resolve and return its value.
+ *
+ * If `pageFunction` throws or rejects, this method throws.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const tweets = page.locator('.tweet .retweets');
+ * expect(await tweets.evaluate(node => node.innerText)).toBe('10 retweets');
+ * ```
+ *
+ * @param pageFunction Function to be evaluated in the page context.
+ * @param arg Optional argument to pass to `pageFunction`.
* @param options
*/
- innerText(options?: {
- /**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
- */
+ evaluate<R, Arg, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(pageFunction: PageFunctionOn<E, Arg, R>, arg: Arg, options?: {
timeout?: number;
- }): Promise<string>;
-
+ }): Promise<R>;
/**
- * Returns the value for the matching `<input>` or `<textarea>` or `<select>` element.
+ * Execute JavaScript code in the page, taking the matching element as an argument.
*
- * **NOTE** If you need to assert input value, prefer
- * [expect(locator).toHaveValue(value[, options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-have-value)
- * to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
+ * **Details**
+ *
+ * Returns the return value of `pageFunction`, called with the matching element as a first argument, and `arg` as a
+ * second argument.
+ *
+ * If `pageFunction` returns a [Promise], this method will wait for the promise to resolve and return its value.
+ *
+ * If `pageFunction` throws or rejects, this method throws.
*
* **Usage**
*
* ```js
- * const value = await page.getByRole('textbox').inputValue();
+ * const tweets = page.locator('.tweet .retweets');
+ * expect(await tweets.evaluate(node => node.innerText)).toBe('10 retweets');
* ```
*
+ * @param pageFunction Function to be evaluated in the page context.
+ * @param arg Optional argument to pass to `pageFunction`.
+ * @param options
+ */
+ evaluate<R, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(pageFunction: PageFunctionOn<E, void, R>, options?: {
+ timeout?: number;
+ }): Promise<R>;
+ /**
+ * Execute JavaScript code in the page, taking the matching element as an argument, and return a {@link JSHandle} with
+ * the result.
+ *
* **Details**
*
- * Throws elements that are not an input, textarea or a select. However, if the element is inside the `<label>`
- * element that has an associated
- * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the
- * control.
+ * Returns the return value of `pageFunction` as a{@link JSHandle}, called with the matching element as a first
+ * argument, and `arg` as a second argument.
+ *
+ * The only difference between
+ * [locator.evaluate(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate)
+ * and
+ * [locator.evaluateHandle(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate-handle)
+ * is that
+ * [locator.evaluateHandle(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate-handle)
+ * returns {@link JSHandle}.
+ *
+ * If `pageFunction` returns a [Promise], this method will wait for the promise to resolve and return its value.
+ *
+ * If `pageFunction` throws or rejects, this method throws.
+ *
+ * See [page.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-page#page-evaluate-handle) for
+ * more details.
+ * @param pageFunction Function to be evaluated in the page context.
+ * @param arg Optional argument to pass to `pageFunction`.
* @param options
*/
- inputValue(options?: {
- /**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
- */
- timeout?: number;
- }): Promise<string>;
-
+ evaluateHandle<R, Arg, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(pageFunction: PageFunctionOn<E, Arg, R>, arg: Arg): Promise<SmartHandle<R>>;
/**
- * Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
+ * Execute JavaScript code in the page, taking the matching element as an argument, and return a {@link JSHandle} with
+ * the result.
*
- * **NOTE** If you need to assert that checkbox is checked, prefer
- * [expect(locator).toBeChecked([options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-be-checked)
- * to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
+ * **Details**
+ *
+ * Returns the return value of `pageFunction` as a{@link JSHandle}, called with the matching element as a first
+ * argument, and `arg` as a second argument.
+ *
+ * The only difference between
+ * [locator.evaluate(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate)
+ * and
+ * [locator.evaluateHandle(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate-handle)
+ * is that
+ * [locator.evaluateHandle(pageFunction[, arg, options])](https://playwright.dev/docs/api/class-locator#locator-evaluate-handle)
+ * returns {@link JSHandle}.
+ *
+ * If `pageFunction` returns a [Promise], this method will wait for the promise to resolve and return its value.
+ *
+ * If `pageFunction` throws or rejects, this method throws.
+ *
+ * See [page.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-page#page-evaluate-handle) for
+ * more details.
+ * @param pageFunction Function to be evaluated in the page context.
+ * @param arg Optional argument to pass to `pageFunction`.
+ * @param options
+ */
+ evaluateHandle<R, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(pageFunction: PageFunctionOn<E, void, R>): Promise<SmartHandle<R>>;
+ /**
+ * Execute JavaScript code in the page, taking all matching elements as an argument.
+ *
+ * **Details**
+ *
+ * Returns the return value of `pageFunction`, called with an array of all matching elements as a first argument, and
+ * `arg` as a second argument.
+ *
+ * If `pageFunction` returns a [Promise], this method will wait for the promise to resolve and return its value.
+ *
+ * If `pageFunction` throws or rejects, this method throws.
*
* **Usage**
*
* ```js
- * const checked = await page.getByRole('checkbox').isChecked();
+ * const locator = page.locator('div');
+ * const moreThanTen = await locator.evaluateAll((divs, min) => divs.length > min, 10);
+ * ```
+ *
+ * @param pageFunction Function to be evaluated in the page context.
+ * @param arg Optional argument to pass to `pageFunction`.
+ */
+ evaluateAll<R, Arg, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(pageFunction: PageFunctionOn<E[], Arg, R>, arg: Arg): Promise<R>;
+ /**
+ * Execute JavaScript code in the page, taking all matching elements as an argument.
+ *
+ * **Details**
+ *
+ * Returns the return value of `pageFunction`, called with an array of all matching elements as a first argument, and
+ * `arg` as a second argument.
+ *
+ * If `pageFunction` returns a [Promise], this method will wait for the promise to resolve and return its value.
+ *
+ * If `pageFunction` throws or rejects, this method throws.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const locator = page.locator('div');
+ * const moreThanTen = await locator.evaluateAll((divs, min) => divs.length > min, 10);
* ```
*
+ * @param pageFunction Function to be evaluated in the page context.
+ * @param arg Optional argument to pass to `pageFunction`.
+ */
+ evaluateAll<R, E extends SVGElement | HTMLElement = SVGElement | HTMLElement>(pageFunction: PageFunctionOn<E[], void, R>): Promise<R>;
+ /**
+ * **NOTE** Always prefer using {@link Locator}s and web assertions over {@link ElementHandle}s because latter are inherently
+ * racy.
+ *
+ * Resolves given locator to the first matching DOM element. If there are no matching elements, waits for one. If
+ * multiple elements match the locator, throws.
* @param options
*/
- isChecked(options?: {
- /**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
- */
+ elementHandle(options?: {
timeout?: number;
- }): Promise<boolean>;
-
+ }): Promise<null|ElementHandle<SVGElement | HTMLElement>>;
/**
- * Returns whether the element is disabled, the opposite of [enabled](https://playwright.dev/docs/actionability#enabled).
+ * When the locator points to a list of elements, this returns an array of locators, pointing to their respective
+ * elements.
*
- * **NOTE** If you need to assert that an element is disabled, prefer
- * [expect(locator).toBeDisabled([options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-be-disabled)
- * to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
+ * **NOTE** [locator.all()](https://playwright.dev/docs/api/class-locator#locator-all) does not wait for elements to
+ * match the locator, and instead immediately returns whatever is present in the page. When the list of elements
+ * changes dynamically, [locator.all()](https://playwright.dev/docs/api/class-locator#locator-all) will produce
+ * unpredictable and flaky results. When the list of elements is stable, but loaded dynamically, wait for the full
+ * list to finish loading before calling [locator.all()](https://playwright.dev/docs/api/class-locator#locator-all).
*
* **Usage**
*
* ```js
- * const disabled = await page.getByRole('button').isDisabled();
+ * for (const li of await page.getByRole('listitem').all())
+ * await li.click();
* ```
*
- * @param options
*/
- isDisabled(options?: {
- /**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
- */
- timeout?: number;
- }): Promise<boolean>;
+ all(): Promise<Array<Locator>>;
/**
- * Returns whether the element is [editable](https://playwright.dev/docs/actionability#editable).
+ * Returns an array of `node.innerText` values for all matching nodes.
*
- * **NOTE** If you need to assert that an element is editable, prefer
- * [expect(locator).toBeEditable([options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-be-editable)
- * to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
+ * **NOTE** If you need to assert text on the page, prefer
+ * [expect(locator).toHaveText(expected[, options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-have-text)
+ * with `useInnerText` option to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
*
* **Usage**
*
* ```js
- * const editable = await page.getByRole('textbox').isEditable();
+ * const texts = await page.getByRole('link').allInnerTexts();
* ```
*
- * @param options
*/
- isEditable(options?: {
- /**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
- */
- timeout?: number;
- }): Promise<boolean>;
+ allInnerTexts(): Promise<Array<string>>;
/**
- * Returns whether the element is [enabled](https://playwright.dev/docs/actionability#enabled).
+ * Returns an array of `node.textContent` values for all matching nodes.
*
- * **NOTE** If you need to assert that an element is enabled, prefer
- * [expect(locator).toBeEnabled([options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-be-enabled)
+ * **NOTE** If you need to assert text on the page, prefer
+ * [expect(locator).toHaveText(expected[, options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-have-text)
* to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
*
* **Usage**
*
* ```js
- * const enabled = await page.getByRole('button').isEnabled();
+ * const texts = await page.getByRole('link').allTextContents();
* ```
*
- * @param options
*/
- isEnabled(options?: {
- /**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
- */
- timeout?: number;
- }): Promise<boolean>;
+ allTextContents(): Promise<Array<string>>;
/**
- * Returns whether the element is hidden, the opposite of [visible](https://playwright.dev/docs/actionability#visible).
- *
- * **NOTE** If you need to assert that element is hidden, prefer
- * [expect(locator).toBeHidden([options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-be-hidden)
- * to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
+ * Creates a locator that matches both this locator and the argument locator.
*
* **Usage**
*
+ * The following example finds a button with a specific title.
+ *
* ```js
- * const hidden = await page.getByRole('button').isHidden();
+ * const button = page.getByRole('button').and(page.getByTitle('Subscribe'));
* ```
*
+ * @param locator Additional locator to match.
+ */
+ and(locator: Locator): Locator;
+
+ /**
+ * Calls [blur](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/blur) on the element.
* @param options
*/
- isHidden(options?: {
+ blur(options?: {
/**
- * @deprecated This option is ignored.
- * [locator.isHidden([options])](https://playwright.dev/docs/api/class-locator#locator-is-hidden) does not wait for
- * the element to become hidden and returns immediately.
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
timeout?: number;
- }): Promise<boolean>;
+ }): Promise<void>;
/**
- * Returns whether the element is [visible](https://playwright.dev/docs/actionability#visible).
+ * This method returns the bounding box of the element matching the locator, or `null` if the element is not visible.
+ * The bounding box is calculated relative to the main frame viewport - which is usually the same as the browser
+ * window.
*
- * **NOTE** If you need to assert that element is visible, prefer
- * [expect(locator).toBeVisible([options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-be-visible)
- * to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
+ * **Details**
*
- * **Usage**
+ * Scrolling affects the returned bounding box, similarly to
+ * [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
+ * That means `x` and/or `y` may be negative.
*
- * ```js
- * const visible = await page.getByRole('button').isVisible();
- * ```
+ * Elements from child frames return the bounding box relative to the main frame, unlike the
+ * [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
*
- * @param options
- */
- isVisible(options?: {
- /**
- * @deprecated This option is ignored.
- * [locator.isVisible([options])](https://playwright.dev/docs/api/class-locator#locator-is-visible) does not wait for
- * the element to become visible and returns immediately.
- */
- timeout?: number;
- }): Promise<boolean>;
-
- /**
- * Returns locator to the last matching element.
+ * Assuming the page is static, it is safe to use bounding box coordinates to perform input. For example, the
+ * following snippet should click the center of the element.
*
* **Usage**
*
* ```js
- * const banana = await page.getByRole('listitem').last();
+ * const box = await page.getByRole('button').boundingBox();
+ * await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
* ```
*
- */
- last(): Locator;
-
- /**
- * The method finds an element matching the specified selector in the locator's subtree. It also accepts filter
- * options, similar to [locator.filter([options])](https://playwright.dev/docs/api/class-locator#locator-filter)
- * method.
- *
- * [Learn more about locators](https://playwright.dev/docs/locators).
- * @param selectorOrLocator A selector or locator to use when resolving DOM element.
* @param options
*/
- locator(selectorOrLocator: string|Locator, options?: {
+ boundingBox(options?: {
/**
- * Narrows down the results of the method to those which contain elements matching this relative locator. For example,
- * `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
- *
- * Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
- * the document root. For example, you can find `content` that has `div` in
- * `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
- * div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
- *
- * Note that outer and inner locators must belong to the same frame. Inner locator must not contain {@link
- * FrameLocator}s.
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
- has?: Locator;
-
+ timeout?: number;
+ }): Promise<null|{
/**
- * Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
- * outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
- *
- * Note that outer and inner locators must belong to the same frame. Inner locator must not contain {@link
- * FrameLocator}s.
+ * the x coordinate of the element in pixels.
*/
- hasNot?: Locator;
+ x: number;
/**
- * Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
- * When passed a [string], matching is case-insensitive and searches for a substring.
+ * the y coordinate of the element in pixels.
*/
- hasNotText?: string|RegExp;
+ y: number;
/**
- * Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
- * passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
- * `<article><div>Playwright</div></article>`.
+ * the width of the element in pixels.
*/
- hasText?: string|RegExp;
- }): Locator;
+ width: number;
- /**
- * Returns locator to the n-th matching element. It's zero based, `nth(0)` selects the first element.
- *
- * **Usage**
- *
- * ```js
- * const banana = await page.getByRole('listitem').nth(2);
- * ```
- *
- * @param index
- */
- nth(index: number): Locator;
+ /**
+ * the height of the element in pixels.
+ */
+ height: number;
+ }>;
/**
- * Creates a locator that matches either of the two locators.
+ * Ensure that checkbox or radio element is checked.
*
- * **Usage**
+ * **Details**
*
- * Consider a scenario where you'd like to click on a "New email" button, but sometimes a security settings dialog
- * shows up instead. In this case, you can wait for either a "New email" button, or a dialog and act accordingly.
+ * Performs the following steps:
+ * 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
+ * checked, this method returns immediately.
+ * 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
+ * 1. Scroll the element into view if needed.
+ * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to click in the center of the
+ * element.
+ * 1. Ensure that the element is now checked. If not, this method throws.
*
- * ```js
- * const newEmail = page.getByRole('button', { name: 'New' });
- * const dialog = page.getByText('Confirm security settings');
- * await expect(newEmail.or(dialog)).toBeVisible();
- * if (await dialog.isVisible())
- * await page.getByRole('button', { name: 'Dismiss' }).click();
- * await newEmail.click();
- * ```
+ * If the element is detached from the DOM at any moment during the action, this method throws.
*
- * @param locator Alternative locator to match.
- */
- or(locator: Locator): Locator;
-
- /**
- * A page this locator belongs to.
- */
- page(): Page;
-
- /**
- * Focuses the matching element and presses a combination of the keys.
+ * When all steps combined have not finished during the specified `timeout`, this method throws a {@link
+ * TimeoutError}. Passing zero timeout disables this.
*
* **Usage**
*
* ```js
- * await page.getByRole('textbox').press('Backspace');
+ * await page.getByRole('checkbox').check();
* ```
*
- * **Details**
- *
- * Focuses the element, and then uses
- * [keyboard.down(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-down) and
- * [keyboard.up(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-up).
- *
- * `key` can specify the intended
- * [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
- * to generate the text for. A superset of the `key` values can be found
- * [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
- *
- * `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
- * `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
- * etc.
- *
- * Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
- * `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
- *
- * Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
- *
- * If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
- * texts.
- *
- * Shortcuts such as `key: "Control+o"`, `key: "Control++` or `key: "Control+Shift+T"` are supported as well. When
- * specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
- * @param key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
* @param options
*/
- press(key: string, options?: {
+ check(options?: {
/**
- * Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
+ * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
+ */
+ force?: boolean;
+
+ /**
+ * This option has no effect.
+ * @deprecated This option has no effect.
*/
- delay?: number;
+ noWaitAfter?: boolean;
/**
- * Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
- * can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
- * navigating to inaccessible pages. Defaults to `false`.
- * @deprecated This option will default to `true` in the future.
+ * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
+ * the element.
*/
- noWaitAfter?: boolean;
+ position?: {
+ x: number;
+
+ y: number;
+ };
/**
* Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
@@ -12396,42 +11786,40 @@ export interface Locator {
* or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
timeout?: number;
+
+ /**
+ * When set, this method only performs the [actionability](https://playwright.dev/docs/actionability) checks and skips the action. Defaults
+ * to `false`. Useful to wait until the element is ready for the action without performing it.
+ */
+ trial?: boolean;
}): Promise<void>;
/**
- * **NOTE** In most cases, you should use
- * [locator.fill(value[, options])](https://playwright.dev/docs/api/class-locator#locator-fill) instead. You only need
- * to press keys one by one if there is special keyboard handling on the page.
- *
- * Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the
- * text.
+ * Clear the input field.
*
- * To press a special key, like `Control` or `ArrowDown`, use
- * [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press).
+ * **Details**
*
- * **Usage**
+ * This method waits for [actionability](https://playwright.dev/docs/actionability) checks, focuses the element, clears it and triggers an
+ * `input` event after clearing.
*
- * ```js
- * await locator.pressSequentially('Hello'); // Types instantly
- * await locator.pressSequentially('World', { delay: 100 }); // Types slower, like a user
- * ```
+ * If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
+ * error. However, if the element is inside the `<label>` element that has an associated
+ * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be cleared
+ * instead.
*
- * An example of typing into a text field and then submitting the form:
+ * **Usage**
*
* ```js
- * const locator = page.getByLabel('Password');
- * await locator.pressSequentially('my password');
- * await locator.press('Enter');
+ * await page.getByRole('textbox').clear();
* ```
*
- * @param text String of characters to sequentially press into a focused element.
* @param options
*/
- pressSequentially(text: string, options?: {
+ clear(options?: {
/**
- * Time to wait between key presses in milliseconds. Defaults to 0.
+ * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
*/
- delay?: number;
+ force?: boolean;
/**
* This option has no effect.
@@ -12449,43 +11837,88 @@ export interface Locator {
}): Promise<void>;
/**
- * Take a screenshot of the element matching the locator.
+ * Click an element.
+ *
+ * **Details**
+ *
+ * This method clicks the element by performing the following steps:
+ * 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
+ * 1. Scroll the element into view if needed.
+ * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to click in the center of the
+ * element, or the specified `position`.
+ * 1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
+ *
+ * If the element is detached from the DOM at any moment during the action, this method throws.
+ *
+ * When all steps combined have not finished during the specified `timeout`, this method throws a {@link
+ * TimeoutError}. Passing zero timeout disables this.
*
* **Usage**
*
+ * Click a button:
+ *
* ```js
- * await page.getByRole('link').screenshot();
+ * await page.getByRole('button').click();
* ```
*
- * Disable animations and save screenshot to a file:
+ * Shift-right-click at a specific position on a canvas:
*
* ```js
- * await page.getByRole('link').screenshot({ animations: 'disabled', path: 'link.png' });
+ * await page.locator('canvas').click({
+ * button: 'right',
+ * modifiers: ['Shift'],
+ * position: { x: 23, y: 32 },
+ * });
* ```
*
- * **Details**
- *
- * This method captures a screenshot of the page, clipped to the size and position of a particular element matching
- * the locator. If the element is covered by other elements, it will not be actually visible on the screenshot. If the
- * element is a scrollable container, only the currently scrolled content will be visible on the screenshot.
- *
- * This method waits for the [actionability](https://playwright.dev/docs/actionability) checks, then scrolls element into view before taking
- * a screenshot. If the element is detached from DOM, the method throws an error.
- *
- * Returns the buffer with the captured screenshot.
* @param options
*/
- screenshot(options?: LocatorScreenshotOptions): Promise<Buffer>;
+ click(options?: {
+ /**
+ * Defaults to `left`.
+ */
+ button?: "left"|"right"|"middle";
+
+ /**
+ * defaults to 1. See [UIEvent.detail].
+ */
+ clickCount?: number;
+
+ /**
+ * Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
+ */
+ delay?: number;
+
+ /**
+ * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
+ */
+ force?: boolean;
+
+ /**
+ * Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
+ * current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
+ * "Control" on Windows and Linux and to "Meta" on macOS.
+ */
+ modifiers?: Array<"Alt"|"Control"|"ControlOrMeta"|"Meta"|"Shift">;
+
+ /**
+ * Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
+ * can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
+ * navigating to inaccessible pages. Defaults to `false`.
+ * @deprecated This option will default to `true` in the future.
+ */
+ noWaitAfter?: boolean;
+
+ /**
+ * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
+ * the element.
+ */
+ position?: {
+ x: number;
+
+ y: number;
+ };
- /**
- * This method waits for [actionability](https://playwright.dev/docs/actionability) checks, then tries to scroll element into view, unless
- * it is completely visible as defined by
- * [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)'s `ratio`.
- *
- * See [scrolling](https://playwright.dev/docs/input#scrolling) for alternative ways to scroll.
- * @param options
- */
- scrollIntoViewIfNeeded(options?: {
/**
* Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
* option in the config, or by using the
@@ -12493,94 +11926,108 @@ export interface Locator {
* or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
timeout?: number;
+
+ /**
+ * When set, this method only performs the [actionability](https://playwright.dev/docs/actionability) checks and skips the action. Defaults
+ * to `false`. Useful to wait until the element is ready for the action without performing it.
+ */
+ trial?: boolean;
}): Promise<void>;
/**
- * Selects option or options in `<select>`.
+ * Returns a {@link FrameLocator} object pointing to the same `iframe` as this locator.
*
- * **Details**
+ * Useful when you have a {@link Locator} object obtained somewhere, and later on would like to interact with the
+ * content inside the frame.
*
- * This method waits for [actionability](https://playwright.dev/docs/actionability) checks, waits until all specified options are present in
- * the `<select>` element and selects these options.
+ * For a reverse operation, use
+ * [frameLocator.owner()](https://playwright.dev/docs/api/class-framelocator#frame-locator-owner).
*
- * If the target element is not a `<select>` element, this method throws an error. However, if the element is inside
- * the `<label>` element that has an associated
- * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be used
- * instead.
+ * **Usage**
*
- * Returns the array of option values that have been successfully selected.
+ * ```js
+ * const locator = page.locator('iframe[name="embedded"]');
+ * // ...
+ * const frameLocator = locator.contentFrame();
+ * await frameLocator.getByRole('button').click();
+ * ```
*
- * Triggers a `change` and `input` event once all the provided options have been selected.
+ */
+ contentFrame(): FrameLocator;
+
+ /**
+ * Returns the number of elements matching the locator.
+ *
+ * **NOTE** If you need to assert the number of elements on the page, prefer
+ * [expect(locator).toHaveCount(count[, options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-have-count)
+ * to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
*
* **Usage**
*
- * ```html
- * <select multiple>
- * <option value="red">Red</div>
- * <option value="green">Green</div>
- * <option value="blue">Blue</div>
- * </select>
+ * ```js
+ * const count = await page.getByRole('listitem').count();
* ```
*
- * ```js
- * // single selection matching the value or label
- * element.selectOption('blue');
+ */
+ count(): Promise<number>;
+
+ /**
+ * Double-click an element.
*
- * // single selection matching the label
- * element.selectOption({ label: 'Blue' });
+ * **Details**
*
- * // multiple selection for red, green and blue options
- * element.selectOption(['red', 'green', 'blue']);
- * ```
+ * This method double clicks the element by performing the following steps:
+ * 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
+ * 1. Scroll the element into view if needed.
+ * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to double click in the center of the
+ * element, or the specified `position`.
*
- * @param values Options to select. If the `<select>` has the `multiple` attribute, all matching options are selected, otherwise
- * only the first option matching one of the passed options is selected. String values are matching both values and
- * labels. Option is considered matching if all specified properties match.
+ * If the element is detached from the DOM at any moment during the action, this method throws.
+ *
+ * When all steps combined have not finished during the specified `timeout`, this method throws a {@link
+ * TimeoutError}. Passing zero timeout disables this.
+ *
+ * **NOTE** `element.dblclick()` dispatches two `click` events and a single `dblclick` event.
* @param options
*/
- selectOption(values: null|string|ElementHandle|ReadonlyArray<string>|{
+ dblclick(options?: {
/**
- * Matches by `option.value`. Optional.
+ * Defaults to `left`.
*/
- value?: string;
+ button?: "left"|"right"|"middle";
/**
- * Matches by `option.label`. Optional.
+ * Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
*/
- label?: string;
+ delay?: number;
/**
- * Matches by the index. Optional.
- */
- index?: number;
- }|ReadonlyArray<ElementHandle>|ReadonlyArray<{
- /**
- * Matches by `option.value`. Optional.
+ * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
*/
- value?: string;
+ force?: boolean;
/**
- * Matches by `option.label`. Optional.
+ * Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
+ * current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
+ * "Control" on Windows and Linux and to "Meta" on macOS.
*/
- label?: string;
+ modifiers?: Array<"Alt"|"Control"|"ControlOrMeta"|"Meta"|"Shift">;
/**
- * Matches by the index. Optional.
- */
- index?: number;
- }>, options?: {
- /**
- * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
+ * This option has no effect.
+ * @deprecated This option has no effect.
*/
- force?: boolean;
+ noWaitAfter?: boolean;
/**
- * Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
- * can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
- * navigating to inaccessible pages. Defaults to `false`.
- * @deprecated This option will default to `true` in the future.
+ * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
+ * the element.
*/
- noWaitAfter?: boolean;
+ position?: {
+ x: number;
+
+ y: number;
+ };
/**
* Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
@@ -12589,23 +12036,57 @@ export interface Locator {
* or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
timeout?: number;
- }): Promise<Array<string>>;
+
+ /**
+ * When set, this method only performs the [actionability](https://playwright.dev/docs/actionability) checks and skips the action. Defaults
+ * to `false`. Useful to wait until the element is ready for the action without performing it.
+ */
+ trial?: boolean;
+ }): Promise<void>;
/**
- * This method waits for [actionability](https://playwright.dev/docs/actionability) checks, then focuses the element and selects all its
- * text content.
+ * Programmatically dispatch an event on the matching element.
*
- * If the element is inside the `<label>` element that has an associated
- * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), focuses and selects text in
- * the control instead.
+ * **Usage**
+ *
+ * ```js
+ * await locator.dispatchEvent('click');
+ * ```
+ *
+ * **Details**
+ *
+ * The snippet above dispatches the `click` event on the element. Regardless of the visibility state of the element,
+ * `click` is dispatched. This is equivalent to calling
+ * [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
+ *
+ * Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit`
+ * properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
+ *
+ * Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
+ * - [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent)
+ * - [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/DeviceOrientationEvent)
+ * - [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
+ * - [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
+ * - [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
+ * - [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
+ * - [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
+ * - [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
+ * - [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
+ * - [WheelEvent](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent)
+ *
+ * You can also specify {@link JSHandle} as the property value if you want live objects to be passed into the event:
+ *
+ * ```js
+ * // Note you can only create DataTransfer in Chromium and Firefox
+ * const dataTransfer = await page.evaluateHandle(() => new DataTransfer());
+ * await locator.dispatchEvent('dragstart', { dataTransfer });
+ * ```
+ *
+ * @param type DOM event type: `"click"`, `"dragstart"`, etc.
+ * @param eventInit Optional event-specific initialization properties.
* @param options
*/
- selectText(options?: {
- /**
- * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
- */
- force?: boolean;
-
+ dispatchEvent(type: string, eventInit?: EvaluationArgument, options?: {
/**
* Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
* option in the config, or by using the
@@ -12616,32 +12097,31 @@ export interface Locator {
}): Promise<void>;
/**
- * Set the state of a checkbox or a radio element.
+ * Drag the source element towards the target element and drop it.
+ *
+ * **Details**
+ *
+ * This method drags the locator to another target locator or target position. It will first move to the source
+ * element, perform a `mousedown`, then move to the target element or position and perform a `mouseup`.
*
* **Usage**
*
* ```js
- * await page.getByRole('checkbox').setChecked(true);
- * ```
- *
- * **Details**
+ * const source = page.locator('#source');
+ * const target = page.locator('#target');
*
- * This method checks or unchecks an element by performing the following steps:
- * 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
- * 1. If the element already has the right checked state, this method returns immediately.
- * 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the matched element, unless `force` option is set. If
- * the element is detached during the checks, the whole action is retried.
- * 1. Scroll the element into view if needed.
- * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to click in the center of the
- * element.
- * 1. Ensure that the element is now checked or unchecked. If not, this method throws.
+ * await source.dragTo(target);
+ * // or specify exact positions relative to the top-left corners of the elements:
+ * await source.dragTo(target, {
+ * sourcePosition: { x: 34, y: 7 },
+ * targetPosition: { x: 10, y: 20 },
+ * });
+ * ```
*
- * When all steps combined have not finished during the specified `timeout`, this method throws a {@link
- * TimeoutError}. Passing zero timeout disables this.
- * @param checked Whether to check or uncheck the checkbox.
+ * @param target Locator of the element to drag to.
* @param options
*/
- setChecked(checked: boolean, options?: {
+ dragTo(target: Locator, options?: {
/**
* Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
*/
@@ -12654,10 +12134,20 @@ export interface Locator {
noWaitAfter?: boolean;
/**
- * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- * the element.
+ * Clicks on the source element at this point relative to the top-left corner of the element's padding box. If not
+ * specified, some visible point of the element is used.
*/
- position?: {
+ sourcePosition?: {
+ x: number;
+
+ y: number;
+ };
+
+ /**
+ * Drops on the target element at this point relative to the top-left corner of the element's padding box. If not
+ * specified, some visible point of the element is used.
+ */
+ targetPosition?: {
x: number;
y: number;
@@ -12679,78 +12169,43 @@ export interface Locator {
}): Promise<void>;
/**
- * Upload file or multiple files into `<input type=file>`. For inputs with a `[webkitdirectory]` attribute, only a
- * single directory path is supported.
+ * **NOTE** Always prefer using {@link Locator}s and web assertions over {@link ElementHandle}s because latter are inherently
+ * racy.
+ *
+ * Resolves given locator to all matching DOM elements. If there are no matching elements, returns an empty list.
+ */
+ elementHandles(): Promise<Array<ElementHandle>>;
+
+ /**
+ * Set a value to the input field.
*
* **Usage**
*
* ```js
- * // Select one file
- * await page.getByLabel('Upload file').setInputFiles(path.join(__dirname, 'myfile.pdf'));
- *
- * // Select multiple files
- * await page.getByLabel('Upload files').setInputFiles([
- * path.join(__dirname, 'file1.txt'),
- * path.join(__dirname, 'file2.txt'),
- * ]);
- *
- * // Select a directory
- * await page.getByLabel('Upload directory').setInputFiles(path.join(__dirname, 'mydir'));
- *
- * // Remove all the selected files
- * await page.getByLabel('Upload file').setInputFiles([]);
- *
- * // Upload buffer from memory
- * await page.getByLabel('Upload file').setInputFiles({
- * name: 'file.txt',
- * mimeType: 'text/plain',
- * buffer: Buffer.from('this is test')
- * });
+ * await page.getByRole('textbox').fill('example value');
* ```
*
* **Details**
*
- * Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then
- * they are resolved relative to the current working directory. For empty array, clears the selected files.
+ * This method waits for [actionability](https://playwright.dev/docs/actionability) checks, focuses the element, fills it and triggers an
+ * `input` event after filling. Note that you can pass an empty string to clear the input field.
*
- * This method expects {@link Locator} to point to an
- * [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). However, if the element is inside
- * the `<label>` element that has an associated
- * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), targets the control instead.
- * @param files
+ * If the target element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an
+ * error. However, if the element is inside the `<label>` element that has an associated
+ * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be filled
+ * instead.
+ *
+ * To send fine-grained keyboard events, use
+ * [locator.pressSequentially(text[, options])](https://playwright.dev/docs/api/class-locator#locator-press-sequentially).
+ * @param value Value to set for the `<input>`, `<textarea>` or `[contenteditable]` element.
* @param options
*/
- setInputFiles(files: string|ReadonlyArray<string>|{
- /**
- * File name
- */
- name: string;
-
- /**
- * File type
- */
- mimeType: string;
-
- /**
- * File content
- */
- buffer: Buffer;
- }|ReadonlyArray<{
- /**
- * File name
- */
- name: string;
-
+ fill(value: string, options?: {
/**
- * File type
+ * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
*/
- mimeType: string;
+ force?: boolean;
- /**
- * File content
- */
- buffer: Buffer;
- }>, options?: {
/**
* This option has no effect.
* @deprecated This option has no effect.
@@ -12767,53 +12222,70 @@ export interface Locator {
}): Promise<void>;
/**
- * Perform a tap gesture on the element matching the locator.
- *
- * **Details**
- *
- * This method taps the element by performing the following steps:
- * 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
- * 1. Scroll the element into view if needed.
- * 1. Use [page.touchscreen](https://playwright.dev/docs/api/class-page#page-touchscreen) to tap the center of the
- * element, or the specified `position`.
+ * This method narrows existing locator according to the options, for example filters by text. It can be chained to
+ * filter multiple times.
*
- * If the element is detached from the DOM at any moment during the action, this method throws.
+ * **Usage**
*
- * When all steps combined have not finished during the specified `timeout`, this method throws a {@link
- * TimeoutError}. Passing zero timeout disables this.
+ * ```js
+ * const rowLocator = page.locator('tr');
+ * // ...
+ * await rowLocator
+ * .filter({ hasText: 'text in column 1' })
+ * .filter({ has: page.getByRole('button', { name: 'column 2 button' }) })
+ * .screenshot();
+ * ```
*
- * **NOTE** `element.tap()` requires that the `hasTouch` option of the browser context be set to true.
* @param options
*/
- tap(options?: {
+ filter(options?: {
/**
- * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
+ * Narrows down the results of the method to those which contain elements matching this relative locator. For example,
+ * `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
+ *
+ * Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
+ * the document root. For example, you can find `content` that has `div` in
+ * `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
+ * div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
+ *
+ * Note that outer and inner locators must belong to the same frame. Inner locator must not contain {@link
+ * FrameLocator}s.
*/
- force?: boolean;
+ has?: Locator;
/**
- * Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
- * current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
- * "Control" on Windows and Linux and to "Meta" on macOS.
+ * Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
+ * outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
+ *
+ * Note that outer and inner locators must belong to the same frame. Inner locator must not contain {@link
+ * FrameLocator}s.
*/
- modifiers?: Array<"Alt"|"Control"|"ControlOrMeta"|"Meta"|"Shift">;
+ hasNot?: Locator;
/**
- * This option has no effect.
- * @deprecated This option has no effect.
+ * Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
+ * When passed a [string], matching is case-insensitive and searches for a substring.
*/
- noWaitAfter?: boolean;
+ hasNotText?: string|RegExp;
/**
- * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- * the element.
+ * Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
+ * passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
+ * `<article><div>Playwright</div></article>`.
*/
- position?: {
- x: number;
+ hasText?: string|RegExp;
+ }): Locator;
- y: number;
- };
+ /**
+ * Returns locator to the first matching element.
+ */
+ first(): Locator;
+ /**
+ * Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the matching element.
+ * @param options
+ */
+ focus(options?: {
/**
* Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
* option in the config, or by using the
@@ -12821,23 +12293,33 @@ export interface Locator {
* or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
timeout?: number;
-
- /**
- * When set, this method only performs the [actionability](https://playwright.dev/docs/actionability) checks and skips the action. Defaults
- * to `false`. Useful to wait until the element is ready for the action without performing it.
- */
- trial?: boolean;
}): Promise<void>;
/**
- * Returns the [`node.textContent`](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent).
+ * When working with iframes, you can create a frame locator that will enter the iframe and allow locating elements in
+ * that iframe:
*
- * **NOTE** If you need to assert text on the page, prefer
- * [expect(locator).toHaveText(expected[, options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-have-text)
+ * **Usage**
+ *
+ * ```js
+ * const locator = page.frameLocator('iframe').getByText('Submit');
+ * await locator.click();
+ * ```
+ *
+ * @param selector A selector to use when resolving DOM element.
+ */
+ frameLocator(selector: string): FrameLocator;
+
+ /**
+ * Returns the matching element's attribute value.
+ *
+ * **NOTE** If you need to assert an element's attribute, prefer
+ * [expect(locator).toHaveAttribute(name, value[, options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-have-attribute)
* to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
+ * @param name Attribute name to get the value for.
* @param options
*/
- textContent(options?: {
+ getAttribute(name: string, options?: {
/**
* Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
* option in the config, or by using the
@@ -12848,1924 +12330,1975 @@ export interface Locator {
}): Promise<null|string>;
/**
- * Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the
- * text.
- *
- * To press a special key, like `Control` or `ArrowDown`, use
- * [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press).
+ * Allows locating elements by their alt text.
*
* **Usage**
- * @deprecated In most cases, you should use
- * [locator.fill(value[, options])](https://playwright.dev/docs/api/class-locator#locator-fill) instead. You only need
- * to press keys one by one if there is special keyboard handling on the page - in this case use
- * [locator.pressSequentially(text[, options])](https://playwright.dev/docs/api/class-locator#locator-press-sequentially).
- * @param text A text to type into a focused element.
+ *
+ * For example, this method will find the image by alt text "Playwright logo":
+ *
+ * ```html
+ * <img alt='Playwright logo'>
+ * ```
+ *
+ * ```js
+ * await page.getByAltText('Playwright logo').click();
+ * ```
+ *
+ * @param text Text to locate the element for.
* @param options
*/
- type(text: string, options?: {
+ getByAltText(text: string|RegExp, options?: {
/**
- * Time to wait between key presses in milliseconds. Defaults to 0.
+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
+ * regular expression. Note that exact match still trims whitespace.
*/
- delay?: number;
+ exact?: boolean;
+ }): Locator;
+ /**
+ * Allows locating input elements by the text of the associated `<label>` or `aria-labelledby` element, or by the
+ * `aria-label` attribute.
+ *
+ * **Usage**
+ *
+ * For example, this method will find inputs by label "Username" and "Password" in the following DOM:
+ *
+ * ```html
+ * <input aria-label="Username">
+ * <label for="password-input">Password:</label>
+ * <input id="password-input">
+ * ```
+ *
+ * ```js
+ * await page.getByLabel('Username').fill('john');
+ * await page.getByLabel('Password').fill('secret');
+ * ```
+ *
+ * @param text Text to locate the element for.
+ * @param options
+ */
+ getByLabel(text: string|RegExp, options?: {
/**
- * This option has no effect.
- * @deprecated This option has no effect.
+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
+ * regular expression. Note that exact match still trims whitespace.
*/
- noWaitAfter?: boolean;
+ exact?: boolean;
+ }): Locator;
+ /**
+ * Allows locating input elements by the placeholder text.
+ *
+ * **Usage**
+ *
+ * For example, consider the following DOM structure.
+ *
+ * ```html
+ * <input type="email" placeholder="[email protected]" />
+ * ```
+ *
+ * You can fill the input after locating it by the placeholder text:
+ *
+ * ```js
+ * await page
+ * .getByPlaceholder('[email protected]')
+ * .fill('[email protected]');
+ * ```
+ *
+ * @param text Text to locate the element for.
+ * @param options
+ */
+ getByPlaceholder(text: string|RegExp, options?: {
/**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
+ * regular expression. Note that exact match still trims whitespace.
*/
- timeout?: number;
- }): Promise<void>;
+ exact?: boolean;
+ }): Locator;
/**
- * Ensure that checkbox or radio element is unchecked.
+ * Allows locating elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles),
+ * [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and
+ * [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
*
* **Usage**
*
+ * Consider the following DOM structure.
+ *
+ * ```html
+ * <h3>Sign up</h3>
+ * <label>
+ * <input type="checkbox" /> Subscribe
+ * </label>
+ * <br/>
+ * <button>Submit</button>
+ * ```
+ *
+ * You can locate each element by it's implicit role:
+ *
* ```js
- * await page.getByRole('checkbox').uncheck();
+ * await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible();
+ *
+ * await page.getByRole('checkbox', { name: 'Subscribe' }).check();
+ *
+ * await page.getByRole('button', { name: /submit/i }).click();
* ```
*
* **Details**
*
- * This method unchecks the element by performing the following steps:
- * 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
- * unchecked, this method returns immediately.
- * 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
- * 1. Scroll the element into view if needed.
- * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to click in the center of the
- * element.
- * 1. Ensure that the element is now unchecked. If not, this method throws.
- *
- * If the element is detached from the DOM at any moment during the action, this method throws.
+ * Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback
+ * about the ARIA guidelines.
*
- * When all steps combined have not finished during the specified `timeout`, this method throws a {@link
- * TimeoutError}. Passing zero timeout disables this.
+ * Many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings)
+ * that is recognized by the role selector. You can find all the
+ * [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend**
+ * duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values.
+ * @param role Required aria role.
* @param options
*/
- uncheck(options?: {
+ getByRole(role: "alert"|"alertdialog"|"application"|"article"|"banner"|"blockquote"|"button"|"caption"|"cell"|"checkbox"|"code"|"columnheader"|"combobox"|"complementary"|"contentinfo"|"definition"|"deletion"|"dialog"|"directory"|"document"|"emphasis"|"feed"|"figure"|"form"|"generic"|"grid"|"gridcell"|"group"|"heading"|"img"|"insertion"|"link"|"list"|"listbox"|"listitem"|"log"|"main"|"marquee"|"math"|"meter"|"menu"|"menubar"|"menuitem"|"menuitemcheckbox"|"menuitemradio"|"navigation"|"none"|"note"|"option"|"paragraph"|"presentation"|"progressbar"|"radio"|"radiogroup"|"region"|"row"|"rowgroup"|"rowheader"|"scrollbar"|"search"|"searchbox"|"separator"|"slider"|"spinbutton"|"status"|"strong"|"subscript"|"superscript"|"switch"|"tab"|"table"|"tablist"|"tabpanel"|"term"|"textbox"|"time"|"timer"|"toolbar"|"tooltip"|"tree"|"treegrid"|"treeitem", options?: {
/**
- * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
+ * An attribute that is usually set by `aria-checked` or native `<input type=checkbox>` controls.
+ *
+ * Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked).
*/
- force?: boolean;
+ checked?: boolean;
/**
- * This option has no effect.
- * @deprecated This option has no effect.
+ * An attribute that is usually set by `aria-disabled` or `disabled`.
+ *
+ * **NOTE** Unlike most other attributes, `disabled` is inherited through the DOM hierarchy. Learn more about
+ * [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled).
*/
- noWaitAfter?: boolean;
+ disabled?: boolean;
/**
- * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
- * the element.
+ * Whether `name` is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when `name` is a
+ * regular expression. Note that exact match still trims whitespace.
*/
- position?: {
- x: number;
+ exact?: boolean;
- y: number;
- };
+ /**
+ * An attribute that is usually set by `aria-expanded`.
+ *
+ * Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded).
+ */
+ expanded?: boolean;
/**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
+ * Option that controls whether hidden elements are matched. By default, only non-hidden elements, as
+ * [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector.
+ *
+ * Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden).
*/
- timeout?: number;
+ includeHidden?: boolean;
/**
- * When set, this method only performs the [actionability](https://playwright.dev/docs/actionability) checks and skips the action. Defaults
- * to `false`. Useful to wait until the element is ready for the action without performing it.
+ * A number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values
+ * for `<h1>-<h6>` elements.
+ *
+ * Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level).
+ */
+ level?: number;
+
+ /**
+ * Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is
+ * case-insensitive and searches for a substring, use `exact` to control this behavior.
+ *
+ * Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name).
+ */
+ name?: string|RegExp;
+
+ /**
+ * An attribute that is usually set by `aria-pressed`.
+ *
+ * Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed).
+ */
+ pressed?: boolean;
+
+ /**
+ * An attribute that is usually set by `aria-selected`.
+ *
+ * Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected).
*/
- trial?: boolean;
- }): Promise<void>;
+ selected?: boolean;
+ }): Locator;
/**
- * Returns when element specified by locator satisfies the `state` option.
- *
- * If target element already satisfies the condition, the method returns immediately. Otherwise, waits for up to
- * `timeout` milliseconds until the condition is met.
+ * Locate element by the test id.
*
* **Usage**
*
- * ```js
- * const orderSent = page.locator('#order-sent');
- * await orderSent.waitFor();
+ * Consider the following DOM structure.
+ *
+ * ```html
+ * <button data-testid="directions">Itinéraire</button>
* ```
*
- * @param options
- */
- waitFor(options?: {
- /**
- * Defaults to `'visible'`. Can be either:
- * - `'attached'` - wait for element to be present in DOM.
- * - `'detached'` - wait for element to not be present in DOM.
- * - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element
- * without any content or with `display:none` has an empty bounding box and is not considered visible.
- * - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or
- * `visibility:hidden`. This is opposite to the `'visible'` option.
- */
- state?: "attached"|"detached"|"visible"|"hidden";
-
- /**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
- */
- timeout?: number;
- }): Promise<void>;
-}
-
-/**
- * BrowserType provides methods to launch a specific browser instance or connect to an existing one. The following is
- * a typical example of using Playwright to drive automation:
- *
- * ```js
- * const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
- *
- * (async () => {
- * const browser = await chromium.launch();
- * const page = await browser.newPage();
- * await page.goto('https://example.com');
- * // other actions...
- * await browser.close();
- * })();
- * ```
- *
- */
-export interface BrowserType<Unused = {}> {
- /**
- * This method attaches Playwright to an existing browser instance using the Chrome DevTools Protocol.
+ * You can locate the element by it's test id:
*
- * The default browser context is accessible via
- * [browser.contexts()](https://playwright.dev/docs/api/class-browser#browser-contexts).
+ * ```js
+ * await page.getByTestId('directions').click();
+ * ```
*
- * **NOTE** Connecting over the Chrome DevTools Protocol is only supported for Chromium-based browsers.
+ * **Details**
*
- * **Usage**
+ * By default, the `data-testid` attribute is used as a test id. Use
+ * [selectors.setTestIdAttribute(attributeName)](https://playwright.dev/docs/api/class-selectors#selectors-set-test-id-attribute)
+ * to configure a different test id attribute if necessary.
*
* ```js
- * const browser = await playwright.chromium.connectOverCDP('http://localhost:9222');
- * const defaultContext = browser.contexts()[0];
- * const page = defaultContext.pages()[0];
+ * // Set custom test id attribute from @playwright/test config:
+ * import { defineConfig } from '@playwright/test';
+ *
+ * export default defineConfig({
+ * use: {
+ * testIdAttribute: 'data-pw'
+ * },
+ * });
* ```
*
- * @param endpointURL A CDP websocket endpoint or http url to connect to. For example `http://localhost:9222/` or
- * `ws://127.0.0.1:9222/devtools/browser/387adf4c-243f-4051-a181-46798f4a46f4`.
- * @param options
- */
- connectOverCDP(endpointURL: string, options?: ConnectOverCDPOptions): Promise<Browser>;
- /**
- * Option `wsEndpoint` is deprecated. Instead use `endpointURL`.
- * @deprecated
+ * @param testId Id to locate the element by.
*/
+ getByTestId(testId: string|RegExp): Locator;
+
/**
- * This method attaches Playwright to an existing browser instance using the Chrome DevTools Protocol.
- *
- * The default browser context is accessible via
- * [browser.contexts()](https://playwright.dev/docs/api/class-browser#browser-contexts).
+ * Allows locating elements that contain given text.
*
- * **NOTE** Connecting over the Chrome DevTools Protocol is only supported for Chromium-based browsers.
+ * See also [locator.filter([options])](https://playwright.dev/docs/api/class-locator#locator-filter) that allows to
+ * match by another criteria, like an accessible role, and then filter by the text content.
*
* **Usage**
*
+ * Consider the following DOM structure:
+ *
+ * ```html
+ * <div>Hello <span>world</span></div>
+ * <div>Hello</div>
+ * ```
+ *
+ * You can locate by text substring, exact string, or a regular expression:
+ *
* ```js
- * const browser = await playwright.chromium.connectOverCDP('http://localhost:9222');
- * const defaultContext = browser.contexts()[0];
- * const page = defaultContext.pages()[0];
+ * // Matches <span>
+ * page.getByText('world');
+ *
+ * // Matches first <div>
+ * page.getByText('Hello world');
+ *
+ * // Matches second <div>
+ * page.getByText('Hello', { exact: true });
+ *
+ * // Matches both <div>s
+ * page.getByText(/Hello/);
+ *
+ * // Matches second <div>
+ * page.getByText(/^hello$/i);
* ```
*
- * @param endpointURL A CDP websocket endpoint or http url to connect to. For example `http://localhost:9222/` or
- * `ws://127.0.0.1:9222/devtools/browser/387adf4c-243f-4051-a181-46798f4a46f4`.
- * @param options
- */
- connectOverCDP(options: ConnectOverCDPOptions & { wsEndpoint?: string }): Promise<Browser>;
- /**
- * This method attaches Playwright to an existing browser instance. When connecting to another browser launched via
- * `BrowserType.launchServer` in Node.js, the major and minor version needs to match the client version (1.2.3 → is
- * compatible with 1.2.x).
- * @param wsEndpoint A browser websocket endpoint to connect to.
- * @param options
- */
- connect(wsEndpoint: string, options?: ConnectOptions): Promise<Browser>;
- /**
- * wsEndpoint in options is deprecated. Instead use `wsEndpoint`.
- * @param wsEndpoint A browser websocket endpoint to connect to.
- * @param options
- * @deprecated
- */
- /**
- * This method attaches Playwright to an existing browser instance. When connecting to another browser launched via
- * `BrowserType.launchServer` in Node.js, the major and minor version needs to match the client version (1.2.3 → is
- * compatible with 1.2.x).
- * @param wsEndpoint A browser websocket endpoint to connect to.
+ * **Details**
+ *
+ * Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into
+ * one, turns line breaks into spaces and ignores leading and trailing whitespace.
+ *
+ * Input elements of the type `button` and `submit` are matched by their `value` instead of the text content. For
+ * example, locating by text `"Log in"` matches `<input type=button value="Log in">`.
+ * @param text Text to locate the element for.
* @param options
*/
- connect(options: ConnectOptions & { wsEndpoint?: string }): Promise<Browser>;
- /**
- * A path where Playwright expects to find a bundled browser executable.
- */
- executablePath(): string;
+ getByText(text: string|RegExp, options?: {
+ /**
+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
+ * regular expression. Note that exact match still trims whitespace.
+ */
+ exact?: boolean;
+ }): Locator;
/**
- * Returns the browser instance.
+ * Allows locating elements by their title attribute.
*
* **Usage**
*
- * You can use `ignoreDefaultArgs` to filter out `--mute-audio` from default arguments:
+ * Consider the following DOM structure.
*
- * ```js
- * const browser = await chromium.launch({ // Or 'firefox' or 'webkit'.
- * ignoreDefaultArgs: ['--mute-audio']
- * });
+ * ```html
+ * <span title='Issues count'>25 issues</span>
* ```
*
- * > **Chromium-only** Playwright can also be used to control the Google Chrome or Microsoft Edge browsers, but it
- * works best with the version of Chromium it is bundled with. There is no guarantee it will work with any other
- * version. Use `executablePath` option with extreme caution.
- * >
- * > If Google Chrome (rather than Chromium) is preferred, a
- * [Chrome Canary](https://www.google.com/chrome/browser/canary.html) or
- * [Dev Channel](https://www.chromium.org/getting-involved/dev-channel) build is suggested.
- * >
- * > Stock browsers like Google Chrome and Microsoft Edge are suitable for tests that require proprietary media codecs
- * for video playback. See
- * [this article](https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/) for
- * other differences between Chromium and Chrome.
- * [This article](https://chromium.googlesource.com/chromium/src/+/lkgr/docs/chromium_browser_vs_google_chrome.md)
- * describes some differences for Linux users.
- * @param options
- */
- launch(options?: LaunchOptions): Promise<Browser>;
-
- /**
- * Returns the persistent browser context instance.
+ * You can check the issues count after locating it by the title text:
*
- * Launches browser that uses persistent storage located at `userDataDir` and returns the only context. Closing this
- * context will automatically close the browser.
- * @param userDataDir Path to a User Data Directory, which stores browser session data like cookies and local storage. More details for
- * [Chromium](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md#introduction) and
- * [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options#User_Profile). Note that Chromium's
- * user data directory is the **parent** directory of the "Profile Path" seen at `chrome://version`. Pass an empty
- * string to use a temporary directory instead.
+ * ```js
+ * await expect(page.getByTitle('Issues count')).toHaveText('25 issues');
+ * ```
+ *
+ * @param text Text to locate the element for.
* @param options
*/
- launchPersistentContext(userDataDir: string, options?: {
- /**
- * Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.
- */
- acceptDownloads?: boolean;
-
- /**
- * **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality.
- *
- * Additional arguments to pass to the browser instance. The list of Chromium flags can be found
- * [here](https://peter.sh/experiments/chromium-command-line-switches/).
- */
- args?: Array<string>;
-
+ getByTitle(text: string|RegExp, 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) constructor for building the corresponding URL.
- * Unset by default. Examples:
- * - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`
- * - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in
- * `http://localhost:3000/foo/bar.html`
- * - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
- * `http://localhost:3000/bar.html`
+ * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a
+ * regular expression. Note that exact match still trims whitespace.
*/
- baseURL?: string;
+ exact?: boolean;
+ }): Locator;
- /**
- * Toggles bypassing page's Content-Security-Policy. Defaults to `false`.
- */
- bypassCSP?: boolean;
+ /**
+ * Highlight the corresponding element(s) on the screen. Useful for debugging, don't commit the code that uses
+ * [locator.highlight()](https://playwright.dev/docs/api/class-locator#locator-highlight).
+ */
+ highlight(): Promise<void>;
+ /**
+ * Hover over the matching element.
+ *
+ * **Usage**
+ *
+ * ```js
+ * await page.getByRole('link').hover();
+ * ```
+ *
+ * **Details**
+ *
+ * This method hovers over the element by performing the following steps:
+ * 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
+ * 1. Scroll the element into view if needed.
+ * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to hover over the center of the
+ * element, or the specified `position`.
+ *
+ * If the element is detached from the DOM at any moment during the action, this method throws.
+ *
+ * When all steps combined have not finished during the specified `timeout`, this method throws a {@link
+ * TimeoutError}. Passing zero timeout disables this.
+ * @param options
+ */
+ hover(options?: {
/**
- * Browser distribution channel. Supported values are "chrome", "chrome-beta", "chrome-dev", "chrome-canary",
- * "msedge", "msedge-beta", "msedge-dev", "msedge-canary". Read more about using
- * [Google Chrome and Microsoft Edge](https://playwright.dev/docs/browsers#google-chrome--microsoft-edge).
+ * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
*/
- channel?: string;
+ force?: boolean;
/**
- * Enable Chromium sandboxing. Defaults to `false`.
+ * Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
+ * current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
+ * "Control" on Windows and Linux and to "Meta" on macOS.
*/
- chromiumSandbox?: boolean;
+ modifiers?: Array<"Alt"|"Control"|"ControlOrMeta"|"Meta"|"Shift">;
/**
- * TLS Client Authentication allows the server to request a client certificate and verify it.
- *
- * **Details**
- *
- * An array of client certificates to be used. Each certificate object must have both `certPath` and `keyPath` or a
- * single `pfxPath` to load the client certificate. Optionally, `passphrase` property should be provided if the
- * certficiate is encrypted. The `origin` property should be provided with an exact match to the request origin that
- * the certificate is valid for.
- *
- * **NOTE** Using Client Certificates in combination with Proxy Servers is not supported.
- *
- * **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
- * work by replacing `localhost` with `local.playwright`.
+ * This option has no effect.
+ * @deprecated This option has no effect.
*/
- clientCertificates?: Array<{
- /**
- * Exact origin that the certificate is valid for. Origin includes `https` protocol, a hostname and optionally a port.
- */
- origin: string;
-
- /**
- * Path to the file with the certificate in PEM format.
- */
- certPath?: string;
-
- /**
- * Path to the file with the private key in PEM format.
- */
- keyPath?: string;
-
- /**
- * Path to the PFX or PKCS12 encoded private key and certificate chain.
- */
- pfxPath?: string;
-
- /**
- * Passphrase for the private key (PEM or PFX).
- */
- passphrase?: string;
- }>;
+ noWaitAfter?: 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.
- * Passing `null` resets emulation to system defaults. Defaults to `'light'`.
+ * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
+ * the element.
*/
- colorScheme?: null|"light"|"dark"|"no-preference";
+ position?: {
+ x: number;
- /**
- * Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about
- * [emulating devices with device scale factor](https://playwright.dev/docs/emulation#devices).
- */
- deviceScaleFactor?: number;
+ y: number;
+ };
/**
- * **Chromium-only** Whether to auto-open a Developer Tools panel for each tab. If this option is `true`, the
- * `headless` option will be set `false`.
- * @deprecated Use [debugging tools](https://playwright.dev/docs/debug) instead.
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
- devtools?: boolean;
+ timeout?: number;
/**
- * If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and
- * is deleted when browser is closed. In either case, the downloads are deleted when the browser context they were
- * created in is closed.
+ * When set, this method only performs the [actionability](https://playwright.dev/docs/actionability) checks and skips the action. Defaults
+ * to `false`. Useful to wait until the element is ready for the action without performing it.
*/
- downloadsPath?: string;
+ trial?: boolean;
+ }): Promise<void>;
+ /**
+ * Returns the [`element.innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML).
+ * @param options
+ */
+ innerHTML(options?: {
/**
- * Specify environment variables that will be visible to the browser. Defaults to `process.env`.
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
- env?: { [key: string]: string|number|boolean; };
+ timeout?: number;
+ }): Promise<string>;
+ /**
+ * Returns the [`element.innerText`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText).
+ *
+ * **NOTE** If you need to assert text on the page, prefer
+ * [expect(locator).toHaveText(expected[, options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-have-text)
+ * with `useInnerText` option to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
+ * @param options
+ */
+ innerText(options?: {
/**
- * Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is
- * resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium,
- * Firefox or WebKit, use at your own risk.
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
- executablePath?: string;
+ timeout?: number;
+ }): Promise<string>;
+ /**
+ * Returns the value for the matching `<input>` or `<textarea>` or `<select>` element.
+ *
+ * **NOTE** If you need to assert input value, prefer
+ * [expect(locator).toHaveValue(value[, options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-have-value)
+ * to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const value = await page.getByRole('textbox').inputValue();
+ * ```
+ *
+ * **Details**
+ *
+ * Throws elements that are not an input, textarea or a select. However, if the element is inside the `<label>`
+ * element that has an associated
+ * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), returns the value of the
+ * control.
+ * @param options
+ */
+ inputValue(options?: {
/**
- * An object containing additional HTTP headers to be sent with every request. Defaults to none.
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
- extraHTTPHeaders?: { [key: string]: string; };
+ timeout?: number;
+ }): Promise<string>;
+ /**
+ * Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
+ *
+ * **NOTE** If you need to assert that checkbox is checked, prefer
+ * [expect(locator).toBeChecked([options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-be-checked)
+ * to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const checked = await page.getByRole('checkbox').isChecked();
+ * ```
+ *
+ * @param options
+ */
+ isChecked(options?: {
/**
- * Firefox user preferences. Learn more about the Firefox user preferences at
- * [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox).
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
- firefoxUserPrefs?: { [key: string]: string|number|boolean; };
+ timeout?: number;
+ }): Promise<boolean>;
+ /**
+ * Returns whether the element is disabled, the opposite of [enabled](https://playwright.dev/docs/actionability#enabled).
+ *
+ * **NOTE** If you need to assert that an element is disabled, prefer
+ * [expect(locator).toBeDisabled([options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-be-disabled)
+ * to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const disabled = await page.getByRole('button').isDisabled();
+ * ```
+ *
+ * @param options
+ */
+ isDisabled(options?: {
/**
- * Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See
- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.
- * Passing `null` resets emulation to system defaults. Defaults to `'none'`.
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
- forcedColors?: null|"active"|"none";
-
- geolocation?: {
- /**
- * Latitude between -90 and 90.
- */
- latitude: number;
-
- /**
- * Longitude between -180 and 180.
- */
- longitude: number;
-
- /**
- * Non-negative accuracy value. Defaults to `0`.
- */
- accuracy?: number;
- };
+ timeout?: number;
+ }): Promise<boolean>;
+ /**
+ * Returns whether the element is [editable](https://playwright.dev/docs/actionability#editable).
+ *
+ * **NOTE** If you need to assert that an element is editable, prefer
+ * [expect(locator).toBeEditable([options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-be-editable)
+ * to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const editable = await page.getByRole('textbox').isEditable();
+ * ```
+ *
+ * @param options
+ */
+ isEditable(options?: {
/**
- * Close the browser process on SIGHUP. Defaults to `true`.
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
- handleSIGHUP?: boolean;
+ timeout?: number;
+ }): Promise<boolean>;
+ /**
+ * Returns whether the element is [enabled](https://playwright.dev/docs/actionability#enabled).
+ *
+ * **NOTE** If you need to assert that an element is enabled, prefer
+ * [expect(locator).toBeEnabled([options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-be-enabled)
+ * to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const enabled = await page.getByRole('button').isEnabled();
+ * ```
+ *
+ * @param options
+ */
+ isEnabled(options?: {
/**
- * Close the browser process on Ctrl-C. Defaults to `true`.
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
- handleSIGINT?: boolean;
+ timeout?: number;
+ }): Promise<boolean>;
+ /**
+ * Returns whether the element is hidden, the opposite of [visible](https://playwright.dev/docs/actionability#visible).
+ *
+ * **NOTE** If you need to assert that element is hidden, prefer
+ * [expect(locator).toBeHidden([options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-be-hidden)
+ * to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const hidden = await page.getByRole('button').isHidden();
+ * ```
+ *
+ * @param options
+ */
+ isHidden(options?: {
/**
- * Close the browser process on SIGTERM. Defaults to `true`.
+ * @deprecated This option is ignored.
+ * [locator.isHidden([options])](https://playwright.dev/docs/api/class-locator#locator-is-hidden) does not wait for
+ * the element to become hidden and returns immediately.
*/
- handleSIGTERM?: boolean;
+ timeout?: number;
+ }): Promise<boolean>;
+ /**
+ * Returns whether the element is [visible](https://playwright.dev/docs/actionability#visible).
+ *
+ * **NOTE** If you need to assert that element is visible, prefer
+ * [expect(locator).toBeVisible([options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-be-visible)
+ * to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const visible = await page.getByRole('button').isVisible();
+ * ```
+ *
+ * @param options
+ */
+ isVisible(options?: {
/**
- * Specifies if viewport supports touch events. Defaults to false. Learn more about
- * [mobile emulation](https://playwright.dev/docs/emulation#devices).
+ * @deprecated This option is ignored.
+ * [locator.isVisible([options])](https://playwright.dev/docs/api/class-locator#locator-is-visible) does not wait for
+ * the element to become visible and returns immediately.
*/
- hasTouch?: boolean;
+ timeout?: number;
+ }): Promise<boolean>;
+
+ /**
+ * Returns locator to the last matching element.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const banana = await page.getByRole('listitem').last();
+ * ```
+ *
+ */
+ last(): Locator;
+ /**
+ * The method finds an element matching the specified selector in the locator's subtree. It also accepts filter
+ * options, similar to [locator.filter([options])](https://playwright.dev/docs/api/class-locator#locator-filter)
+ * method.
+ *
+ * [Learn more about locators](https://playwright.dev/docs/locators).
+ * @param selectorOrLocator A selector or locator to use when resolving DOM element.
+ * @param options
+ */
+ locator(selectorOrLocator: string|Locator, options?: {
/**
- * Whether to run browser in headless mode. More details for
- * [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and
- * [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode). Defaults to `true` unless the
- * `devtools` option is `true`.
+ * Narrows down the results of the method to those which contain elements matching this relative locator. For example,
+ * `article` that has `text=Playwright` matches `<article><div>Playwright</div></article>`.
+ *
+ * Inner locator **must be relative** to the outer locator and is queried starting with the outer locator match, not
+ * the document root. For example, you can find `content` that has `div` in
+ * `<article><content><div>Playwright</div></content></article>`. However, looking for `content` that has `article
+ * div` will fail, because the inner locator must be relative and should not use any elements outside the `content`.
+ *
+ * Note that outer and inner locators must belong to the same frame. Inner locator must not contain {@link
+ * FrameLocator}s.
*/
- headless?: boolean;
+ has?: Locator;
/**
- * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
- * origin is specified, the username and password are sent to any servers upon unauthorized responses.
+ * Matches elements that do not contain an element that matches an inner locator. Inner locator is queried against the
+ * outer one. For example, `article` that does not have `div` matches `<article><span>Playwright</span></article>`.
+ *
+ * Note that outer and inner locators must belong to the same frame. Inner locator must not contain {@link
+ * FrameLocator}s.
*/
- httpCredentials?: {
- username: string;
-
- password: string;
-
- /**
- * Restrain sending http credentials on specific origin (scheme://host:port).
- */
- origin?: string;
-
- /**
- * This option only applies to the requests sent from corresponding {@link APIRequestContext} and does not affect
- * requests sent from the browser. `'always'` - `Authorization` header with basic authentication credentials will be
- * sent with the each API request. `'unauthorized` - the credentials are only sent when 401 (Unauthorized) response
- * with `WWW-Authenticate` header is received. Defaults to `'unauthorized'`.
- */
- send?: "unauthorized"|"always";
- };
+ hasNot?: Locator;
/**
- * If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. If an array is
- * given, then filters out the given default arguments. Dangerous option; use with care. Defaults to `false`.
+ * Matches elements that do not contain specified text somewhere inside, possibly in a child or a descendant element.
+ * When passed a [string], matching is case-insensitive and searches for a substring.
*/
- ignoreDefaultArgs?: boolean|Array<string>;
+ hasNotText?: string|RegExp;
/**
- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
+ * Matches elements containing specified text somewhere inside, possibly in a child or a descendant element. When
+ * passed a [string], matching is case-insensitive and searches for a substring. For example, `"Playwright"` matches
+ * `<article><div>Playwright</div></article>`.
*/
- ignoreHTTPSErrors?: boolean;
+ hasText?: string|RegExp;
+ }): Locator;
+
+ /**
+ * Returns locator to the n-th matching element. It's zero based, `nth(0)` selects the first element.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const banana = await page.getByRole('listitem').nth(2);
+ * ```
+ *
+ * @param index
+ */
+ nth(index: number): Locator;
+
+ /**
+ * Creates a locator that matches either of the two locators.
+ *
+ * **Usage**
+ *
+ * Consider a scenario where you'd like to click on a "New email" button, but sometimes a security settings dialog
+ * shows up instead. In this case, you can wait for either a "New email" button, or a dialog and act accordingly.
+ *
+ * ```js
+ * const newEmail = page.getByRole('button', { name: 'New' });
+ * const dialog = page.getByText('Confirm security settings');
+ * await expect(newEmail.or(dialog)).toBeVisible();
+ * if (await dialog.isVisible())
+ * await page.getByRole('button', { name: 'Dismiss' }).click();
+ * await newEmail.click();
+ * ```
+ *
+ * @param locator Alternative locator to match.
+ */
+ or(locator: Locator): Locator;
+ /**
+ * A page this locator belongs to.
+ */
+ page(): Page;
+
+ /**
+ * Focuses the matching element and presses a combination of the keys.
+ *
+ * **Usage**
+ *
+ * ```js
+ * await page.getByRole('textbox').press('Backspace');
+ * ```
+ *
+ * **Details**
+ *
+ * Focuses the element, and then uses
+ * [keyboard.down(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-down) and
+ * [keyboard.up(key)](https://playwright.dev/docs/api/class-keyboard#keyboard-up).
+ *
+ * `key` can specify the intended
+ * [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character
+ * to generate the text for. A superset of the `key` values can be found
+ * [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
+ *
+ * `F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
+ * `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`,
+ * etc.
+ *
+ * Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`,
+ * `ControlOrMeta`. `ControlOrMeta` resolves to `Control` on Windows and Linux and to `Meta` on macOS.
+ *
+ * Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
+ *
+ * If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
+ * texts.
+ *
+ * Shortcuts such as `key: "Control+o"`, `key: "Control++` or `key: "Control+Shift+T"` are supported as well. When
+ * specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
+ * @param key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
+ * @param options
+ */
+ press(key: string, options?: {
/**
- * Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,
- * so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more
- * about [mobile emulation](https://playwright.dev/docs/emulation#ismobile).
+ * Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
*/
- isMobile?: boolean;
+ delay?: number;
/**
- * Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about
- * [disabling JavaScript](https://playwright.dev/docs/emulation#javascript-enabled).
+ * Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
+ * can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
+ * navigating to inaccessible pages. Defaults to `false`.
+ * @deprecated This option will default to `true` in the future.
*/
- javaScriptEnabled?: boolean;
+ noWaitAfter?: 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. Defaults to the system default
- * locale. Learn more about emulation in our [emulation guide](https://playwright.dev/docs/emulation#locale--timezone).
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
- locale?: string;
+ timeout?: number;
+ }): Promise<void>;
+ /**
+ * **NOTE** In most cases, you should use
+ * [locator.fill(value[, options])](https://playwright.dev/docs/api/class-locator#locator-fill) instead. You only need
+ * to press keys one by one if there is special keyboard handling on the page.
+ *
+ * Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the
+ * text.
+ *
+ * To press a special key, like `Control` or `ArrowDown`, use
+ * [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press).
+ *
+ * **Usage**
+ *
+ * ```js
+ * await locator.pressSequentially('Hello'); // Types instantly
+ * await locator.pressSequentially('World', { delay: 100 }); // Types slower, like a user
+ * ```
+ *
+ * An example of typing into a text field and then submitting the form:
+ *
+ * ```js
+ * const locator = page.getByLabel('Password');
+ * await locator.pressSequentially('my password');
+ * await locator.press('Enter');
+ * ```
+ *
+ * @param text String of characters to sequentially press into a focused element.
+ * @param options
+ */
+ pressSequentially(text: string, options?: {
/**
- * Logger sink for Playwright logging.
+ * Time to wait between key presses in milliseconds. Defaults to 0.
*/
- logger?: Logger;
+ delay?: number;
/**
- * Whether to emulate network being offline. Defaults to `false`. Learn more about
- * [network emulation](https://playwright.dev/docs/emulation#offline).
+ * This option has no effect.
+ * @deprecated This option has no effect.
*/
- offline?: boolean;
+ noWaitAfter?: 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. Defaults to none.
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
- permissions?: Array<string>;
+ timeout?: number;
+ }): Promise<void>;
+
+ /**
+ * Take a screenshot of the element matching the locator.
+ *
+ * **Usage**
+ *
+ * ```js
+ * await page.getByRole('link').screenshot();
+ * ```
+ *
+ * Disable animations and save screenshot to a file:
+ *
+ * ```js
+ * await page.getByRole('link').screenshot({ animations: 'disabled', path: 'link.png' });
+ * ```
+ *
+ * **Details**
+ *
+ * This method captures a screenshot of the page, clipped to the size and position of a particular element matching
+ * the locator. If the element is covered by other elements, it will not be actually visible on the screenshot. If the
+ * element is a scrollable container, only the currently scrolled content will be visible on the screenshot.
+ *
+ * This method waits for the [actionability](https://playwright.dev/docs/actionability) checks, then scrolls element into view before taking
+ * a screenshot. If the element is detached from DOM, the method throws an error.
+ *
+ * Returns the buffer with the captured screenshot.
+ * @param options
+ */
+ screenshot(options?: LocatorScreenshotOptions): Promise<Buffer>;
+ /**
+ * This method waits for [actionability](https://playwright.dev/docs/actionability) checks, then tries to scroll element into view, unless
+ * it is completely visible as defined by
+ * [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)'s `ratio`.
+ *
+ * See [scrolling](https://playwright.dev/docs/input#scrolling) for alternative ways to scroll.
+ * @param options
+ */
+ scrollIntoViewIfNeeded(options?: {
/**
- * Network proxy settings.
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
- 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 comma-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;
- };
+ timeout?: number;
+ }): Promise<void>;
+ /**
+ * Selects option or options in `<select>`.
+ *
+ * **Details**
+ *
+ * This method waits for [actionability](https://playwright.dev/docs/actionability) checks, waits until all specified options are present in
+ * the `<select>` element and selects these options.
+ *
+ * If the target element is not a `<select>` element, this method throws an error. However, if the element is inside
+ * the `<label>` element that has an associated
+ * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), the control will be used
+ * instead.
+ *
+ * Returns the array of option values that have been successfully selected.
+ *
+ * Triggers a `change` and `input` event once all the provided options have been selected.
+ *
+ * **Usage**
+ *
+ * ```html
+ * <select multiple>
+ * <option value="red">Red</div>
+ * <option value="green">Green</div>
+ * <option value="blue">Blue</div>
+ * </select>
+ * ```
+ *
+ * ```js
+ * // single selection matching the value or label
+ * element.selectOption('blue');
+ *
+ * // single selection matching the label
+ * element.selectOption({ label: 'Blue' });
+ *
+ * // multiple selection for red, green and blue options
+ * element.selectOption(['red', 'green', 'blue']);
+ * ```
+ *
+ * @param values Options to select. If the `<select>` has the `multiple` attribute, all matching options are selected, otherwise
+ * only the first option matching one of the passed options is selected. String values are matching both values and
+ * labels. Option is considered matching if all specified properties match.
+ * @param options
+ */
+ selectOption(values: null|string|ElementHandle|ReadonlyArray<string>|{
/**
- * Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into `recordHar.path` file.
- * If not specified, the HAR is not recorded. Make sure to await
- * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for
- * the HAR to be saved.
+ * Matches by `option.value`. Optional.
*/
- recordHar?: {
- /**
- * Optional setting to control whether to omit request content from the HAR. Defaults to `false`. Deprecated, use
- * `content` policy instead.
- */
- omitContent?: boolean;
-
- /**
- * Optional setting to control resource content management. If `omit` is specified, content is not persisted. If
- * `attach` is specified, resources are persisted as separate files or entries in the ZIP archive. If `embed` is
- * specified, content is stored inline the HAR file as per HAR specification. Defaults to `attach` for `.zip` output
- * files and to `embed` for all other file extensions.
- */
- content?: "omit"|"embed"|"attach";
-
- /**
- * Path on the filesystem to write the HAR file to. If the file name ends with `.zip`, `content: 'attach'` is used by
- * default.
- */
- path: string;
-
- /**
- * When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
- * cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.
- */
- mode?: "full"|"minimal";
-
- /**
- * A glob or regex pattern to filter requests that are stored in the HAR. When a `baseURL` via the context options was
- * provided and the passed URL is a path, it gets merged via the
- * [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor. Defaults to none.
- */
- urlFilter?: string|RegExp;
- };
+ 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([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for
- * videos to be saved.
+ * Matches by `option.label`. Optional.
*/
- 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;
- };
- };
+ label?: string;
/**
- * Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See
- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.
- * Passing `null` resets emulation to system defaults. Defaults to `'no-preference'`.
+ * Matches by the index. Optional.
*/
- reducedMotion?: null|"reduce"|"no-preference";
-
+ index?: number;
+ }|ReadonlyArray<ElementHandle>|ReadonlyArray<{
/**
- * Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the
- * `viewport` is set.
+ * Matches by `option.value`. Optional.
*/
- screen?: {
- /**
- * page width in pixels.
- */
- width: number;
-
- /**
- * page height in pixels.
- */
- height: number;
- };
+ value?: string;
/**
- * Whether to allow sites to register Service workers. Defaults to `'allow'`.
- * - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be
- * registered.
- * - `'block'`: Playwright will block all registration of Service Workers.
+ * Matches by `option.label`. Optional.
*/
- serviceWorkers?: "allow"|"block";
+ label?: string;
/**
- * Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
- * on.
+ * Matches by the index. Optional.
*/
- slowMo?: number;
+ index?: number;
+ }>, options?: {
+ /**
+ * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
+ */
+ force?: boolean;
/**
- * If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on
- * selectors that imply single target DOM element will throw when more than one element matches the selector. This
- * option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See {@link Locator} to
- * learn more about the strict mode.
+ * Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You
+ * can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as
+ * navigating to inaccessible pages. Defaults to `false`.
+ * @deprecated This option will default to `true` in the future.
*/
- strictSelectors?: boolean;
+ noWaitAfter?: boolean;
/**
- * Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0`
- * to disable timeout.
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
timeout?: number;
+ }): Promise<Array<string>>;
+ /**
+ * This method waits for [actionability](https://playwright.dev/docs/actionability) checks, then focuses the element and selects all its
+ * text content.
+ *
+ * If the element is inside the `<label>` element that has an associated
+ * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), focuses and selects text in
+ * the control instead.
+ * @param options
+ */
+ selectText(options?: {
/**
- * Changes the timezone of the context. See
- * [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)
- * for a list of supported timezone IDs. Defaults to the system timezone.
+ * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
*/
- timezoneId?: string;
+ force?: boolean;
/**
- * If specified, traces are saved into this directory.
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
- tracesDir?: string;
+ timeout?: number;
+ }): Promise<void>;
+
+ /**
+ * Set the state of a checkbox or a radio element.
+ *
+ * **Usage**
+ *
+ * ```js
+ * await page.getByRole('checkbox').setChecked(true);
+ * ```
+ *
+ * **Details**
+ *
+ * This method checks or unchecks an element by performing the following steps:
+ * 1. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
+ * 1. If the element already has the right checked state, this method returns immediately.
+ * 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the matched element, unless `force` option is set. If
+ * the element is detached during the checks, the whole action is retried.
+ * 1. Scroll the element into view if needed.
+ * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to click in the center of the
+ * element.
+ * 1. Ensure that the element is now checked or unchecked. If not, this method throws.
+ *
+ * When all steps combined have not finished during the specified `timeout`, this method throws a {@link
+ * TimeoutError}. Passing zero timeout disables this.
+ * @param checked Whether to check or uncheck the checkbox.
+ * @param options
+ */
+ setChecked(checked: boolean, options?: {
+ /**
+ * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
+ */
+ force?: boolean;
/**
- * Specific user agent to use in this context.
+ * This option has no effect.
+ * @deprecated This option has no effect.
*/
- userAgent?: string;
+ noWaitAfter?: boolean;
/**
- * @deprecated Use `recordVideo` instead.
+ * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
+ * the element.
*/
- videoSize?: {
- /**
- * Video frame width.
- */
- width: number;
+ position?: {
+ x: number;
- /**
- * Video frame height.
- */
- height: number;
+ y: number;
};
/**
- * @deprecated Use `recordVideo` instead.
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
- videosPath?: string;
+ timeout?: number;
/**
- * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use `null` to disable the consistent
- * viewport emulation. Learn more about [viewport emulation](https://playwright.dev/docs/emulation#viewport).
- *
- * **NOTE** The `null` value opts out from the default presets, makes viewport depend on the host window size defined
- * by the operating system. It makes the execution of the tests non-deterministic.
+ * When set, this method only performs the [actionability](https://playwright.dev/docs/actionability) checks and skips the action. Defaults
+ * to `false`. Useful to wait until the element is ready for the action without performing it.
*/
- viewport?: null|{
- /**
- * page width in pixels.
- */
- width: number;
-
- /**
- * page height in pixels.
- */
- height: number;
- };
- }): Promise<BrowserContext>;
+ trial?: boolean;
+ }): Promise<void>;
/**
- * Returns the browser app instance. You can connect to it via
- * [browserType.connect(wsEndpoint[, options])](https://playwright.dev/docs/api/class-browsertype#browser-type-connect),
- * which requires the major/minor client/server version to match (1.2.3 → is compatible with 1.2.x).
+ * Upload file or multiple files into `<input type=file>`. For inputs with a `[webkitdirectory]` attribute, only a
+ * single directory path is supported.
*
* **Usage**
*
- * Launches browser server that client can connect to. An example of launching a browser executable and connecting to
- * it later:
- *
* ```js
- * const { chromium } = require('playwright'); // Or 'webkit' or 'firefox'.
+ * // Select one file
+ * await page.getByLabel('Upload file').setInputFiles(path.join(__dirname, 'myfile.pdf'));
*
- * (async () => {
- * const browserServer = await chromium.launchServer();
- * const wsEndpoint = browserServer.wsEndpoint();
- * // Use web socket endpoint later to establish a connection.
- * const browser = await chromium.connect(wsEndpoint);
- * // Close browser instance.
- * await browserServer.close();
- * })();
+ * // Select multiple files
+ * await page.getByLabel('Upload files').setInputFiles([
+ * path.join(__dirname, 'file1.txt'),
+ * path.join(__dirname, 'file2.txt'),
+ * ]);
+ *
+ * // Select a directory
+ * await page.getByLabel('Upload directory').setInputFiles(path.join(__dirname, 'mydir'));
+ *
+ * // Remove all the selected files
+ * await page.getByLabel('Upload file').setInputFiles([]);
+ *
+ * // Upload buffer from memory
+ * await page.getByLabel('Upload file').setInputFiles({
+ * name: 'file.txt',
+ * mimeType: 'text/plain',
+ * buffer: Buffer.from('this is test')
+ * });
* ```
*
+ * **Details**
+ *
+ * Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then
+ * they are resolved relative to the current working directory. For empty array, clears the selected files.
+ *
+ * This method expects {@link Locator} to point to an
+ * [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input). However, if the element is inside
+ * the `<label>` element that has an associated
+ * [control](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/control), targets the control instead.
+ * @param files
* @param options
*/
- launchServer(options?: {
+ setInputFiles(files: string|ReadonlyArray<string>|{
/**
- * **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality.
- *
- * Additional arguments to pass to the browser instance. The list of Chromium flags can be found
- * [here](https://peter.sh/experiments/chromium-command-line-switches/).
+ * File name
*/
- args?: Array<string>;
+ name: string;
/**
- * Browser distribution channel. Supported values are "chrome", "chrome-beta", "chrome-dev", "chrome-canary",
- * "msedge", "msedge-beta", "msedge-dev", "msedge-canary". Read more about using
- * [Google Chrome and Microsoft Edge](https://playwright.dev/docs/browsers#google-chrome--microsoft-edge).
+ * File type
*/
- channel?: string;
+ mimeType: string;
/**
- * Enable Chromium sandboxing. Defaults to `false`.
+ * File content
*/
- chromiumSandbox?: boolean;
-
+ buffer: Buffer;
+ }|ReadonlyArray<{
/**
- * **Chromium-only** Whether to auto-open a Developer Tools panel for each tab. If this option is `true`, the
- * `headless` option will be set `false`.
- * @deprecated Use [debugging tools](https://playwright.dev/docs/debug) instead.
+ * File name
*/
- devtools?: boolean;
+ name: string;
/**
- * If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and
- * is deleted when browser is closed. In either case, the downloads are deleted when the browser context they were
- * created in is closed.
+ * File type
*/
- downloadsPath?: string;
+ mimeType: string;
/**
- * Specify environment variables that will be visible to the browser. Defaults to `process.env`.
+ * File content
*/
- env?: { [key: string]: string|number|boolean; };
+ buffer: Buffer;
+ }>, options?: {
+ /**
+ * This option has no effect.
+ * @deprecated This option has no effect.
+ */
+ noWaitAfter?: boolean;
/**
- * Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is
- * resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium,
- * Firefox or WebKit, use at your own risk.
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
- executablePath?: string;
+ timeout?: number;
+ }): Promise<void>;
+ /**
+ * Perform a tap gesture on the element matching the locator.
+ *
+ * **Details**
+ *
+ * This method taps the element by performing the following steps:
+ * 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
+ * 1. Scroll the element into view if needed.
+ * 1. Use [page.touchscreen](https://playwright.dev/docs/api/class-page#page-touchscreen) to tap the center of the
+ * element, or the specified `position`.
+ *
+ * If the element is detached from the DOM at any moment during the action, this method throws.
+ *
+ * When all steps combined have not finished during the specified `timeout`, this method throws a {@link
+ * TimeoutError}. Passing zero timeout disables this.
+ *
+ * **NOTE** `element.tap()` requires that the `hasTouch` option of the browser context be set to true.
+ * @param options
+ */
+ tap(options?: {
/**
- * Firefox user preferences. Learn more about the Firefox user preferences at
- * [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox).
+ * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
*/
- firefoxUserPrefs?: { [key: string]: string|number|boolean; };
+ force?: boolean;
/**
- * Close the browser process on SIGHUP. Defaults to `true`.
+ * Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores
+ * current modifiers back. If not specified, currently pressed modifiers are used. "ControlOrMeta" resolves to
+ * "Control" on Windows and Linux and to "Meta" on macOS.
*/
- handleSIGHUP?: boolean;
+ modifiers?: Array<"Alt"|"Control"|"ControlOrMeta"|"Meta"|"Shift">;
/**
- * Close the browser process on Ctrl-C. Defaults to `true`.
+ * This option has no effect.
+ * @deprecated This option has no effect.
*/
- handleSIGINT?: boolean;
+ noWaitAfter?: boolean;
/**
- * Close the browser process on SIGTERM. Defaults to `true`.
+ * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
+ * the element.
*/
- handleSIGTERM?: boolean;
+ position?: {
+ x: number;
- /**
- * Whether to run browser in headless mode. More details for
- * [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and
- * [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode). Defaults to `true` unless the
- * `devtools` option is `true`.
- */
- headless?: boolean;
+ y: number;
+ };
/**
- * Host to use for the web socket. It is optional and if it is omitted, the server will accept connections on the
- * unspecified IPv6 address (::) when IPv6 is available, or the unspecified IPv4 address (0.0.0.0) otherwise. Consider
- * hardening it with picking a specific interface.
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
- host?: string;
+ timeout?: number;
/**
- * If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. If an array is
- * given, then filters out the given default arguments. Dangerous option; use with care. Defaults to `false`.
+ * When set, this method only performs the [actionability](https://playwright.dev/docs/actionability) checks and skips the action. Defaults
+ * to `false`. Useful to wait until the element is ready for the action without performing it.
*/
- ignoreDefaultArgs?: boolean|Array<string>;
+ trial?: boolean;
+ }): Promise<void>;
+ /**
+ * Returns the [`node.textContent`](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent).
+ *
+ * **NOTE** If you need to assert text on the page, prefer
+ * [expect(locator).toHaveText(expected[, options])](https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-have-text)
+ * to avoid flakiness. See [assertions guide](https://playwright.dev/docs/test-assertions) for more details.
+ * @param options
+ */
+ textContent(options?: {
/**
- * Logger sink for Playwright logging.
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
- logger?: Logger;
+ timeout?: number;
+ }): Promise<null|string>;
+ /**
+ * Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the
+ * text.
+ *
+ * To press a special key, like `Control` or `ArrowDown`, use
+ * [locator.press(key[, options])](https://playwright.dev/docs/api/class-locator#locator-press).
+ *
+ * **Usage**
+ * @deprecated In most cases, you should use
+ * [locator.fill(value[, options])](https://playwright.dev/docs/api/class-locator#locator-fill) instead. You only need
+ * to press keys one by one if there is special keyboard handling on the page - in this case use
+ * [locator.pressSequentially(text[, options])](https://playwright.dev/docs/api/class-locator#locator-press-sequentially).
+ * @param text A text to type into a focused element.
+ * @param options
+ */
+ type(text: string, options?: {
/**
- * Port to use for the web socket. Defaults to 0 that picks any available port.
+ * Time to wait between key presses in milliseconds. Defaults to 0.
*/
- port?: number;
+ delay?: number;
/**
- * Network proxy settings.
+ * This option has no effect.
+ * @deprecated This option has no effect.
*/
- 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 comma-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;
- };
+ noWaitAfter?: boolean;
/**
- * Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0`
- * to disable timeout.
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
timeout?: number;
+ }): Promise<void>;
+ /**
+ * Ensure that checkbox or radio element is unchecked.
+ *
+ * **Usage**
+ *
+ * ```js
+ * await page.getByRole('checkbox').uncheck();
+ * ```
+ *
+ * **Details**
+ *
+ * This method unchecks the element by performing the following steps:
+ * 1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already
+ * unchecked, this method returns immediately.
+ * 1. Wait for [actionability](https://playwright.dev/docs/actionability) checks on the element, unless `force` option is set.
+ * 1. Scroll the element into view if needed.
+ * 1. Use [page.mouse](https://playwright.dev/docs/api/class-page#page-mouse) to click in the center of the
+ * element.
+ * 1. Ensure that the element is now unchecked. If not, this method throws.
+ *
+ * If the element is detached from the DOM at any moment during the action, this method throws.
+ *
+ * When all steps combined have not finished during the specified `timeout`, this method throws a {@link
+ * TimeoutError}. Passing zero timeout disables this.
+ * @param options
+ */
+ uncheck(options?: {
/**
- * If specified, traces are saved into this directory.
+ * Whether to bypass the [actionability](https://playwright.dev/docs/actionability) checks. Defaults to `false`.
*/
- tracesDir?: string;
+ force?: boolean;
/**
- * Path at which to serve the Browser Server. For security, this defaults to an unguessable string.
- *
- * **NOTE** Any process or web page (including those running in Playwright) with knowledge of the `wsPath` can take
- * control of the OS user. For this reason, you should use an unguessable token when using this option.
+ * This option has no effect.
+ * @deprecated This option has no effect.
*/
- wsPath?: string;
- }): Promise<BrowserServer>;
-
- /**
- * Returns browser name. For example: `'chromium'`, `'webkit'` or `'firefox'`.
- */
- name(): string;
-}
-
-/**
- * - extends: [EventEmitter]
- *
- * The `CDPSession` instances are used to talk raw Chrome Devtools Protocol:
- * - protocol methods can be called with `session.send` method.
- * - protocol events can be subscribed to with `session.on` method.
- *
- * Useful links:
- * - Documentation on DevTools Protocol can be found here:
- * [DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/).
- * - Getting Started with DevTools Protocol:
- * https://github.com/aslushnikov/getting-started-with-cdp/blob/master/README.md
- *
- * ```js
- * const client = await page.context().newCDPSession(page);
- * await client.send('Animation.enable');
- * client.on('Animation.animationCreated', () => console.log('Animation created!'));
- * const response = await client.send('Animation.getPlaybackRate');
- * console.log('playback rate is ' + response.playbackRate);
- * await client.send('Animation.setPlaybackRate', {
- * playbackRate: response.playbackRate / 2
- * });
- * ```
- *
- */
-export interface CDPSession {
- on: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;
- addListener: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;
- off: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;
- removeListener: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;
- once: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;
- /**
- * @param method Protocol method name.
- * @param params Optional method parameters.
- */
- send<T extends keyof Protocol.CommandParameters>(
- method: T,
- params?: Protocol.CommandParameters[T]
- ): Promise<Protocol.CommandReturnValues[T]>;
- /**
- * Detaches the CDPSession from the target. Once detached, the CDPSession object won't emit any events and can't be
- * used to send messages.
- */
- detach(): Promise<void>;
-}
-
-type DeviceDescriptor = {
- viewport: ViewportSize;
- userAgent: string;
- deviceScaleFactor: number;
- isMobile: boolean;
- hasTouch: boolean;
- defaultBrowserType: 'chromium' | 'firefox' | 'webkit';
-};
-
-export namespace errors {
+ noWaitAfter?: boolean;
-/**
- * - extends: [Error]
- *
- * TimeoutError is emitted whenever certain operations are terminated due to timeout, e.g.
- * [locator.waitFor([options])](https://playwright.dev/docs/api/class-locator#locator-wait-for) or
- * [browserType.launch([options])](https://playwright.dev/docs/api/class-browsertype#browser-type-launch).
- *
- * ```js
- * const playwright = require('playwright');
- *
- * (async () => {
- * const browser = await playwright.chromium.launch();
- * const context = await browser.newContext();
- * const page = await context.newPage();
- * try {
- * await page.locator('text=Foo').click({
- * timeout: 100,
- * });
- * } catch (error) {
- * if (error instanceof playwright.errors.TimeoutError)
- * console.log('Timeout!');
- * }
- * await browser.close();
- * })();
- * ```
- *
- */
-class TimeoutError extends Error {
-}
+ /**
+ * A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of
+ * the element.
+ */
+ position?: {
+ x: number;
-}
+ y: number;
+ };
+
+ /**
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
+ */
+ timeout?: number;
+
+ /**
+ * When set, this method only performs the [actionability](https://playwright.dev/docs/actionability) checks and skips the action. Defaults
+ * to `false`. Useful to wait until the element is ready for the action without performing it.
+ */
+ trial?: boolean;
+ }): Promise<void>;
-/**
- * The Accessibility class provides methods for inspecting Chromium's accessibility tree. The accessibility tree is
- * used by assistive technology such as [screen readers](https://en.wikipedia.org/wiki/Screen_reader) or
- * [switches](https://en.wikipedia.org/wiki/Switch_access).
- *
- * Accessibility is a very platform-specific thing. On different platforms, there are different screen readers that
- * might have wildly different output.
- *
- * Rendering engines of Chromium, Firefox and WebKit have a concept of "accessibility tree", which is then translated
- * into different platform-specific APIs. Accessibility namespace gives access to this Accessibility Tree.
- *
- * Most of the accessibility tree gets filtered out when converting from internal browser AX Tree to Platform-specific
- * AX-Tree or by assistive technologies themselves. By default, Playwright tries to approximate this filtering,
- * exposing only the "interesting" nodes of the tree.
- */
-export interface Accessibility {
/**
- * Captures the current state of the accessibility tree. The returned object represents the root accessible node of
- * the page.
+ * Returns when element specified by locator satisfies the `state` option.
*
- * **NOTE** The Chromium accessibility tree contains nodes that go unused on most platforms and by most screen
- * readers. Playwright will discard them as well for an easier to process tree, unless `interestingOnly` is set to
- * `false`.
+ * If target element already satisfies the condition, the method returns immediately. Otherwise, waits for up to
+ * `timeout` milliseconds until the condition is met.
*
* **Usage**
*
- * An example of dumping the entire accessibility tree:
- *
- * ```js
- * const snapshot = await page.accessibility.snapshot();
- * console.log(snapshot);
- * ```
- *
- * An example of logging the focused node's name:
- *
* ```js
- * const snapshot = await page.accessibility.snapshot();
- * const node = findFocusedNode(snapshot);
- * console.log(node && node.name);
- *
- * function findFocusedNode(node) {
- * if (node.focused)
- * return node;
- * for (const child of node.children || []) {
- * const foundNode = findFocusedNode(child);
- * if (foundNode)
- * return foundNode;
- * }
- * return null;
- * }
+ * const orderSent = page.locator('#order-sent');
+ * await orderSent.waitFor();
* ```
*
- * @deprecated This method is deprecated. Please use other libraries such as [Axe](https://www.deque.com/axe/) if you need to test
- * page accessibility. See our Node.js [guide](https://playwright.dev/docs/accessibility-testing) for integration with
- * Axe.
* @param options
*/
- snapshot(options?: AccessibilitySnapshotOptions): Promise<null|AccessibilityNode>;
-
-}
+ waitFor(options?: {
+ /**
+ * Defaults to `'visible'`. Can be either:
+ * - `'attached'` - wait for element to be present in DOM.
+ * - `'detached'` - wait for element to not be present in DOM.
+ * - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element
+ * without any content or with `display:none` has an empty bounding box and is not considered visible.
+ * - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or
+ * `visibility:hidden`. This is opposite to the `'visible'` option.
+ */
+ state?: "attached"|"detached"|"visible"|"hidden";
-type AccessibilityNode = {
- role: string;
- name: string;
- value?: string|number;
- description?: string;
- keyshortcuts?: string;
- roledescription?: string;
- valuetext?: string;
- disabled?: boolean;
- expanded?: boolean;
- focused?: boolean;
- modal?: boolean;
- multiline?: boolean;
- multiselectable?: boolean;
- readonly?: boolean;
- required?: boolean;
- selected?: boolean;
- checked?: boolean|"mixed";
- pressed?: boolean|"mixed";
- level?: number;
- valuemin?: number;
- valuemax?: number;
- autocomplete?: string;
- haspopup?: string;
- invalid?: string;
- orientation?: string;
- children?: AccessibilityNode[];
+ /**
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
+ */
+ timeout?: number;
+ }): Promise<void>;
}
-export const devices: Devices;
-
-//@ts-ignore this will be any if electron is not installed
-type ElectronType = typeof import('electron');
-
/**
- * Electron application representation. You can use
- * [electron.launch([options])](https://playwright.dev/docs/api/class-electron#electron-launch) to obtain the
- * application instance. This instance you can control main electron process as well as work with Electron windows:
+ * BrowserType provides methods to launch a specific browser instance or connect to an existing one. The following is
+ * a typical example of using Playwright to drive automation:
*
* ```js
- * const { _electron: electron } = require('playwright');
+ * const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
*
* (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();
+ * const browser = await chromium.launch();
+ * const page = await browser.newPage();
+ * await page.goto('https://example.com');
+ * // other actions...
+ * await browser.close();
* })();
* ```
*
*/
-export interface ElectronApplication {
- /**
- * Returns the return value of `pageFunction`.
- *
- * If the function passed to the
- * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)
- * returns a [Promise], then
- * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)
- * would wait for the promise to resolve and return its value.
- *
- * If the function passed to the
- * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)
- * returns a non-[Serializable] value, then
- * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)
- * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by
- * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.
- * @param pageFunction Function to be evaluated in the main Electron process.
- * @param arg Optional argument to pass to `pageFunction`.
- */
- evaluate<R, Arg>(pageFunction: PageFunctionOn<ElectronType, Arg, R>, arg: Arg): Promise<R>;
+export interface BrowserType<Unused = {}> {
/**
- * Returns the return value of `pageFunction`.
- *
- * If the function passed to the
- * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)
- * returns a [Promise], then
- * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)
- * would wait for the promise to resolve and return its value.
+ * This method attaches Playwright to an existing browser instance using the Chrome DevTools Protocol.
*
- * If the function passed to the
- * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)
- * returns a non-[Serializable] value, then
- * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)
- * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by
- * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.
- * @param pageFunction Function to be evaluated in the main Electron process.
- * @param arg Optional argument to pass to `pageFunction`.
- */
- evaluate<R>(pageFunction: PageFunctionOn<ElectronType, void, R>, arg?: any): Promise<R>;
-
- /**
- * Returns the return value of `pageFunction` as a {@link JSHandle}.
+ * The default browser context is accessible via
+ * [browser.contexts()](https://playwright.dev/docs/api/class-browser#browser-contexts).
*
- * The only difference between
- * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)
- * and
- * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)
- * is that
- * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)
- * returns {@link JSHandle}.
+ * **NOTE** Connecting over the Chrome DevTools Protocol is only supported for Chromium-based browsers.
*
- * If the function passed to the
- * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)
- * returns a [Promise], then
- * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)
- * would wait for the promise to resolve and return its value.
- * @param pageFunction Function to be evaluated in the main Electron process.
- * @param arg Optional argument to pass to `pageFunction`.
- */
- evaluateHandle<R, Arg>(pageFunction: PageFunctionOn<ElectronType, Arg, R>, arg: Arg): Promise<SmartHandle<R>>;
- /**
- * Returns the return value of `pageFunction` as a {@link JSHandle}.
+ * **Usage**
*
- * The only difference between
- * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)
- * and
- * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)
- * is that
- * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)
- * returns {@link JSHandle}.
+ * ```js
+ * const browser = await playwright.chromium.connectOverCDP('http://localhost:9222');
+ * const defaultContext = browser.contexts()[0];
+ * const page = defaultContext.pages()[0];
+ * ```
*
- * If the function passed to the
- * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)
- * returns a [Promise], then
- * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)
- * would wait for the promise to resolve and return its value.
- * @param pageFunction Function to be evaluated in the main Electron process.
- * @param arg Optional argument to pass to `pageFunction`.
+ * @param endpointURL A CDP websocket endpoint or http url to connect to. For example `http://localhost:9222/` or
+ * `ws://127.0.0.1:9222/devtools/browser/387adf4c-243f-4051-a181-46798f4a46f4`.
+ * @param options
*/
- evaluateHandle<R>(pageFunction: PageFunctionOn<ElectronType, void, R>, arg?: any): Promise<SmartHandle<R>>;
+ connectOverCDP(endpointURL: string, options?: ConnectOverCDPOptions): Promise<Browser>;
/**
- * This event is issued when the application process has been terminated.
+ * Option `wsEndpoint` is deprecated. Instead use `endpointURL`.
+ * @deprecated
*/
- on(event: 'close', listener: () => any): this;
-
/**
- * Emitted when JavaScript within the Electron main process calls one of console API methods, e.g. `console.log` or
- * `console.dir`.
+ * This method attaches Playwright to an existing browser instance using the Chrome DevTools Protocol.
*
- * The arguments passed into `console.log` are available on the {@link ConsoleMessage} event handler argument.
+ * The default browser context is accessible via
+ * [browser.contexts()](https://playwright.dev/docs/api/class-browser#browser-contexts).
+ *
+ * **NOTE** Connecting over the Chrome DevTools Protocol is only supported for Chromium-based browsers.
*
* **Usage**
*
* ```js
- * electronApp.on('console', async msg => {
- * const values = [];
- * for (const arg of msg.args())
- * values.push(await arg.jsonValue());
- * console.log(...values);
- * });
- * await electronApp.evaluate(() => console.log('hello', 5, { foo: 'bar' }));
+ * const browser = await playwright.chromium.connectOverCDP('http://localhost:9222');
+ * const defaultContext = browser.contexts()[0];
+ * const page = defaultContext.pages()[0];
* ```
*
+ * @param endpointURL A CDP websocket endpoint or http url to connect to. For example `http://localhost:9222/` or
+ * `ws://127.0.0.1:9222/devtools/browser/387adf4c-243f-4051-a181-46798f4a46f4`.
+ * @param options
*/
- on(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;
-
- /**
- * This event is issued for every window that is created **and loaded** in Electron. It contains a {@link Page} that
- * can be used for Playwright automation.
- */
- on(event: 'window', listener: (page: Page) => any): this;
-
+ connectOverCDP(options: ConnectOverCDPOptions & { wsEndpoint?: string }): Promise<Browser>;
/**
- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.
+ * This method attaches Playwright to an existing browser instance. When connecting to another browser launched via
+ * `BrowserType.launchServer` in Node.js, the major and minor version needs to match the client version (1.2.3 → is
+ * compatible with 1.2.x).
+ * @param wsEndpoint A browser websocket endpoint to connect to.
+ * @param options
*/
- once(event: 'close', listener: () => any): this;
-
+ connect(wsEndpoint: string, options?: ConnectOptions): Promise<Browser>;
/**
- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.
+ * wsEndpoint in options is deprecated. Instead use `wsEndpoint`.
+ * @param wsEndpoint A browser websocket endpoint to connect to.
+ * @param options
+ * @deprecated
*/
- once(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;
-
/**
- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.
+ * This method attaches Playwright to an existing browser instance. When connecting to another browser launched via
+ * `BrowserType.launchServer` in Node.js, the major and minor version needs to match the client version (1.2.3 → is
+ * compatible with 1.2.x).
+ * @param wsEndpoint A browser websocket endpoint to connect to.
+ * @param options
*/
- once(event: 'window', listener: (page: Page) => any): this;
-
+ connect(options: ConnectOptions & { wsEndpoint?: string }): Promise<Browser>;
/**
- * This event is issued when the application process has been terminated.
+ * A path where Playwright expects to find a bundled browser executable.
*/
- addListener(event: 'close', listener: () => any): this;
+ executablePath(): string;
/**
- * Emitted when JavaScript within the Electron main process calls one of console API methods, e.g. `console.log` or
- * `console.dir`.
- *
- * The arguments passed into `console.log` are available on the {@link ConsoleMessage} event handler argument.
+ * Returns the browser instance.
*
* **Usage**
*
+ * You can use `ignoreDefaultArgs` to filter out `--mute-audio` from default arguments:
+ *
* ```js
- * electronApp.on('console', async msg => {
- * const values = [];
- * for (const arg of msg.args())
- * values.push(await arg.jsonValue());
- * console.log(...values);
+ * const browser = await chromium.launch({ // Or 'firefox' or 'webkit'.
+ * ignoreDefaultArgs: ['--mute-audio']
* });
- * await electronApp.evaluate(() => console.log('hello', 5, { foo: 'bar' }));
* ```
*
+ * > **Chromium-only** Playwright can also be used to control the Google Chrome or Microsoft Edge browsers, but it
+ * works best with the version of Chromium it is bundled with. There is no guarantee it will work with any other
+ * version. Use `executablePath` option with extreme caution.
+ * >
+ * > If Google Chrome (rather than Chromium) is preferred, a
+ * [Chrome Canary](https://www.google.com/chrome/browser/canary.html) or
+ * [Dev Channel](https://www.chromium.org/getting-involved/dev-channel) build is suggested.
+ * >
+ * > Stock browsers like Google Chrome and Microsoft Edge are suitable for tests that require proprietary media codecs
+ * for video playback. See
+ * [this article](https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/) for
+ * other differences between Chromium and Chrome.
+ * [This article](https://chromium.googlesource.com/chromium/src/+/lkgr/docs/chromium_browser_vs_google_chrome.md)
+ * describes some differences for Linux users.
+ * @param options
*/
- addListener(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;
+ launch(options?: LaunchOptions): Promise<Browser>;
/**
- * This event is issued for every window that is created **and loaded** in Electron. It contains a {@link Page} that
- * can be used for Playwright automation.
+ * Returns the persistent browser context instance.
+ *
+ * Launches browser that uses persistent storage located at `userDataDir` and returns the only context. Closing this
+ * context will automatically close the browser.
+ * @param userDataDir Path to a User Data Directory, which stores browser session data like cookies and local storage. More details for
+ * [Chromium](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md#introduction) and
+ * [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options#User_Profile). Note that Chromium's
+ * user data directory is the **parent** directory of the "Profile Path" seen at `chrome://version`. Pass an empty
+ * string to use a temporary directory instead.
+ * @param options
*/
- addListener(event: 'window', listener: (page: Page) => any): this;
+ launchPersistentContext(userDataDir: string, options?: {
+ /**
+ * Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.
+ */
+ acceptDownloads?: boolean;
- /**
- * Removes an event listener added by `on` or `addListener`.
- */
- removeListener(event: 'close', listener: () => any): this;
+ /**
+ * **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality.
+ *
+ * Additional arguments to pass to the browser instance. The list of Chromium flags can be found
+ * [here](https://peter.sh/experiments/chromium-command-line-switches/).
+ */
+ args?: Array<string>;
- /**
- * Removes an event listener added by `on` or `addListener`.
- */
- removeListener(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;
+ /**
+ * When using [page.goto(url[, options])](https://playwright.dev/docs/api/class-page#page-goto),
+ * [page.route(url, handler[, options])](https://playwright.dev/docs/api/class-page#page-route),
+ * [page.waitForURL(url[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-url),
+ * [page.waitForRequest(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-request),
+ * or
+ * [page.waitForResponse(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-response)
+ * it takes the base URL in consideration by using the
+ * [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL.
+ * Unset by default. Examples:
+ * - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`
+ * - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in
+ * `http://localhost:3000/foo/bar.html`
+ * - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
+ * `http://localhost:3000/bar.html`
+ */
+ baseURL?: string;
- /**
- * Removes an event listener added by `on` or `addListener`.
- */
- removeListener(event: 'window', listener: (page: Page) => any): this;
+ /**
+ * Toggles bypassing page's Content-Security-Policy. Defaults to `false`.
+ */
+ bypassCSP?: boolean;
- /**
- * Removes an event listener added by `on` or `addListener`.
- */
- off(event: 'close', listener: () => any): this;
+ /**
+ * Browser distribution channel. Supported values are "chrome", "chrome-beta", "chrome-dev", "chrome-canary",
+ * "msedge", "msedge-beta", "msedge-dev", "msedge-canary". Read more about using
+ * [Google Chrome and Microsoft Edge](https://playwright.dev/docs/browsers#google-chrome--microsoft-edge).
+ */
+ channel?: string;
- /**
- * Removes an event listener added by `on` or `addListener`.
- */
- off(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;
+ /**
+ * Enable Chromium sandboxing. Defaults to `false`.
+ */
+ chromiumSandbox?: boolean;
- /**
- * Removes an event listener added by `on` or `addListener`.
- */
- off(event: 'window', listener: (page: Page) => any): this;
+ /**
+ * TLS Client Authentication allows the server to request a client certificate and verify it.
+ *
+ * **Details**
+ *
+ * An array of client certificates to be used. Each certificate object must have both `certPath` and `keyPath` or a
+ * single `pfxPath` to load the client certificate. Optionally, `passphrase` property should be provided if the
+ * certficiate is encrypted. The `origin` property should be provided with an exact match to the request origin that
+ * the certificate is valid for.
+ *
+ * **NOTE** Using Client Certificates in combination with Proxy Servers is not supported.
+ *
+ * **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
+ * work by replacing `localhost` with `local.playwright`.
+ */
+ clientCertificates?: Array<{
+ /**
+ * Exact origin that the certificate is valid for. Origin includes `https` protocol, a hostname and optionally a port.
+ */
+ origin: string;
- /**
- * This event is issued when the application process has been terminated.
- */
- prependListener(event: 'close', listener: () => any): this;
+ /**
+ * Path to the file with the certificate in PEM format.
+ */
+ certPath?: string;
- /**
- * Emitted when JavaScript within the Electron main process calls one of console API methods, e.g. `console.log` or
- * `console.dir`.
- *
- * The arguments passed into `console.log` are available on the {@link ConsoleMessage} event handler argument.
- *
- * **Usage**
- *
- * ```js
- * electronApp.on('console', async msg => {
- * const values = [];
- * for (const arg of msg.args())
- * values.push(await arg.jsonValue());
- * console.log(...values);
- * });
- * await electronApp.evaluate(() => console.log('hello', 5, { foo: 'bar' }));
- * ```
- *
- */
- prependListener(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;
+ /**
+ * Path to the file with the private key in PEM format.
+ */
+ keyPath?: string;
+
+ /**
+ * Path to the PFX or PKCS12 encoded private key and certificate chain.
+ */
+ pfxPath?: string;
+
+ /**
+ * Passphrase for the private key (PEM or PFX).
+ */
+ passphrase?: string;
+ }>;
+
+ /**
+ * 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.
+ * Passing `null` resets emulation to system defaults. Defaults to `'light'`.
+ */
+ colorScheme?: null|"light"|"dark"|"no-preference";
+
+ /**
+ * Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about
+ * [emulating devices with device scale factor](https://playwright.dev/docs/emulation#devices).
+ */
+ deviceScaleFactor?: number;
+
+ /**
+ * **Chromium-only** Whether to auto-open a Developer Tools panel for each tab. If this option is `true`, the
+ * `headless` option will be set `false`.
+ * @deprecated Use [debugging tools](https://playwright.dev/docs/debug) instead.
+ */
+ devtools?: boolean;
+
+ /**
+ * If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and
+ * is deleted when browser is closed. In either case, the downloads are deleted when the browser context they were
+ * created in is closed.
+ */
+ downloadsPath?: string;
- /**
- * This event is issued for every window that is created **and loaded** in Electron. It contains a {@link Page} that
- * can be used for Playwright automation.
- */
- prependListener(event: 'window', listener: (page: Page) => any): this;
+ /**
+ * Specify environment variables that will be visible to the browser. Defaults to `process.env`.
+ */
+ env?: { [key: string]: string|number|boolean; };
- /**
- * Returns the BrowserWindow object that corresponds to the given Playwright page.
- * @param page Page to retrieve the window for.
- */
- browserWindow(page: Page): Promise<JSHandle>;
+ /**
+ * Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is
+ * resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium,
+ * Firefox or WebKit, use at your own risk.
+ */
+ executablePath?: string;
- /**
- * Closes Electron application.
- */
- close(): Promise<void>;
+ /**
+ * An object containing additional HTTP headers to be sent with every request. Defaults to none.
+ */
+ extraHTTPHeaders?: { [key: string]: string; };
- /**
- * This method returns browser context that can be used for setting up context-wide routing, etc.
- */
- context(): BrowserContext;
+ /**
+ * Firefox user preferences. Learn more about the Firefox user preferences at
+ * [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox).
+ */
+ firefoxUserPrefs?: { [key: string]: string|number|boolean; };
- /**
- * Convenience method that waits for the first application window to be opened.
- *
- * **Usage**
- *
- * ```js
- * const electronApp = await electron.launch({
- * args: ['main.js']
- * });
- * const window = await electronApp.firstWindow();
- * // ...
- * ```
- *
- * @param options
- */
- firstWindow(options?: {
/**
- * Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
- * default value can be changed by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout).
+ * Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See
+ * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.
+ * Passing `null` resets emulation to system defaults. Defaults to `'none'`.
*/
- timeout?: number;
- }): Promise<Page>;
+ forcedColors?: null|"active"|"none";
- /**
- * Returns the main process for this Electron Application.
- */
- process(): ChildProcess;
+ geolocation?: {
+ /**
+ * Latitude between -90 and 90.
+ */
+ latitude: number;
- /**
- * This event is issued when the application process has been terminated.
- */
- waitForEvent(event: 'close', optionsOrPredicate?: { predicate?: () => boolean | Promise<boolean>, timeout?: number } | (() => boolean | Promise<boolean>)): Promise<void>;
+ /**
+ * Longitude between -180 and 180.
+ */
+ longitude: number;
- /**
- * Emitted when JavaScript within the Electron main process calls one of console API methods, e.g. `console.log` or
- * `console.dir`.
- *
- * The arguments passed into `console.log` are available on the {@link ConsoleMessage} event handler argument.
- *
- * **Usage**
- *
- * ```js
- * electronApp.on('console', async msg => {
- * const values = [];
- * for (const arg of msg.args())
- * values.push(await arg.jsonValue());
- * console.log(...values);
- * });
- * await electronApp.evaluate(() => console.log('hello', 5, { foo: 'bar' }));
- * ```
- *
- */
- waitForEvent(event: 'console', optionsOrPredicate?: { predicate?: (consoleMessage: ConsoleMessage) => boolean | Promise<boolean>, timeout?: number } | ((consoleMessage: ConsoleMessage) => boolean | Promise<boolean>)): Promise<ConsoleMessage>;
+ /**
+ * Non-negative accuracy value. Defaults to `0`.
+ */
+ accuracy?: number;
+ };
- /**
- * This event is issued for every window that is created **and loaded** in Electron. It contains a {@link Page} that
- * can be used for Playwright automation.
- */
- waitForEvent(event: 'window', optionsOrPredicate?: { predicate?: (page: Page) => boolean | Promise<boolean>, timeout?: number } | ((page: Page) => boolean | Promise<boolean>)): Promise<Page>;
+ /**
+ * Close the browser process on SIGHUP. Defaults to `true`.
+ */
+ handleSIGHUP?: boolean;
+ /**
+ * Close the browser process on Ctrl-C. Defaults to `true`.
+ */
+ handleSIGINT?: boolean;
- /**
- * Convenience method that returns all the opened windows.
- */
- windows(): Array<Page>;
+ /**
+ * Close the browser process on SIGTERM. Defaults to `true`.
+ */
+ handleSIGTERM?: boolean;
- [Symbol.asyncDispose](): Promise<void>;
-}
+ /**
+ * Specifies if viewport supports touch events. Defaults to false. Learn more about
+ * [mobile emulation](https://playwright.dev/docs/emulation#devices).
+ */
+ hasTouch?: boolean;
-export type AndroidElementInfo = {
- clazz: string;
- desc: string;
- res: string;
- pkg: string;
- text: string;
- bounds: { x: number, y: number, width: number, height: number };
- checkable: boolean;
- checked: boolean;
- clickable: boolean;
- enabled: boolean;
- focusable: boolean;
- focused: boolean;
- longClickable: boolean;
- scrollable: boolean;
- selected: boolean;
-};
+ /**
+ * Whether to run browser in headless mode. More details for
+ * [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and
+ * [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode). Defaults to `true` unless the
+ * `devtools` option is `true`.
+ */
+ headless?: boolean;
-export type AndroidSelector = {
- checkable?: boolean,
- checked?: boolean,
- clazz?: string | RegExp,
- clickable?: boolean,
- depth?: number,
- desc?: string | RegExp,
- enabled?: boolean,
- focusable?: boolean,
- focused?: boolean,
- hasChild?: { selector: AndroidSelector },
- hasDescendant?: { selector: AndroidSelector, maxDepth?: number },
- longClickable?: boolean,
- pkg?: string | RegExp,
- res?: string | RegExp,
- scrollable?: boolean,
- selected?: boolean,
- text?: string | RegExp,
-};
+ /**
+ * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
+ * origin is specified, the username and password are sent to any servers upon unauthorized responses.
+ */
+ httpCredentials?: {
+ username: string;
-export type AndroidKey =
- 'Unknown' |
- 'SoftLeft' | 'SoftRight' |
- 'Home' |
- 'Back' |
- 'Call' | 'EndCall' |
- '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' |
- 'Star' | 'Pound' | '*' | '#' |
- 'DialUp' | 'DialDown' | 'DialLeft' | 'DialRight' | 'DialCenter' |
- 'VolumeUp' | 'VolumeDown' |
- 'ChannelUp' | 'ChannelDown' |
- 'Power' |
- 'Camera' |
- 'Clear' |
- 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' |
- 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z' |
- 'Comma' | ',' |
- 'Period' | '.' |
- 'AltLeft' | 'AltRight' |
- 'ShiftLeft' | 'ShiftRight' |
- 'Tab' | '\t' |
- 'Space' | ' ' |
- 'Sym' |
- 'Explorer' |
- 'Envelop' |
- 'Enter' | '\n' |
- 'Del' |
- 'Grave' |
- 'Minus' | '-' |
- 'Equals' | '=' |
- 'LeftBracket' | '(' |
- 'RightBracket' | ')' |
- 'Backslash' | '\\' |
- 'Semicolon' | ';' |
- 'Apostrophe' | '`' |
- 'Slash' | '/' |
- 'At' | '@' |
- 'Num' |
- 'HeadsetHook' |
- 'Focus' |
- 'Plus' | '+' |
- 'Menu' |
- 'Notification' |
- 'Search' |
- 'RecentApps' |
- 'AppSwitch' |
- 'Assist' |
- 'Cut' |
- 'Copy' |
- 'Paste';
+ password: string;
-export const _electron: Electron;
-export const _android: Android;
+ /**
+ * Restrain sending http credentials on specific origin (scheme://host:port).
+ */
+ origin?: string;
+
+ /**
+ * This option only applies to the requests sent from corresponding {@link APIRequestContext} and does not affect
+ * requests sent from the browser. `'always'` - `Authorization` header with basic authentication credentials will be
+ * sent with the each API request. `'unauthorized` - the credentials are only sent when 401 (Unauthorized) response
+ * with `WWW-Authenticate` header is received. Defaults to `'unauthorized'`.
+ */
+ send?: "unauthorized"|"always";
+ };
+
+ /**
+ * If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. If an array is
+ * given, then filters out the given default arguments. Dangerous option; use with care. Defaults to `false`.
+ */
+ ignoreDefaultArgs?: boolean|Array<string>;
+
+ /**
+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
+ */
+ ignoreHTTPSErrors?: boolean;
-// This is required to not export everything by default. See https://github.com/Microsoft/TypeScript/issues/19545#issuecomment-340490459
-export {};
+ /**
+ * Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,
+ * so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more
+ * about [mobile emulation](https://playwright.dev/docs/emulation#ismobile).
+ */
+ isMobile?: boolean;
+ /**
+ * Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about
+ * [disabling JavaScript](https://playwright.dev/docs/emulation#javascript-enabled).
+ */
+ javaScriptEnabled?: boolean;
-/**
- * Playwright has **experimental** support for Android automation. This includes Chrome for Android and Android
- * WebView.
- *
- * *Requirements*
- * - Android device or AVD Emulator.
- * - [ADB daemon](https://developer.android.com/studio/command-line/adb) running and authenticated with your device.
- * Typically running `adb devices` is all you need to do.
- * - [`Chrome 87`](https://play.google.com/store/apps/details?id=com.android.chrome) or newer installed on the
- * device
- * - "Enable command line on non-rooted devices" enabled in `chrome://flags`.
- *
- * *Known limitations*
- * - Raw USB operation is not yet supported, so you need ADB.
- * - Device needs to be awake to produce screenshots. Enabling "Stay awake" developer mode will help.
- * - We didn't run all the tests against the device, so not everything works.
- *
- * *How to run*
- *
- * An example of the Android automation script would be:
- *
- * ```js
- * const { _android: android } = require('playwright');
- *
- * (async () => {
- * // Connect to the device.
- * const [device] = await android.devices();
- * console.log(`Model: ${device.model()}`);
- * console.log(`Serial: ${device.serial()}`);
- * // Take screenshot of the whole device.
- * await device.screenshot({ path: 'device.png' });
- *
- * {
- * // --------------------- WebView -----------------------
- *
- * // Launch an application with WebView.
- * await device.shell('am force-stop org.chromium.webview_shell');
- * await device.shell('am start org.chromium.webview_shell/.WebViewBrowserActivity');
- * // Get the WebView.
- * const webview = await device.webView({ pkg: 'org.chromium.webview_shell' });
- *
- * // Fill the input box.
- * await device.fill({
- * res: 'org.chromium.webview_shell:id/url_field',
- * }, 'github.com/microsoft/playwright');
- * await device.press({
- * res: 'org.chromium.webview_shell:id/url_field',
- * }, 'Enter');
- *
- * // Work with WebView's page as usual.
- * const page = await webview.page();
- * await page.waitForNavigation({ url: /.*microsoft\/playwright.*\/ });
- * console.log(await page.title());
- * }
- *
- * {
- * // --------------------- Browser -----------------------
- *
- * // Launch Chrome browser.
- * await device.shell('am force-stop com.android.chrome');
- * const context = await device.launchBrowser();
- *
- * // Use BrowserContext as usual.
- * const page = await context.newPage();
- * await page.goto('https://webkit.org/');
- * console.log(await page.evaluate(() => window.location.href));
- * await page.screenshot({ path: 'page.png' });
- *
- * await context.close();
- * }
- *
- * // Close the device.
- * await device.close();
- * })();
- * ```
- *
- */
-export interface Android {
- /**
- * This methods attaches Playwright to an existing Android device. Use
- * [android.launchServer([options])](https://playwright.dev/docs/api/class-android#android-launch-server) to launch a
- * new Android server instance.
- * @param wsEndpoint A browser websocket endpoint to connect to.
- * @param options
- */
- connect(wsEndpoint: string, options?: {
/**
- * Additional HTTP headers to be sent with web socket connect request. Optional.
+ * Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value,
+ * `Accept-Language` request header value as well as number and date formatting rules. Defaults to the system default
+ * locale. Learn more about emulation in our [emulation guide](https://playwright.dev/docs/emulation#locale--timezone).
*/
- headers?: { [key: string]: string; };
+ locale?: string;
/**
- * Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
- * on. Defaults to `0`.
+ * Logger sink for Playwright logging.
*/
- slowMo?: number;
+ logger?: Logger;
/**
- * Maximum time in milliseconds to wait for the connection to be established. Defaults to `30000` (30 seconds). Pass
- * `0` to disable timeout.
+ * Whether to emulate network being offline. Defaults to `false`. Learn more about
+ * [network emulation](https://playwright.dev/docs/emulation#offline).
*/
- timeout?: number;
- }): Promise<AndroidDevice>;
+ offline?: boolean;
- /**
- * Returns the list of detected Android devices.
- * @param options
- */
- devices(options?: {
/**
- * Optional host to establish ADB server connection. Default to `127.0.0.1`.
+ * A list of permissions to grant to all pages in this context. See
+ * [browserContext.grantPermissions(permissions[, options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-grant-permissions)
+ * for more details. Defaults to none.
*/
- host?: string;
+ permissions?: Array<string>;
/**
- * Prevents automatic playwright driver installation on attach. Assumes that the drivers have been installed already.
+ * Network proxy settings.
*/
- omitDriverInstall?: boolean;
+ 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 comma-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;
+ };
/**
- * Optional port to establish ADB server connection. Default to `5037`.
+ * Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into `recordHar.path` file.
+ * If not specified, the HAR is not recorded. Make sure to await
+ * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for
+ * the HAR to be saved.
*/
- port?: number;
- }): Promise<Array<AndroidDevice>>;
+ recordHar?: {
+ /**
+ * Optional setting to control whether to omit request content from the HAR. Defaults to `false`. Deprecated, use
+ * `content` policy instead.
+ */
+ omitContent?: boolean;
+
+ /**
+ * Optional setting to control resource content management. If `omit` is specified, content is not persisted. If
+ * `attach` is specified, resources are persisted as separate files or entries in the ZIP archive. If `embed` is
+ * specified, content is stored inline the HAR file as per HAR specification. Defaults to `attach` for `.zip` output
+ * files and to `embed` for all other file extensions.
+ */
+ content?: "omit"|"embed"|"attach";
+
+ /**
+ * Path on the filesystem to write the HAR file to. If the file name ends with `.zip`, `content: 'attach'` is used by
+ * default.
+ */
+ path: string;
+
+ /**
+ * When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
+ * cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.
+ */
+ mode?: "full"|"minimal";
+
+ /**
+ * A glob or regex pattern to filter requests that are stored in the HAR. When a `baseURL` via the context options was
+ * provided and the passed URL is a path, it gets merged via the
+ * [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor. Defaults to none.
+ */
+ urlFilter?: string|RegExp;
+ };
- /**
- * Launches Playwright Android server that clients can connect to. See the following example:
- *
- * **Usage**
- *
- * Server Side:
- *
- * ```js
- * const { _android } = require('playwright');
- *
- * (async () => {
- * const browserServer = await _android.launchServer({
- * // If you have multiple devices connected and want to use a specific one.
- * // deviceSerialNumber: '<deviceSerialNumber>',
- * });
- * const wsEndpoint = browserServer.wsEndpoint();
- * console.log(wsEndpoint);
- * })();
- * ```
- *
- * Client Side:
- *
- * ```js
- * const { _android } = require('playwright');
- *
- * (async () => {
- * const device = await _android.connect('<wsEndpoint>');
- *
- * console.log(device.model());
- * console.log(device.serial());
- * await device.shell('am force-stop com.android.chrome');
- * const context = await device.launchBrowser();
- *
- * const page = await context.newPage();
- * await page.goto('https://webkit.org/');
- * console.log(await page.evaluate(() => window.location.href));
- * await page.screenshot({ path: 'page-chrome-1.png' });
- *
- * await context.close();
- * })();
- * ```
- *
- * @param options
- */
- launchServer(options?: {
/**
- * Optional host to establish ADB server connection. Default to `127.0.0.1`.
+ * Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded.
+ * Make sure to await
+ * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for
+ * videos to be saved.
*/
- adbHost?: string;
+ 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;
+ };
+ };
/**
- * Optional port to establish ADB server connection. Default to `5037`.
+ * Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See
+ * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.
+ * Passing `null` resets emulation to system defaults. Defaults to `'no-preference'`.
*/
- adbPort?: number;
+ reducedMotion?: null|"reduce"|"no-preference";
/**
- * Optional device serial number to launch the browser on. If not specified, it will throw if multiple devices are
- * connected.
+ * Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the
+ * `viewport` is set.
*/
- deviceSerialNumber?: string;
+ screen?: {
+ /**
+ * page width in pixels.
+ */
+ width: number;
+
+ /**
+ * page height in pixels.
+ */
+ height: number;
+ };
/**
- * Host to use for the web socket. It is optional and if it is omitted, the server will accept connections on the
- * unspecified IPv6 address (::) when IPv6 is available, or the unspecified IPv4 address (0.0.0.0) otherwise. Consider
- * hardening it with picking a specific interface.
+ * Whether to allow sites to register Service workers. Defaults to `'allow'`.
+ * - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be
+ * registered.
+ * - `'block'`: Playwright will block all registration of Service Workers.
*/
- host?: string;
+ serviceWorkers?: "allow"|"block";
/**
- * Prevents automatic playwright driver installation on attach. Assumes that the drivers have been installed already.
+ * Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
+ * on.
*/
- omitDriverInstall?: boolean;
+ slowMo?: number;
/**
- * Port to use for the web socket. Defaults to 0 that picks any available port.
+ * If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on
+ * selectors that imply single target DOM element will throw when more than one element matches the selector. This
+ * option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See {@link Locator} to
+ * learn more about the strict mode.
*/
- port?: number;
+ strictSelectors?: boolean;
/**
- * Path at which to serve the Android Server. For security, this defaults to an unguessable string.
- *
- * **NOTE** Any process or web page (including those running in Playwright) with knowledge of the `wsPath` can take
- * control of the OS user. For this reason, you should use an unguessable token when using this option.
+ * Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0`
+ * to disable timeout.
*/
- wsPath?: string;
- }): Promise<BrowserServer>;
-
- /**
- * This setting will change the default maximum time for all the methods accepting `timeout` option.
- * @param timeout Maximum time in milliseconds
- */
- setDefaultTimeout(timeout: number): void;
-}
-
-/**
- * {@link AndroidDevice} represents a connected device, either real hardware or emulated. Devices can be obtained
- * using [android.devices([options])](https://playwright.dev/docs/api/class-android#android-devices).
- */
-export interface AndroidDevice {
- /**
- * Emitted when the device connection gets closed.
- */
- on(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;
-
- /**
- * Emitted when a new WebView instance is detected.
- */
- on(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;
-
- /**
- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.
- */
- once(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;
-
- /**
- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.
- */
- once(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;
-
- /**
- * Emitted when the device connection gets closed.
- */
- addListener(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;
-
- /**
- * Emitted when a new WebView instance is detected.
- */
- addListener(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;
-
- /**
- * Removes an event listener added by `on` or `addListener`.
- */
- removeListener(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;
-
- /**
- * Removes an event listener added by `on` or `addListener`.
- */
- removeListener(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;
-
- /**
- * Removes an event listener added by `on` or `addListener`.
- */
- off(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;
-
- /**
- * Removes an event listener added by `on` or `addListener`.
- */
- off(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;
-
- /**
- * Emitted when the device connection gets closed.
- */
- prependListener(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;
-
- /**
- * Emitted when a new WebView instance is detected.
- */
- prependListener(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;
-
- /**
- * Disconnects from the device.
- */
- close(): Promise<void>;
-
- /**
- * Drags the widget defined by `selector` towards `dest` point.
- * @param selector Selector to drag.
- * @param dest Point to drag to.
- * @param options
- */
- drag(selector: AndroidSelector, dest: {
- x: number;
+ timeout?: number;
- y: number;
- }, options?: {
/**
- * Optional speed of the drag in pixels per second.
+ * Changes the timezone of the context. See
+ * [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)
+ * for a list of supported timezone IDs. Defaults to the system timezone.
*/
- speed?: number;
+ timezoneId?: string;
/**
- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
- * by using the
- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
- * method.
+ * If specified, traces are saved into this directory.
*/
- timeout?: number;
- }): Promise<void>;
+ tracesDir?: string;
- /**
- * Fills the specific `selector` input box with `text`.
- * @param selector Selector to fill.
- * @param text Text to be filled in the input box.
- * @param options
- */
- fill(selector: AndroidSelector, text: string, options?: {
/**
- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
- * by using the
- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
- * method.
+ * Specific user agent to use in this context.
*/
- timeout?: number;
- }): Promise<void>;
+ userAgent?: string;
- /**
- * Flings the widget defined by `selector` in the specified `direction`.
- * @param selector Selector to fling.
- * @param direction Fling direction.
- * @param options
- */
- fling(selector: AndroidSelector, direction: "down"|"up"|"left"|"right", options?: {
/**
- * Optional speed of the fling in pixels per second.
+ * @deprecated Use `recordVideo` instead.
*/
- speed?: number;
+ videoSize?: {
+ /**
+ * Video frame width.
+ */
+ width: number;
+
+ /**
+ * Video frame height.
+ */
+ height: number;
+ };
/**
- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
- * by using the
- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
- * method.
+ * @deprecated Use `recordVideo` instead.
*/
- timeout?: number;
- }): Promise<void>;
-
- /**
- * Returns information about a widget defined by `selector`.
- * @param selector Selector to return information about.
- */
- info(selector: AndroidSelector): Promise<AndroidElementInfo>;
+ videosPath?: string;
- /**
- * Installs an apk on the device.
- * @param file Either a path to the apk file, or apk file content.
- * @param options
- */
- installApk(file: string|Buffer, options?: {
/**
- * Optional arguments to pass to the `shell:cmd package install` call. Defaults to `-r -t -S`.
+ * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use `null` to disable the consistent
+ * viewport emulation. Learn more about [viewport emulation](https://playwright.dev/docs/emulation#viewport).
+ *
+ * **NOTE** The `null` value opts out from the default presets, makes viewport depend on the host window size defined
+ * by the operating system. It makes the execution of the tests non-deterministic.
*/
- args?: Array<string>;
- }): Promise<void>;
+ viewport?: null|{
+ /**
+ * page width in pixels.
+ */
+ width: number;
+
+ /**
+ * page height in pixels.
+ */
+ height: number;
+ };
+ }): Promise<BrowserContext>;
/**
- * Launches Chrome browser on the device, and returns its persistent context.
+ * Returns the browser app instance. You can connect to it via
+ * [browserType.connect(wsEndpoint[, options])](https://playwright.dev/docs/api/class-browsertype#browser-type-connect),
+ * which requires the major/minor client/server version to match (1.2.3 → is compatible with 1.2.x).
+ *
+ * **Usage**
+ *
+ * Launches browser server that client can connect to. An example of launching a browser executable and connecting to
+ * it later:
+ *
+ * ```js
+ * const { chromium } = require('playwright'); // Or 'webkit' or 'firefox'.
+ *
+ * (async () => {
+ * const browserServer = await chromium.launchServer();
+ * const wsEndpoint = browserServer.wsEndpoint();
+ * // Use web socket endpoint later to establish a connection.
+ * const browser = await chromium.connect(wsEndpoint);
+ * // Close browser instance.
+ * await browserServer.close();
+ * })();
+ * ```
+ *
* @param options
*/
- launchBrowser(options?: {
- /**
- * Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.
- */
- acceptDownloads?: boolean;
-
+ launchServer(options?: {
/**
* **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality.
*
@@ -14775,128 +14308,84 @@ export interface AndroidDevice {
args?: Array<string>;
/**
- * When using [page.goto(url[, options])](https://playwright.dev/docs/api/class-page#page-goto),
- * [page.route(url, handler[, options])](https://playwright.dev/docs/api/class-page#page-route),
- * [page.waitForURL(url[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-url),
- * [page.waitForRequest(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-request),
- * or
- * [page.waitForResponse(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-response)
- * it takes the base URL in consideration by using the
- * [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL.
- * Unset by default. Examples:
- * - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`
- * - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in
- * `http://localhost:3000/foo/bar.html`
- * - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
- * `http://localhost:3000/bar.html`
+ * Browser distribution channel. Supported values are "chrome", "chrome-beta", "chrome-dev", "chrome-canary",
+ * "msedge", "msedge-beta", "msedge-dev", "msedge-canary". Read more about using
+ * [Google Chrome and Microsoft Edge](https://playwright.dev/docs/browsers#google-chrome--microsoft-edge).
*/
- baseURL?: string;
+ channel?: string;
/**
- * Toggles bypassing page's Content-Security-Policy. Defaults to `false`.
+ * Enable Chromium sandboxing. Defaults to `false`.
*/
- bypassCSP?: boolean;
+ chromiumSandbox?: 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.
- * Passing `null` resets emulation to system defaults. Defaults to `'light'`.
+ * **Chromium-only** Whether to auto-open a Developer Tools panel for each tab. If this option is `true`, the
+ * `headless` option will be set `false`.
+ * @deprecated Use [debugging tools](https://playwright.dev/docs/debug) instead.
*/
- colorScheme?: null|"light"|"dark"|"no-preference";
+ devtools?: boolean;
/**
- * Optional package name to launch instead of default Chrome for Android.
+ * If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and
+ * is deleted when browser is closed. In either case, the downloads are deleted when the browser context they were
+ * created in is closed.
*/
- command?: string;
+ downloadsPath?: string;
/**
- * Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about
- * [emulating devices with device scale factor](https://playwright.dev/docs/emulation#devices).
+ * Specify environment variables that will be visible to the browser. Defaults to `process.env`.
*/
- deviceScaleFactor?: number;
+ env?: { [key: string]: string|number|boolean; };
/**
- * An object containing additional HTTP headers to be sent with every request. Defaults to none.
+ * Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is
+ * resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium,
+ * Firefox or WebKit, use at your own risk.
*/
- extraHTTPHeaders?: { [key: string]: string; };
+ executablePath?: string;
/**
- * Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See
- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.
- * Passing `null` resets emulation to system defaults. Defaults to `'none'`.
+ * Firefox user preferences. Learn more about the Firefox user preferences at
+ * [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox).
*/
- forcedColors?: null|"active"|"none";
-
- geolocation?: {
- /**
- * Latitude between -90 and 90.
- */
- latitude: number;
-
- /**
- * Longitude between -180 and 180.
- */
- longitude: number;
-
- /**
- * Non-negative accuracy value. Defaults to `0`.
- */
- accuracy?: number;
- };
+ firefoxUserPrefs?: { [key: string]: string|number|boolean; };
/**
- * Specifies if viewport supports touch events. Defaults to false. Learn more about
- * [mobile emulation](https://playwright.dev/docs/emulation#devices).
+ * Close the browser process on SIGHUP. Defaults to `true`.
*/
- hasTouch?: boolean;
+ handleSIGHUP?: boolean;
/**
- * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
- * origin is specified, the username and password are sent to any servers upon unauthorized responses.
+ * Close the browser process on Ctrl-C. Defaults to `true`.
*/
- httpCredentials?: {
- username: string;
-
- password: string;
-
- /**
- * Restrain sending http credentials on specific origin (scheme://host:port).
- */
- origin?: string;
-
- /**
- * This option only applies to the requests sent from corresponding {@link APIRequestContext} and does not affect
- * requests sent from the browser. `'always'` - `Authorization` header with basic authentication credentials will be
- * sent with the each API request. `'unauthorized` - the credentials are only sent when 401 (Unauthorized) response
- * with `WWW-Authenticate` header is received. Defaults to `'unauthorized'`.
- */
- send?: "unauthorized"|"always";
- };
+ handleSIGINT?: boolean;
/**
- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
+ * Close the browser process on SIGTERM. Defaults to `true`.
*/
- ignoreHTTPSErrors?: boolean;
+ handleSIGTERM?: boolean;
/**
- * Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,
- * so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more
- * about [mobile emulation](https://playwright.dev/docs/emulation#ismobile).
+ * Whether to run browser in headless mode. More details for
+ * [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and
+ * [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode). Defaults to `true` unless the
+ * `devtools` option is `true`.
*/
- isMobile?: boolean;
+ headless?: boolean;
/**
- * Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about
- * [disabling JavaScript](https://playwright.dev/docs/emulation#javascript-enabled).
+ * Host to use for the web socket. It is optional and if it is omitted, the server will accept connections on the
+ * unspecified IPv6 address (::) when IPv6 is available, or the unspecified IPv4 address (0.0.0.0) otherwise. Consider
+ * hardening it with picking a specific interface.
*/
- javaScriptEnabled?: boolean;
+ host?: 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. Defaults to the system default
- * locale. Learn more about emulation in our [emulation guide](https://playwright.dev/docs/emulation#locale--timezone).
+ * If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. If an array is
+ * given, then filters out the given default arguments. Dangerous option; use with care. Defaults to `false`.
*/
- locale?: string;
+ ignoreDefaultArgs?: boolean|Array<string>;
/**
* Logger sink for Playwright logging.
@@ -14904,17 +14393,9 @@ export interface AndroidDevice {
logger?: Logger;
/**
- * Whether to emulate network being offline. Defaults to `false`. Learn more about
- * [network emulation](https://playwright.dev/docs/emulation#offline).
- */
- 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. Defaults to none.
+ * Port to use for the web socket. Defaults to 0 that picks any available port.
*/
- permissions?: Array<string>;
+ port?: number;
/**
* Network proxy settings.
@@ -14926,703 +14407,1133 @@ export interface AndroidDevice {
*/
server: string;
- /**
- * Optional comma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.
- */
- bypass?: string;
+ /**
+ * Optional comma-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;
+ };
+
+ /**
+ * Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0`
+ * to disable timeout.
+ */
+ timeout?: number;
+
+ /**
+ * If specified, traces are saved into this directory.
+ */
+ tracesDir?: string;
+
+ /**
+ * Path at which to serve the Browser Server. For security, this defaults to an unguessable string.
+ *
+ * **NOTE** Any process or web page (including those running in Playwright) with knowledge of the `wsPath` can take
+ * control of the OS user. For this reason, you should use an unguessable token when using this option.
+ */
+ wsPath?: string;
+ }): Promise<BrowserServer>;
+
+ /**
+ * Returns browser name. For example: `'chromium'`, `'webkit'` or `'firefox'`.
+ */
+ name(): string;
+}
+
+/**
+ * - extends: [EventEmitter]
+ *
+ * The `CDPSession` instances are used to talk raw Chrome Devtools Protocol:
+ * - protocol methods can be called with `session.send` method.
+ * - protocol events can be subscribed to with `session.on` method.
+ *
+ * Useful links:
+ * - Documentation on DevTools Protocol can be found here:
+ * [DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/).
+ * - Getting Started with DevTools Protocol:
+ * https://github.com/aslushnikov/getting-started-with-cdp/blob/master/README.md
+ *
+ * ```js
+ * const client = await page.context().newCDPSession(page);
+ * await client.send('Animation.enable');
+ * client.on('Animation.animationCreated', () => console.log('Animation created!'));
+ * const response = await client.send('Animation.getPlaybackRate');
+ * console.log('playback rate is ' + response.playbackRate);
+ * await client.send('Animation.setPlaybackRate', {
+ * playbackRate: response.playbackRate / 2
+ * });
+ * ```
+ *
+ */
+export interface CDPSession {
+ on: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;
+ addListener: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;
+ off: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;
+ removeListener: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;
+ once: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;
+ /**
+ * @param method Protocol method name.
+ * @param params Optional method parameters.
+ */
+ send<T extends keyof Protocol.CommandParameters>(
+ method: T,
+ params?: Protocol.CommandParameters[T]
+ ): Promise<Protocol.CommandReturnValues[T]>;
+ /**
+ * Detaches the CDPSession from the target. Once detached, the CDPSession object won't emit any events and can't be
+ * used to send messages.
+ */
+ detach(): Promise<void>;
+}
+
+type DeviceDescriptor = {
+ viewport: ViewportSize;
+ userAgent: string;
+ deviceScaleFactor: number;
+ isMobile: boolean;
+ hasTouch: boolean;
+ defaultBrowserType: 'chromium' | 'firefox' | 'webkit';
+};
+
+export namespace errors {
+
+/**
+ * - extends: [Error]
+ *
+ * TimeoutError is emitted whenever certain operations are terminated due to timeout, e.g.
+ * [locator.waitFor([options])](https://playwright.dev/docs/api/class-locator#locator-wait-for) or
+ * [browserType.launch([options])](https://playwright.dev/docs/api/class-browsertype#browser-type-launch).
+ *
+ * ```js
+ * const playwright = require('playwright');
+ *
+ * (async () => {
+ * const browser = await playwright.chromium.launch();
+ * const context = await browser.newContext();
+ * const page = await context.newPage();
+ * try {
+ * await page.locator('text=Foo').click({
+ * timeout: 100,
+ * });
+ * } catch (error) {
+ * if (error instanceof playwright.errors.TimeoutError)
+ * console.log('Timeout!');
+ * }
+ * await browser.close();
+ * })();
+ * ```
+ *
+ */
+class TimeoutError extends Error {
+}
- /**
- * Optional username to use if HTTP proxy requires authentication.
- */
- username?: string;
+}
- /**
- * Optional password to use if HTTP proxy requires authentication.
- */
- password?: string;
- };
+/**
+ * The Accessibility class provides methods for inspecting Chromium's accessibility tree. The accessibility tree is
+ * used by assistive technology such as [screen readers](https://en.wikipedia.org/wiki/Screen_reader) or
+ * [switches](https://en.wikipedia.org/wiki/Switch_access).
+ *
+ * Accessibility is a very platform-specific thing. On different platforms, there are different screen readers that
+ * might have wildly different output.
+ *
+ * Rendering engines of Chromium, Firefox and WebKit have a concept of "accessibility tree", which is then translated
+ * into different platform-specific APIs. Accessibility namespace gives access to this Accessibility Tree.
+ *
+ * Most of the accessibility tree gets filtered out when converting from internal browser AX Tree to Platform-specific
+ * AX-Tree or by assistive technologies themselves. By default, Playwright tries to approximate this filtering,
+ * exposing only the "interesting" nodes of the tree.
+ */
+export interface Accessibility {
+ /**
+ * Captures the current state of the accessibility tree. The returned object represents the root accessible node of
+ * the page.
+ *
+ * **NOTE** The Chromium accessibility tree contains nodes that go unused on most platforms and by most screen
+ * readers. Playwright will discard them as well for an easier to process tree, unless `interestingOnly` is set to
+ * `false`.
+ *
+ * **Usage**
+ *
+ * An example of dumping the entire accessibility tree:
+ *
+ * ```js
+ * const snapshot = await page.accessibility.snapshot();
+ * console.log(snapshot);
+ * ```
+ *
+ * An example of logging the focused node's name:
+ *
+ * ```js
+ * const snapshot = await page.accessibility.snapshot();
+ * const node = findFocusedNode(snapshot);
+ * console.log(node && node.name);
+ *
+ * function findFocusedNode(node) {
+ * if (node.focused)
+ * return node;
+ * for (const child of node.children || []) {
+ * const foundNode = findFocusedNode(child);
+ * if (foundNode)
+ * return foundNode;
+ * }
+ * return null;
+ * }
+ * ```
+ *
+ * @deprecated This method is deprecated. Please use other libraries such as [Axe](https://www.deque.com/axe/) if you need to test
+ * page accessibility. See our Node.js [guide](https://playwright.dev/docs/accessibility-testing) for integration with
+ * Axe.
+ * @param options
+ */
+ snapshot(options?: AccessibilitySnapshotOptions): Promise<null|AccessibilityNode>;
- /**
- * Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into `recordHar.path` file.
- * If not specified, the HAR is not recorded. Make sure to await
- * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for
- * the HAR to be saved.
- */
- recordHar?: {
- /**
- * Optional setting to control whether to omit request content from the HAR. Defaults to `false`. Deprecated, use
- * `content` policy instead.
- */
- omitContent?: boolean;
+}
- /**
- * Optional setting to control resource content management. If `omit` is specified, content is not persisted. If
- * `attach` is specified, resources are persisted as separate files or entries in the ZIP archive. If `embed` is
- * specified, content is stored inline the HAR file as per HAR specification. Defaults to `attach` for `.zip` output
- * files and to `embed` for all other file extensions.
- */
- content?: "omit"|"embed"|"attach";
+type AccessibilityNode = {
+ role: string;
+ name: string;
+ value?: string|number;
+ description?: string;
+ keyshortcuts?: string;
+ roledescription?: string;
+ valuetext?: string;
+ disabled?: boolean;
+ expanded?: boolean;
+ focused?: boolean;
+ modal?: boolean;
+ multiline?: boolean;
+ multiselectable?: boolean;
+ readonly?: boolean;
+ required?: boolean;
+ selected?: boolean;
+ checked?: boolean|"mixed";
+ pressed?: boolean|"mixed";
+ level?: number;
+ valuemin?: number;
+ valuemax?: number;
+ autocomplete?: string;
+ haspopup?: string;
+ invalid?: string;
+ orientation?: string;
+ children?: AccessibilityNode[];
+}
- /**
- * Path on the filesystem to write the HAR file to. If the file name ends with `.zip`, `content: 'attach'` is used by
- * default.
- */
- path: string;
+export const devices: Devices;
- /**
- * When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
- * cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.
- */
- mode?: "full"|"minimal";
+//@ts-ignore this will be any if electron is not installed
+type ElectronType = typeof import('electron');
- /**
- * A glob or regex pattern to filter requests that are stored in the HAR. When a `baseURL` via the context options was
- * provided and the passed URL is a path, it gets merged via the
- * [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor. Defaults to none.
- */
- urlFilter?: string|RegExp;
- };
+/**
+ * Electron application representation. You can use
+ * [electron.launch([options])](https://playwright.dev/docs/api/class-electron#electron-launch) to obtain the
+ * application instance. This instance you can control main electron process as well as work with Electron windows:
+ *
+ * ```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();
+ * })();
+ * ```
+ *
+ */
+export interface ElectronApplication {
+ /**
+ * Returns the return value of `pageFunction`.
+ *
+ * If the function passed to the
+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)
+ * returns a [Promise], then
+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)
+ * would wait for the promise to resolve and return its value.
+ *
+ * If the function passed to the
+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)
+ * returns a non-[Serializable] value, then
+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)
+ * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by
+ * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.
+ * @param pageFunction Function to be evaluated in the main Electron process.
+ * @param arg Optional argument to pass to `pageFunction`.
+ */
+ evaluate<R, Arg>(pageFunction: PageFunctionOn<ElectronType, Arg, R>, arg: Arg): Promise<R>;
+ /**
+ * Returns the return value of `pageFunction`.
+ *
+ * If the function passed to the
+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)
+ * returns a [Promise], then
+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)
+ * would wait for the promise to resolve and return its value.
+ *
+ * If the function passed to the
+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)
+ * returns a non-[Serializable] value, then
+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)
+ * returns `undefined`. Playwright also supports transferring some additional values that are not serializable by
+ * `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.
+ * @param pageFunction Function to be evaluated in the main Electron process.
+ * @param arg Optional argument to pass to `pageFunction`.
+ */
+ evaluate<R>(pageFunction: PageFunctionOn<ElectronType, void, R>, arg?: any): Promise<R>;
- /**
- * Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded.
- * Make sure to await
- * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for
- * videos to be saved.
- */
- recordVideo?: {
- /**
- * Path to the directory to put videos into.
- */
- dir: string;
+ /**
+ * Returns the return value of `pageFunction` as a {@link JSHandle}.
+ *
+ * The only difference between
+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)
+ * and
+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)
+ * is that
+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)
+ * returns {@link JSHandle}.
+ *
+ * If the function passed to the
+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)
+ * returns a [Promise], then
+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)
+ * would wait for the promise to resolve and return its value.
+ * @param pageFunction Function to be evaluated in the main Electron process.
+ * @param arg Optional argument to pass to `pageFunction`.
+ */
+ evaluateHandle<R, Arg>(pageFunction: PageFunctionOn<ElectronType, Arg, R>, arg: Arg): Promise<SmartHandle<R>>;
+ /**
+ * Returns the return value of `pageFunction` as a {@link JSHandle}.
+ *
+ * The only difference between
+ * [electronApplication.evaluate(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate)
+ * and
+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)
+ * is that
+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)
+ * returns {@link JSHandle}.
+ *
+ * If the function passed to the
+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)
+ * returns a [Promise], then
+ * [electronApplication.evaluateHandle(pageFunction[, arg])](https://playwright.dev/docs/api/class-electronapplication#electron-application-evaluate-handle)
+ * would wait for the promise to resolve and return its value.
+ * @param pageFunction Function to be evaluated in the main Electron process.
+ * @param arg Optional argument to pass to `pageFunction`.
+ */
+ evaluateHandle<R>(pageFunction: PageFunctionOn<ElectronType, void, R>, arg?: any): Promise<SmartHandle<R>>;
+ /**
+ * This event is issued when the application process has been terminated.
+ */
+ on(event: 'close', listener: () => any): this;
- /**
- * 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;
+ /**
+ * Emitted when JavaScript within the Electron main process calls one of console API methods, e.g. `console.log` or
+ * `console.dir`.
+ *
+ * The arguments passed into `console.log` are available on the {@link ConsoleMessage} event handler argument.
+ *
+ * **Usage**
+ *
+ * ```js
+ * electronApp.on('console', async msg => {
+ * const values = [];
+ * for (const arg of msg.args())
+ * values.push(await arg.jsonValue());
+ * console.log(...values);
+ * });
+ * await electronApp.evaluate(() => console.log('hello', 5, { foo: 'bar' }));
+ * ```
+ *
+ */
+ on(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;
- /**
- * Video frame height.
- */
- height: number;
- };
- };
+ /**
+ * This event is issued for every window that is created **and loaded** in Electron. It contains a {@link Page} that
+ * can be used for Playwright automation.
+ */
+ on(event: 'window', listener: (page: Page) => any): this;
- /**
- * Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See
- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.
- * Passing `null` resets emulation to system defaults. Defaults to `'no-preference'`.
- */
- reducedMotion?: null|"reduce"|"no-preference";
+ /**
+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.
+ */
+ once(event: 'close', listener: () => any): this;
- /**
- * 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;
+ /**
+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.
+ */
+ once(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;
- /**
- * page height in pixels.
- */
- height: number;
- };
+ /**
+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.
+ */
+ once(event: 'window', listener: (page: Page) => any): this;
- /**
- * Whether to allow sites to register Service workers. Defaults to `'allow'`.
- * - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be
- * registered.
- * - `'block'`: Playwright will block all registration of Service Workers.
- */
- serviceWorkers?: "allow"|"block";
+ /**
+ * This event is issued when the application process has been terminated.
+ */
+ addListener(event: 'close', listener: () => any): this;
- /**
- * If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on
- * selectors that imply single target DOM element will throw when more than one element matches the selector. This
- * option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See {@link Locator} to
- * learn more about the strict mode.
- */
- strictSelectors?: boolean;
+ /**
+ * Emitted when JavaScript within the Electron main process calls one of console API methods, e.g. `console.log` or
+ * `console.dir`.
+ *
+ * The arguments passed into `console.log` are available on the {@link ConsoleMessage} event handler argument.
+ *
+ * **Usage**
+ *
+ * ```js
+ * electronApp.on('console', async msg => {
+ * const values = [];
+ * for (const arg of msg.args())
+ * values.push(await arg.jsonValue());
+ * console.log(...values);
+ * });
+ * await electronApp.evaluate(() => console.log('hello', 5, { foo: 'bar' }));
+ * ```
+ *
+ */
+ addListener(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;
- /**
- * Changes the timezone of the context. See
- * [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)
- * for a list of supported timezone IDs. Defaults to the system timezone.
- */
- timezoneId?: string;
+ /**
+ * This event is issued for every window that is created **and loaded** in Electron. It contains a {@link Page} that
+ * can be used for Playwright automation.
+ */
+ addListener(event: 'window', listener: (page: Page) => any): this;
- /**
- * Specific user agent to use in this context.
- */
- userAgent?: string;
+ /**
+ * Removes an event listener added by `on` or `addListener`.
+ */
+ removeListener(event: 'close', listener: () => any): this;
- /**
- * @deprecated Use `recordVideo` instead.
- */
- videoSize?: {
- /**
- * Video frame width.
- */
- width: number;
+ /**
+ * Removes an event listener added by `on` or `addListener`.
+ */
+ removeListener(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;
- /**
- * Video frame height.
- */
- height: number;
- };
+ /**
+ * Removes an event listener added by `on` or `addListener`.
+ */
+ removeListener(event: 'window', listener: (page: Page) => any): this;
- /**
- * @deprecated Use `recordVideo` instead.
- */
- videosPath?: string;
+ /**
+ * Removes an event listener added by `on` or `addListener`.
+ */
+ off(event: 'close', listener: () => any): this;
- /**
- * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use `null` to disable the consistent
- * viewport emulation. Learn more about [viewport emulation](https://playwright.dev/docs/emulation#viewport).
- *
- * **NOTE** The `null` value opts out from the default presets, makes viewport depend on the host window size defined
- * by the operating system. It makes the execution of the tests non-deterministic.
- */
- viewport?: null|{
- /**
- * page width in pixels.
- */
- width: number;
+ /**
+ * Removes an event listener added by `on` or `addListener`.
+ */
+ off(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;
- /**
- * page height in pixels.
- */
- height: number;
- };
- }): Promise<BrowserContext>;
+ /**
+ * Removes an event listener added by `on` or `addListener`.
+ */
+ off(event: 'window', listener: (page: Page) => any): this;
/**
- * Performs a long tap on the widget defined by `selector`.
- * @param selector Selector to tap on.
- * @param options
+ * This event is issued when the application process has been terminated.
*/
- longTap(selector: AndroidSelector, options?: {
- /**
- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
- * by using the
- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
- * method.
- */
- timeout?: number;
- }): Promise<void>;
+ prependListener(event: 'close', listener: () => any): this;
+
+ /**
+ * Emitted when JavaScript within the Electron main process calls one of console API methods, e.g. `console.log` or
+ * `console.dir`.
+ *
+ * The arguments passed into `console.log` are available on the {@link ConsoleMessage} event handler argument.
+ *
+ * **Usage**
+ *
+ * ```js
+ * electronApp.on('console', async msg => {
+ * const values = [];
+ * for (const arg of msg.args())
+ * values.push(await arg.jsonValue());
+ * console.log(...values);
+ * });
+ * await electronApp.evaluate(() => console.log('hello', 5, { foo: 'bar' }));
+ * ```
+ *
+ */
+ prependListener(event: 'console', listener: (consoleMessage: ConsoleMessage) => any): this;
/**
- * Device model.
+ * This event is issued for every window that is created **and loaded** in Electron. It contains a {@link Page} that
+ * can be used for Playwright automation.
*/
- model(): string;
+ prependListener(event: 'window', listener: (page: Page) => any): this;
/**
- * Launches a process in the shell on the device and returns a socket to communicate with the launched process.
- * @param command
+ * Returns the BrowserWindow object that corresponds to the given Playwright page.
+ * @param page Page to retrieve the window for.
*/
- open(command: string): Promise<AndroidSocket>;
+ browserWindow(page: Page): Promise<JSHandle>;
/**
- * Pinches the widget defined by `selector` in the closing direction.
- * @param selector Selector to pinch close.
- * @param percent The size of the pinch as a percentage of the widget's size.
- * @param options
+ * Closes Electron application.
*/
- pinchClose(selector: AndroidSelector, percent: number, options?: {
- /**
- * Optional speed of the pinch in pixels per second.
- */
- speed?: number;
-
- /**
- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
- * by using the
- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
- * method.
- */
- timeout?: number;
- }): Promise<void>;
+ close(): Promise<void>;
/**
- * Pinches the widget defined by `selector` in the open direction.
- * @param selector Selector to pinch open.
- * @param percent The size of the pinch as a percentage of the widget's size.
- * @param options
+ * This method returns browser context that can be used for setting up context-wide routing, etc.
*/
- pinchOpen(selector: AndroidSelector, percent: number, options?: {
- /**
- * Optional speed of the pinch in pixels per second.
- */
- speed?: number;
-
- /**
- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
- * by using the
- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
- * method.
- */
- timeout?: number;
- }): Promise<void>;
+ context(): BrowserContext;
/**
- * Presses the specific `key` in the widget defined by `selector`.
- * @param selector Selector to press the key in.
- * @param key The key to press.
+ * Convenience method that waits for the first application window to be opened.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const electronApp = await electron.launch({
+ * args: ['main.js']
+ * });
+ * const window = await electronApp.firstWindow();
+ * // ...
+ * ```
+ *
* @param options
*/
- press(selector: AndroidSelector, key: AndroidKey, options?: {
+ firstWindow(options?: {
/**
- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
- * by using the
- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
- * method.
+ * Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
+ * default value can be changed by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout).
*/
timeout?: number;
- }): Promise<void>;
+ }): Promise<Page>;
/**
- * Copies a file to the device.
- * @param file Either a path to the file, or file content.
- * @param path Path to the file on the device.
- * @param options
+ * Returns the main process for this Electron Application.
*/
- push(file: string|Buffer, path: string, options?: {
- /**
- * Optional file mode, defaults to `644` (`rw-r--r--`).
- */
- mode?: number;
- }): Promise<void>;
+ process(): ChildProcess;
/**
- * Returns the buffer with the captured screenshot of the device.
- * @param options
+ * This event is issued when the application process has been terminated.
*/
- screenshot(options?: {
- /**
- * The file path to save the image to. If `path` is a relative path, then it is resolved relative to the current
- * working directory. If no path is provided, the image won't be saved to the disk.
- */
- path?: string;
- }): Promise<Buffer>;
+ waitForEvent(event: 'close', optionsOrPredicate?: { predicate?: () => boolean | Promise<boolean>, timeout?: number } | (() => boolean | Promise<boolean>)): Promise<void>;
/**
- * Scrolls the widget defined by `selector` in the specified `direction`.
- * @param selector Selector to scroll.
- * @param direction Scroll direction.
- * @param percent Distance to scroll as a percentage of the widget's size.
- * @param options
+ * Emitted when JavaScript within the Electron main process calls one of console API methods, e.g. `console.log` or
+ * `console.dir`.
+ *
+ * The arguments passed into `console.log` are available on the {@link ConsoleMessage} event handler argument.
+ *
+ * **Usage**
+ *
+ * ```js
+ * electronApp.on('console', async msg => {
+ * const values = [];
+ * for (const arg of msg.args())
+ * values.push(await arg.jsonValue());
+ * console.log(...values);
+ * });
+ * await electronApp.evaluate(() => console.log('hello', 5, { foo: 'bar' }));
+ * ```
+ *
*/
- scroll(selector: AndroidSelector, direction: "down"|"up"|"left"|"right", percent: number, options?: {
- /**
- * Optional speed of the scroll in pixels per second.
- */
- speed?: number;
-
- /**
- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
- * by using the
- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
- * method.
- */
- timeout?: number;
- }): Promise<void>;
+ waitForEvent(event: 'console', optionsOrPredicate?: { predicate?: (consoleMessage: ConsoleMessage) => boolean | Promise<boolean>, timeout?: number } | ((consoleMessage: ConsoleMessage) => boolean | Promise<boolean>)): Promise<ConsoleMessage>;
/**
- * Device serial number.
+ * This event is issued for every window that is created **and loaded** in Electron. It contains a {@link Page} that
+ * can be used for Playwright automation.
*/
- serial(): string;
+ waitForEvent(event: 'window', optionsOrPredicate?: { predicate?: (page: Page) => boolean | Promise<boolean>, timeout?: number } | ((page: Page) => boolean | Promise<boolean>)): Promise<Page>;
- /**
- * This setting will change the default maximum time for all the methods accepting `timeout` option.
- * @param timeout Maximum time in milliseconds
- */
- setDefaultTimeout(timeout: number): void;
/**
- * Executes a shell command on the device and returns its output.
- * @param command Shell command to execute.
+ * Convenience method that returns all the opened windows.
*/
- shell(command: string): Promise<Buffer>;
+ windows(): Array<Page>;
- /**
- * Swipes the widget defined by `selector` in the specified `direction`.
- * @param selector Selector to swipe.
- * @param direction Swipe direction.
- * @param percent Distance to swipe as a percentage of the widget's size.
- * @param options
- */
- swipe(selector: AndroidSelector, direction: "down"|"up"|"left"|"right", percent: number, options?: {
- /**
- * Optional speed of the swipe in pixels per second.
- */
- speed?: number;
+ [Symbol.asyncDispose](): Promise<void>;
+}
+
+export type AndroidElementInfo = {
+ clazz: string;
+ desc: string;
+ res: string;
+ pkg: string;
+ text: string;
+ bounds: { x: number, y: number, width: number, height: number };
+ checkable: boolean;
+ checked: boolean;
+ clickable: boolean;
+ enabled: boolean;
+ focusable: boolean;
+ focused: boolean;
+ longClickable: boolean;
+ scrollable: boolean;
+ selected: boolean;
+};
+
+export type AndroidSelector = {
+ checkable?: boolean,
+ checked?: boolean,
+ clazz?: string | RegExp,
+ clickable?: boolean,
+ depth?: number,
+ desc?: string | RegExp,
+ enabled?: boolean,
+ focusable?: boolean,
+ focused?: boolean,
+ hasChild?: { selector: AndroidSelector },
+ hasDescendant?: { selector: AndroidSelector, maxDepth?: number },
+ longClickable?: boolean,
+ pkg?: string | RegExp,
+ res?: string | RegExp,
+ scrollable?: boolean,
+ selected?: boolean,
+ text?: string | RegExp,
+};
+
+export type AndroidKey =
+ 'Unknown' |
+ 'SoftLeft' | 'SoftRight' |
+ 'Home' |
+ 'Back' |
+ 'Call' | 'EndCall' |
+ '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' |
+ 'Star' | 'Pound' | '*' | '#' |
+ 'DialUp' | 'DialDown' | 'DialLeft' | 'DialRight' | 'DialCenter' |
+ 'VolumeUp' | 'VolumeDown' |
+ 'ChannelUp' | 'ChannelDown' |
+ 'Power' |
+ 'Camera' |
+ 'Clear' |
+ 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' |
+ 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z' |
+ 'Comma' | ',' |
+ 'Period' | '.' |
+ 'AltLeft' | 'AltRight' |
+ 'ShiftLeft' | 'ShiftRight' |
+ 'Tab' | '\t' |
+ 'Space' | ' ' |
+ 'Sym' |
+ 'Explorer' |
+ 'Envelop' |
+ 'Enter' | '\n' |
+ 'Del' |
+ 'Grave' |
+ 'Minus' | '-' |
+ 'Equals' | '=' |
+ 'LeftBracket' | '(' |
+ 'RightBracket' | ')' |
+ 'Backslash' | '\\' |
+ 'Semicolon' | ';' |
+ 'Apostrophe' | '`' |
+ 'Slash' | '/' |
+ 'At' | '@' |
+ 'Num' |
+ 'HeadsetHook' |
+ 'Focus' |
+ 'Plus' | '+' |
+ 'Menu' |
+ 'Notification' |
+ 'Search' |
+ 'RecentApps' |
+ 'AppSwitch' |
+ 'Assist' |
+ 'Cut' |
+ 'Copy' |
+ 'Paste';
- /**
- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
- * by using the
- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
- * method.
- */
- timeout?: number;
- }): Promise<void>;
+export const _electron: Electron;
+export const _android: Android;
+
+// This is required to not export everything by default. See https://github.com/Microsoft/TypeScript/issues/19545#issuecomment-340490459
+export {};
+
+/**
+ * Playwright has **experimental** support for Android automation. This includes Chrome for Android and Android
+ * WebView.
+ *
+ * *Requirements*
+ * - Android device or AVD Emulator.
+ * - [ADB daemon](https://developer.android.com/studio/command-line/adb) running and authenticated with your device.
+ * Typically running `adb devices` is all you need to do.
+ * - [`Chrome 87`](https://play.google.com/store/apps/details?id=com.android.chrome) or newer installed on the
+ * device
+ * - "Enable command line on non-rooted devices" enabled in `chrome://flags`.
+ *
+ * *Known limitations*
+ * - Raw USB operation is not yet supported, so you need ADB.
+ * - Device needs to be awake to produce screenshots. Enabling "Stay awake" developer mode will help.
+ * - We didn't run all the tests against the device, so not everything works.
+ *
+ * *How to run*
+ *
+ * An example of the Android automation script would be:
+ *
+ * ```js
+ * const { _android: android } = require('playwright');
+ *
+ * (async () => {
+ * // Connect to the device.
+ * const [device] = await android.devices();
+ * console.log(`Model: ${device.model()}`);
+ * console.log(`Serial: ${device.serial()}`);
+ * // Take screenshot of the whole device.
+ * await device.screenshot({ path: 'device.png' });
+ *
+ * {
+ * // --------------------- WebView -----------------------
+ *
+ * // Launch an application with WebView.
+ * await device.shell('am force-stop org.chromium.webview_shell');
+ * await device.shell('am start org.chromium.webview_shell/.WebViewBrowserActivity');
+ * // Get the WebView.
+ * const webview = await device.webView({ pkg: 'org.chromium.webview_shell' });
+ *
+ * // Fill the input box.
+ * await device.fill({
+ * res: 'org.chromium.webview_shell:id/url_field',
+ * }, 'github.com/microsoft/playwright');
+ * await device.press({
+ * res: 'org.chromium.webview_shell:id/url_field',
+ * }, 'Enter');
+ *
+ * // Work with WebView's page as usual.
+ * const page = await webview.page();
+ * await page.waitForNavigation({ url: /.*microsoft\/playwright.*\/ });
+ * console.log(await page.title());
+ * }
+ *
+ * {
+ * // --------------------- Browser -----------------------
+ *
+ * // Launch Chrome browser.
+ * await device.shell('am force-stop com.android.chrome');
+ * const context = await device.launchBrowser();
+ *
+ * // Use BrowserContext as usual.
+ * const page = await context.newPage();
+ * await page.goto('https://webkit.org/');
+ * console.log(await page.evaluate(() => window.location.href));
+ * await page.screenshot({ path: 'page.png' });
+ *
+ * await context.close();
+ * }
+ *
+ * // Close the device.
+ * await device.close();
+ * })();
+ * ```
+ *
+ */
+export interface Android {
/**
- * Taps on the widget defined by `selector`.
- * @param selector Selector to tap on.
+ * This methods attaches Playwright to an existing Android device. Use
+ * [android.launchServer([options])](https://playwright.dev/docs/api/class-android#android-launch-server) to launch a
+ * new Android server instance.
+ * @param wsEndpoint A browser websocket endpoint to connect to.
* @param options
*/
- tap(selector: AndroidSelector, options?: {
- /**
- * Optional duration of the tap in milliseconds.
- */
- duration?: number;
-
+ connect(wsEndpoint: string, options?: {
/**
- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
- * by using the
- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
- * method.
+ * Additional HTTP headers to be sent with web socket connect request. Optional.
*/
- timeout?: number;
- }): Promise<void>;
+ headers?: { [key: string]: string; };
- /**
- * Waits for the specific `selector` to either appear or disappear, depending on the `state`.
- * @param selector Selector to wait for.
- * @param options
- */
- wait(selector: AndroidSelector, options?: {
/**
- * Optional state. Can be either:
- * - default - wait for element to be present.
- * - `'gone'` - wait for element to not be present.
+ * Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
+ * on. Defaults to `0`.
*/
- state?: "gone";
+ slowMo?: number;
/**
- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
- * by using the
- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
- * method.
+ * Maximum time in milliseconds to wait for the connection to be established. Defaults to `30000` (30 seconds). Pass
+ * `0` to disable timeout.
*/
timeout?: number;
- }): Promise<void>;
-
- /**
- * Emitted when the device connection gets closed.
- */
- waitForEvent(event: 'close', optionsOrPredicate?: { predicate?: (androidDevice: AndroidDevice) => boolean | Promise<boolean>, timeout?: number } | ((androidDevice: AndroidDevice) => boolean | Promise<boolean>)): Promise<AndroidDevice>;
-
- /**
- * Emitted when a new WebView instance is detected.
- */
- waitForEvent(event: 'webview', optionsOrPredicate?: { predicate?: (androidWebView: AndroidWebView) => boolean | Promise<boolean>, timeout?: number } | ((androidWebView: AndroidWebView) => boolean | Promise<boolean>)): Promise<AndroidWebView>;
-
+ }): Promise<AndroidDevice>;
/**
- * This method waits until {@link AndroidWebView} matching the `selector` is opened and returns it. If there is
- * already an open {@link AndroidWebView} matching the `selector`, returns immediately.
- * @param selector
+ * Returns the list of detected Android devices.
* @param options
*/
- webView(selector: {
+ devices(options?: {
/**
- * Optional Package identifier.
+ * Optional host to establish ADB server connection. Default to `127.0.0.1`.
*/
- pkg?: string;
+ host?: string;
/**
- * Optional webview socket name.
+ * Prevents automatic playwright driver installation on attach. Assumes that the drivers have been installed already.
*/
- socketName?: string;
- }, options?: {
+ omitDriverInstall?: boolean;
+
/**
- * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
- * by using the
- * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
- * method.
+ * Optional port to establish ADB server connection. Default to `5037`.
*/
- timeout?: number;
- }): Promise<AndroidWebView>;
-
- /**
- * Currently open WebViews.
- */
- webViews(): Array<AndroidWebView>;
-
- input: AndroidInput;
-
- [Symbol.asyncDispose](): Promise<void>;
-}
-
-export interface AndroidInput {
- /**
- * Performs a drag between `from` and `to` points.
- * @param from The start point of the drag.
- * @param to The end point of the drag.
- * @param steps The number of steps in the drag. Each step takes 5 milliseconds to complete.
- */
- drag(from: {
- x: number;
-
- y: number;
- }, to: {
- x: number;
-
- y: number;
- }, steps: number): Promise<void>;
-
- /**
- * Presses the `key`.
- * @param key Key to press.
- */
- press(key: AndroidKey): Promise<void>;
+ port?: number;
+ }): Promise<Array<AndroidDevice>>;
/**
- * Swipes following the path defined by `segments`.
- * @param from The point to start swiping from.
- * @param segments Points following the `from` point in the swipe gesture.
- * @param steps The number of steps for each segment. Each step takes 5 milliseconds to complete, so 100 steps means half a second
- * per each segment.
+ * Launches Playwright Android server that clients can connect to. See the following example:
+ *
+ * **Usage**
+ *
+ * Server Side:
+ *
+ * ```js
+ * const { _android } = require('playwright');
+ *
+ * (async () => {
+ * const browserServer = await _android.launchServer({
+ * // If you have multiple devices connected and want to use a specific one.
+ * // deviceSerialNumber: '<deviceSerialNumber>',
+ * });
+ * const wsEndpoint = browserServer.wsEndpoint();
+ * console.log(wsEndpoint);
+ * })();
+ * ```
+ *
+ * Client Side:
+ *
+ * ```js
+ * const { _android } = require('playwright');
+ *
+ * (async () => {
+ * const device = await _android.connect('<wsEndpoint>');
+ *
+ * console.log(device.model());
+ * console.log(device.serial());
+ * await device.shell('am force-stop com.android.chrome');
+ * const context = await device.launchBrowser();
+ *
+ * const page = await context.newPage();
+ * await page.goto('https://webkit.org/');
+ * console.log(await page.evaluate(() => window.location.href));
+ * await page.screenshot({ path: 'page-chrome-1.png' });
+ *
+ * await context.close();
+ * })();
+ * ```
+ *
+ * @param options
*/
- swipe(from: {
- x: number;
+ launchServer(options?: {
+ /**
+ * Optional host to establish ADB server connection. Default to `127.0.0.1`.
+ */
+ adbHost?: string;
- y: number;
- }, segments: ReadonlyArray<{
- x: number;
+ /**
+ * Optional port to establish ADB server connection. Default to `5037`.
+ */
+ adbPort?: number;
- y: number;
- }>, steps: number): Promise<void>;
+ /**
+ * Optional device serial number to launch the browser on. If not specified, it will throw if multiple devices are
+ * connected.
+ */
+ deviceSerialNumber?: string;
- /**
- * Taps at the specified `point`.
- * @param point The point to tap at.
- */
- tap(point: {
- x: number;
+ /**
+ * Host to use for the web socket. It is optional and if it is omitted, the server will accept connections on the
+ * unspecified IPv6 address (::) when IPv6 is available, or the unspecified IPv4 address (0.0.0.0) otherwise. Consider
+ * hardening it with picking a specific interface.
+ */
+ host?: string;
- y: number;
- }): Promise<void>;
+ /**
+ * Prevents automatic playwright driver installation on attach. Assumes that the drivers have been installed already.
+ */
+ omitDriverInstall?: boolean;
+
+ /**
+ * Port to use for the web socket. Defaults to 0 that picks any available port.
+ */
+ port?: number;
+
+ /**
+ * Path at which to serve the Android Server. For security, this defaults to an unguessable string.
+ *
+ * **NOTE** Any process or web page (including those running in Playwright) with knowledge of the `wsPath` can take
+ * control of the OS user. For this reason, you should use an unguessable token when using this option.
+ */
+ wsPath?: string;
+ }): Promise<BrowserServer>;
/**
- * Types `text` into currently focused widget.
- * @param text Text to type.
+ * This setting will change the default maximum time for all the methods accepting `timeout` option.
+ * @param timeout Maximum time in milliseconds
*/
- type(text: string): Promise<void>;
+ setDefaultTimeout(timeout: number): void;
}
/**
- * {@link AndroidSocket} is a way to communicate with a process launched on the {@link AndroidDevice}. Use
- * [androidDevice.open(command)](https://playwright.dev/docs/api/class-androiddevice#android-device-open) to open a
- * socket.
+ * {@link AndroidDevice} represents a connected device, either real hardware or emulated. Devices can be obtained
+ * using [android.devices([options])](https://playwright.dev/docs/api/class-android#android-devices).
*/
-export interface AndroidSocket {
+export interface AndroidDevice {
/**
- * Emitted when the socket is closed.
+ * Emitted when the device connection gets closed.
*/
- on(event: 'close', listener: () => any): this;
+ on(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;
/**
- * Emitted when data is available to read from the socket.
+ * Emitted when a new WebView instance is detected.
*/
- on(event: 'data', listener: (buffer: Buffer) => any): this;
+ on(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;
/**
* Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.
*/
- once(event: 'close', listener: () => any): this;
+ once(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;
/**
* Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.
*/
- once(event: 'data', listener: (buffer: Buffer) => any): this;
+ once(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;
/**
- * Emitted when the socket is closed.
+ * Emitted when the device connection gets closed.
*/
- addListener(event: 'close', listener: () => any): this;
+ addListener(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;
/**
- * Emitted when data is available to read from the socket.
+ * Emitted when a new WebView instance is detected.
*/
- addListener(event: 'data', listener: (buffer: Buffer) => any): this;
+ addListener(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;
/**
* Removes an event listener added by `on` or `addListener`.
*/
- removeListener(event: 'close', listener: () => any): this;
+ removeListener(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;
/**
* Removes an event listener added by `on` or `addListener`.
*/
- removeListener(event: 'data', listener: (buffer: Buffer) => any): this;
+ removeListener(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;
/**
* Removes an event listener added by `on` or `addListener`.
*/
- off(event: 'close', listener: () => any): this;
+ off(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;
/**
* Removes an event listener added by `on` or `addListener`.
*/
- off(event: 'data', listener: (buffer: Buffer) => any): this;
+ off(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;
/**
- * Emitted when the socket is closed.
+ * Emitted when the device connection gets closed.
*/
- prependListener(event: 'close', listener: () => any): this;
+ prependListener(event: 'close', listener: (androidDevice: AndroidDevice) => any): this;
/**
- * Emitted when data is available to read from the socket.
+ * Emitted when a new WebView instance is detected.
*/
- prependListener(event: 'data', listener: (buffer: Buffer) => any): this;
+ prependListener(event: 'webview', listener: (androidWebView: AndroidWebView) => any): this;
/**
- * Closes the socket.
+ * Disconnects from the device.
*/
close(): Promise<void>;
/**
- * Writes some `data` to the socket.
- * @param data Data to write.
+ * Drags the widget defined by `selector` towards `dest` point.
+ * @param selector Selector to drag.
+ * @param dest Point to drag to.
+ * @param options
*/
- write(data: Buffer): Promise<void>;
+ drag(selector: AndroidSelector, dest: {
+ x: number;
- [Symbol.asyncDispose](): Promise<void>;
-}
+ y: number;
+ }, options?: {
+ /**
+ * Optional speed of the drag in pixels per second.
+ */
+ speed?: number;
-/**
- * {@link AndroidWebView} represents a WebView open on the {@link AndroidDevice}. WebView is usually obtained using
- * [androidDevice.webView(selector[, options])](https://playwright.dev/docs/api/class-androiddevice#android-device-web-view).
- */
-export interface AndroidWebView {
- /**
- * Emitted when the WebView is closed.
- */
- on(event: 'close', listener: () => any): this;
+ /**
+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
+ * by using the
+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
+ * method.
+ */
+ timeout?: number;
+ }): Promise<void>;
/**
- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.
+ * Fills the specific `selector` input box with `text`.
+ * @param selector Selector to fill.
+ * @param text Text to be filled in the input box.
+ * @param options
*/
- once(event: 'close', listener: () => any): this;
+ fill(selector: AndroidSelector, text: string, options?: {
+ /**
+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
+ * by using the
+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
+ * method.
+ */
+ timeout?: number;
+ }): Promise<void>;
/**
- * Emitted when the WebView is closed.
+ * Flings the widget defined by `selector` in the specified `direction`.
+ * @param selector Selector to fling.
+ * @param direction Fling direction.
+ * @param options
*/
- addListener(event: 'close', listener: () => any): this;
+ fling(selector: AndroidSelector, direction: "down"|"up"|"left"|"right", options?: {
+ /**
+ * Optional speed of the fling in pixels per second.
+ */
+ speed?: number;
- /**
- * Removes an event listener added by `on` or `addListener`.
- */
- removeListener(event: 'close', listener: () => any): this;
+ /**
+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
+ * by using the
+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
+ * method.
+ */
+ timeout?: number;
+ }): Promise<void>;
/**
- * Removes an event listener added by `on` or `addListener`.
+ * Returns information about a widget defined by `selector`.
+ * @param selector Selector to return information about.
*/
- off(event: 'close', listener: () => any): this;
+ info(selector: AndroidSelector): Promise<AndroidElementInfo>;
/**
- * Emitted when the WebView is closed.
+ * Installs an apk on the device.
+ * @param file Either a path to the apk file, or apk file content.
+ * @param options
*/
- prependListener(event: 'close', listener: () => any): this;
+ installApk(file: string|Buffer, options?: {
+ /**
+ * Optional arguments to pass to the `shell:cmd package install` call. Defaults to `-r -t -S`.
+ */
+ args?: Array<string>;
+ }): Promise<void>;
/**
- * Connects to the WebView and returns a regular Playwright {@link Page} to interact with.
+ * Launches Chrome browser on the device, and returns its persistent context.
+ * @param options
*/
- page(): Promise<Page>;
+ launchBrowser(options?: {
+ /**
+ * Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.
+ */
+ acceptDownloads?: boolean;
- /**
- * WebView process PID.
- */
- pid(): number;
+ /**
+ * **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality.
+ *
+ * Additional arguments to pass to the browser instance. The list of Chromium flags can be found
+ * [here](https://peter.sh/experiments/chromium-command-line-switches/).
+ */
+ args?: Array<string>;
- /**
- * WebView package identifier.
- */
- pkg(): string;
-}
+ /**
+ * When using [page.goto(url[, options])](https://playwright.dev/docs/api/class-page#page-goto),
+ * [page.route(url, handler[, options])](https://playwright.dev/docs/api/class-page#page-route),
+ * [page.waitForURL(url[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-url),
+ * [page.waitForRequest(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-request),
+ * or
+ * [page.waitForResponse(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-response)
+ * it takes the base URL in consideration by using the
+ * [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL.
+ * Unset by default. Examples:
+ * - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`
+ * - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in
+ * `http://localhost:3000/foo/bar.html`
+ * - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
+ * `http://localhost:3000/bar.html`
+ */
+ baseURL?: string;
+
+ /**
+ * Toggles bypassing page's Content-Security-Policy. Defaults to `false`.
+ */
+ bypassCSP?: boolean;
+
+ /**
+ * 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.
+ * Passing `null` resets emulation to system defaults. Defaults to `'light'`.
+ */
+ colorScheme?: null|"light"|"dark"|"no-preference";
-/**
- * Exposes API that can be used for the Web API testing. This class is used for creating {@link APIRequestContext}
- * instance which in turn can be used for sending web requests. An instance of this class can be obtained via
- * [playwright.request](https://playwright.dev/docs/api/class-playwright#playwright-request). For more information see
- * {@link APIRequestContext}.
- */
-export interface APIRequest {
- /**
- * Creates new instances of {@link APIRequestContext}.
- * @param options
- */
- newContext(options?: {
/**
- * Methods like
- * [apiRequestContext.get(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-get)
- * take the base URL into consideration by using the
- * [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL.
- * Examples:
- * - baseURL: `http://localhost:3000` and sending request to `/bar.html` results in `http://localhost:3000/bar.html`
- * - baseURL: `http://localhost:3000/foo/` and sending request to `./bar.html` results in
- * `http://localhost:3000/foo/bar.html`
- * - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
- * `http://localhost:3000/bar.html`
+ * Optional package name to launch instead of default Chrome for Android.
*/
- baseURL?: string;
+ command?: string;
/**
- * TLS Client Authentication allows the server to request a client certificate and verify it.
- *
- * **Details**
- *
- * An array of client certificates to be used. Each certificate object must have both `certPath` and `keyPath` or a
- * single `pfxPath` to load the client certificate. Optionally, `passphrase` property should be provided if the
- * certficiate is encrypted. The `origin` property should be provided with an exact match to the request origin that
- * the certificate is valid for.
- *
- * **NOTE** Using Client Certificates in combination with Proxy Servers is not supported.
- *
- * **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
- * work by replacing `localhost` with `local.playwright`.
+ * Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about
+ * [emulating devices with device scale factor](https://playwright.dev/docs/emulation#devices).
*/
- clientCertificates?: Array<{
- /**
- * Exact origin that the certificate is valid for. Origin includes `https` protocol, a hostname and optionally a port.
- */
- origin: string;
+ deviceScaleFactor?: number;
- /**
- * Path to the file with the certificate in PEM format.
- */
- certPath?: string;
+ /**
+ * An object containing additional HTTP headers to be sent with every request. Defaults to none.
+ */
+ extraHTTPHeaders?: { [key: string]: string; };
+
+ /**
+ * Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See
+ * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.
+ * Passing `null` resets emulation to system defaults. Defaults to `'none'`.
+ */
+ forcedColors?: null|"active"|"none";
+ geolocation?: {
/**
- * Path to the file with the private key in PEM format.
+ * Latitude between -90 and 90.
*/
- keyPath?: string;
+ latitude: number;
/**
- * Path to the PFX or PKCS12 encoded private key and certificate chain.
+ * Longitude between -180 and 180.
*/
- pfxPath?: string;
+ longitude: number;
/**
- * Passphrase for the private key (PEM or PFX).
+ * Non-negative accuracy value. Defaults to `0`.
*/
- passphrase?: string;
- }>;
+ accuracy?: number;
+ };
/**
- * An object containing additional HTTP headers to be sent with every request. Defaults to none.
+ * Specifies if viewport supports touch events. Defaults to false. Learn more about
+ * [mobile emulation](https://playwright.dev/docs/emulation#devices).
*/
- extraHTTPHeaders?: { [key: string]: string; };
+ hasTouch?: boolean;
/**
* Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
@@ -15652,6 +15563,44 @@ export interface APIRequest {
*/
ignoreHTTPSErrors?: boolean;
+ /**
+ * Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,
+ * so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more
+ * about [mobile emulation](https://playwright.dev/docs/emulation#ismobile).
+ */
+ isMobile?: boolean;
+
+ /**
+ * Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about
+ * [disabling JavaScript](https://playwright.dev/docs/emulation#javascript-enabled).
+ */
+ 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. Defaults to the system default
+ * locale. Learn more about emulation in our [emulation guide](https://playwright.dev/docs/emulation#locale--timezone).
+ */
+ locale?: string;
+
+ /**
+ * Logger sink for Playwright logging.
+ */
+ logger?: Logger;
+
+ /**
+ * Whether to emulate network being offline. Defaults to `false`. Learn more about
+ * [network emulation](https://playwright.dev/docs/emulation#offline).
+ */
+ 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. Defaults to none.
+ */
+ permissions?: Array<string>;
+
/**
* Network proxy settings.
*/
@@ -15660,550 +15609,728 @@ export interface APIRequest {
* 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;
+ server: string;
+
+ /**
+ * Optional comma-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([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for
+ * the HAR to be saved.
+ */
+ recordHar?: {
+ /**
+ * Optional setting to control whether to omit request content from the HAR. Defaults to `false`. Deprecated, use
+ * `content` policy instead.
+ */
+ omitContent?: boolean;
+
+ /**
+ * Optional setting to control resource content management. If `omit` is specified, content is not persisted. If
+ * `attach` is specified, resources are persisted as separate files or entries in the ZIP archive. If `embed` is
+ * specified, content is stored inline the HAR file as per HAR specification. Defaults to `attach` for `.zip` output
+ * files and to `embed` for all other file extensions.
+ */
+ content?: "omit"|"embed"|"attach";
+
+ /**
+ * Path on the filesystem to write the HAR file to. If the file name ends with `.zip`, `content: 'attach'` is used by
+ * default.
+ */
+ path: string;
+
+ /**
+ * When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
+ * cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.
+ */
+ mode?: "full"|"minimal";
+
+ /**
+ * A glob or regex pattern to filter requests that are stored in the HAR. When a `baseURL` via the context options was
+ * provided and the passed URL is a path, it gets merged via the
+ * [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor. Defaults to none.
+ */
+ urlFilter?: string|RegExp;
+ };
+
+ /**
+ * Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded.
+ * Make sure to await
+ * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for
+ * videos to be saved.
+ */
+ 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.
+ * Passing `null` resets emulation to system defaults. Defaults to `'no-preference'`.
+ */
+ reducedMotion?: null|"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;
+ };
+
+ /**
+ * Whether to allow sites to register Service workers. Defaults to `'allow'`.
+ * - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be
+ * registered.
+ * - `'block'`: Playwright will block all registration of Service Workers.
+ */
+ serviceWorkers?: "allow"|"block";
+
+ /**
+ * If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on
+ * selectors that imply single target DOM element will throw when more than one element matches the selector. This
+ * option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See {@link 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. Defaults to the system timezone.
+ */
+ timezoneId?: string;
+
+ /**
+ * Specific user agent to use in this context.
+ */
+ userAgent?: string;
+
+ /**
+ * @deprecated Use `recordVideo` instead.
+ */
+ videoSize?: {
+ /**
+ * Video frame width.
+ */
+ width: number;
/**
- * Optional comma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.
+ * Video frame height.
*/
- bypass?: string;
+ height: number;
+ };
+ /**
+ * @deprecated Use `recordVideo` instead.
+ */
+ videosPath?: string;
+
+ /**
+ * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use `null` to disable the consistent
+ * viewport emulation. Learn more about [viewport emulation](https://playwright.dev/docs/emulation#viewport).
+ *
+ * **NOTE** The `null` value opts out from the default presets, makes viewport depend on the host window size defined
+ * by the operating system. It makes the execution of the tests non-deterministic.
+ */
+ viewport?: null|{
/**
- * Optional username to use if HTTP proxy requires authentication.
+ * page width in pixels.
*/
- username?: string;
+ width: number;
/**
- * Optional password to use if HTTP proxy requires authentication.
+ * page height in pixels.
*/
- password?: string;
+ height: number;
};
+ }): Promise<BrowserContext>;
+ /**
+ * Performs a long tap on the widget defined by `selector`.
+ * @param selector Selector to tap on.
+ * @param options
+ */
+ longTap(selector: AndroidSelector, options?: {
/**
- * 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.
+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
+ * by using the
+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
+ * method.
*/
- 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;
+ timeout?: number;
+ }): Promise<void>;
- localStorage: Array<{
- name: string;
+ /**
+ * Device model.
+ */
+ model(): string;
- value: string;
- }>;
- }>;
- };
+ /**
+ * Launches a process in the shell on the device and returns a socket to communicate with the launched process.
+ * @param command
+ */
+ open(command: string): Promise<AndroidSocket>;
+ /**
+ * Pinches the widget defined by `selector` in the closing direction.
+ * @param selector Selector to pinch close.
+ * @param percent The size of the pinch as a percentage of the widget's size.
+ * @param options
+ */
+ pinchClose(selector: AndroidSelector, percent: number, options?: {
/**
- * Maximum time in milliseconds to wait for the response. Defaults to `30000` (30 seconds). Pass `0` to disable
- * timeout.
+ * Optional speed of the pinch in pixels per second.
*/
- timeout?: number;
+ speed?: number;
/**
- * Specific user agent to use in this context.
+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
+ * by using the
+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
+ * method.
*/
- userAgent?: string;
- }): Promise<APIRequestContext>;
-}
+ timeout?: number;
+ }): Promise<void>;
-/**
- * This API is used for the Web API testing. You can use it to trigger API endpoints, configure micro-services,
- * prepare environment or the service to your e2e test.
- *
- * Each Playwright browser context has associated with it {@link APIRequestContext} instance which shares cookie
- * storage with the browser context and can be accessed via
- * [browserContext.request](https://playwright.dev/docs/api/class-browsercontext#browser-context-request) or
- * [page.request](https://playwright.dev/docs/api/class-page#page-request). It is also possible to create a new
- * APIRequestContext instance manually by calling
- * [apiRequest.newContext([options])](https://playwright.dev/docs/api/class-apirequest#api-request-new-context).
- *
- * **Cookie management**
- *
- * {@link APIRequestContext} returned by
- * [browserContext.request](https://playwright.dev/docs/api/class-browsercontext#browser-context-request) and
- * [page.request](https://playwright.dev/docs/api/class-page#page-request) shares cookie storage with the
- * corresponding {@link BrowserContext}. Each API request will have `Cookie` header populated with the values from the
- * browser context. If the API response contains `Set-Cookie` header it will automatically update {@link
- * BrowserContext} cookies and requests made from the page will pick them up. This means that if you log in using this
- * API, your e2e test will be logged in and vice versa.
- *
- * If you want API requests to not interfere with the browser cookies you should create a new {@link
- * APIRequestContext} by calling
- * [apiRequest.newContext([options])](https://playwright.dev/docs/api/class-apirequest#api-request-new-context). Such
- * `APIRequestContext` object will have its own isolated cookie storage.
- */
-export interface APIRequestContext {
/**
- * Sends HTTP(S) [DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE) request and returns its
- * response. The method will populate request cookies from the context and update context cookies from the response.
- * The method will automatically follow redirects.
- * @param url Target URL.
+ * Pinches the widget defined by `selector` in the open direction.
+ * @param selector Selector to pinch open.
+ * @param percent The size of the pinch as a percentage of the widget's size.
* @param options
*/
- delete(url: string, options?: {
- /**
- * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
- * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
- * header will be set to `application/octet-stream` if not explicitly set.
- */
- data?: string|Buffer|Serializable;
-
+ pinchOpen(selector: AndroidSelector, percent: number, options?: {
/**
- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
- * codes.
+ * Optional speed of the pinch in pixels per second.
*/
- failOnStatusCode?: boolean;
+ speed?: 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.
+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
+ * by using the
+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
+ * method.
*/
- form?: { [key: string]: string|number|boolean; };
+ timeout?: number;
+ }): Promise<void>;
+ /**
+ * Presses the specific `key` in the widget defined by `selector`.
+ * @param selector Selector to press the key in.
+ * @param key The key to press.
+ * @param options
+ */
+ press(selector: AndroidSelector, key: AndroidKey, options?: {
/**
- * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
- * it.
+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
+ * by using the
+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
+ * method.
*/
- headers?: { [key: string]: string; };
+ timeout?: number;
+ }): Promise<void>;
+ /**
+ * Copies a file to the device.
+ * @param file Either a path to the file, or file content.
+ * @param path Path to the file on the device.
+ * @param options
+ */
+ push(file: string|Buffer, path: string, options?: {
/**
- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
+ * Optional file mode, defaults to `644` (`rw-r--r--`).
*/
- ignoreHTTPSErrors?: boolean;
+ mode?: number;
+ }): Promise<void>;
+ /**
+ * Returns the buffer with the captured screenshot of the device.
+ * @param options
+ */
+ screenshot(options?: {
/**
- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.
+ * The file path to save the image to. If `path` is a relative path, then it is resolved relative to the current
+ * working directory. If no path is provided, the image won't be saved to the disk.
*/
- maxRedirects?: number;
+ path?: string;
+ }): Promise<Buffer>;
+ /**
+ * Scrolls the widget defined by `selector` in the specified `direction`.
+ * @param selector Selector to scroll.
+ * @param direction Scroll direction.
+ * @param percent Distance to scroll as a percentage of the widget's size.
+ * @param options
+ */
+ scroll(selector: AndroidSelector, direction: "down"|"up"|"left"|"right", percent: number, options?: {
/**
- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
+ * Optional speed of the scroll in pixels per second.
*/
- maxRetries?: number;
+ speed?: number;
/**
- * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
- * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
- * explicitly provided. File values can be passed either as
- * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file
- * name, mime-type and its content.
+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
+ * by using the
+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
+ * method.
*/
- multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{
- /**
- * File name
- */
- name: string;
+ timeout?: number;
+ }): Promise<void>;
- /**
- * File type
- */
- mimeType: string;
+ /**
+ * Device serial number.
+ */
+ serial(): string;
- /**
- * File content
- */
- buffer: Buffer;
- }; };
+ /**
+ * This setting will change the default maximum time for all the methods accepting `timeout` option.
+ * @param timeout Maximum time in milliseconds
+ */
+ setDefaultTimeout(timeout: number): void;
+
+ /**
+ * Executes a shell command on the device and returns its output.
+ * @param command Shell command to execute.
+ */
+ shell(command: string): Promise<Buffer>;
+ /**
+ * Swipes the widget defined by `selector` in the specified `direction`.
+ * @param selector Selector to swipe.
+ * @param direction Swipe direction.
+ * @param percent Distance to swipe as a percentage of the widget's size.
+ * @param options
+ */
+ swipe(selector: AndroidSelector, direction: "down"|"up"|"left"|"right", percent: number, options?: {
/**
- * Query parameters to be sent with the URL.
+ * Optional speed of the swipe in pixels per second.
*/
- params?: { [key: string]: string|number|boolean; };
+ speed?: number;
/**
- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
+ * by using the
+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
+ * method.
*/
timeout?: number;
- }): Promise<APIResponse>;
+ }): Promise<void>;
/**
- * All responses returned by
- * [apiRequestContext.get(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-get)
- * and similar methods are stored in the memory, so that you can later call
- * [apiResponse.body()](https://playwright.dev/docs/api/class-apiresponse#api-response-body).This method discards all
- * its resources, calling any method on disposed {@link APIRequestContext} will throw an exception.
+ * Taps on the widget defined by `selector`.
+ * @param selector Selector to tap on.
* @param options
*/
- dispose(options?: {
+ tap(selector: AndroidSelector, options?: {
/**
- * The reason to be reported to the operations interrupted by the context disposal.
+ * Optional duration of the tap in milliseconds.
*/
- reason?: string;
+ duration?: number;
+
+ /**
+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
+ * by using the
+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
+ * method.
+ */
+ timeout?: number;
}): Promise<void>;
/**
- * Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and
- * update context cookies from the response. The method will automatically follow redirects.
- *
- * **Usage**
- *
- * JSON objects can be passed directly to the request:
- *
- * ```js
- * await request.fetch('https://example.com/api/createBook', {
- * method: 'post',
- * data: {
- * title: 'Book Title',
- * author: 'John Doe',
- * }
- * });
- * ```
- *
- * The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data`
- * encoding. Use [FormData] to construct request body and pass it to the request as `multipart` parameter:
- *
- * ```js
- * const form = new FormData();
- * form.set('name', 'John');
- * form.append('name', 'Doe');
- * // Send two file fields with the same name.
- * form.append('file', new File(['console.log(2024);'], 'f1.js', { type: 'text/javascript' }));
- * form.append('file', new File(['hello'], 'f2.txt', { type: 'text/plain' }));
- * await request.fetch('https://example.com/api/uploadForm', {
- * multipart: form
- * });
- * ```
- *
- * @param urlOrRequest Target URL or Request to get all parameters from.
+ * Waits for the specific `selector` to either appear or disappear, depending on the `state`.
+ * @param selector Selector to wait for.
* @param options
*/
- fetch(urlOrRequest: string|Request, options?: {
+ wait(selector: AndroidSelector, 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.
+ * Optional state. Can be either:
+ * - default - wait for element to be present.
+ * - `'gone'` - wait for element to not be present.
*/
- data?: string|Buffer|Serializable;
+ state?: "gone";
/**
- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
- * codes.
+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
+ * by using the
+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
+ * method.
*/
- failOnStatusCode?: boolean;
+ timeout?: number;
+ }): Promise<void>;
- /**
- * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
- * as this request body. If this parameter is specified `content-type` header will be set to
- * `application/x-www-form-urlencoded` unless explicitly provided.
- */
- form?: { [key: string]: string|number|boolean; };
+ /**
+ * Emitted when the device connection gets closed.
+ */
+ waitForEvent(event: 'close', optionsOrPredicate?: { predicate?: (androidDevice: AndroidDevice) => boolean | Promise<boolean>, timeout?: number } | ((androidDevice: AndroidDevice) => boolean | Promise<boolean>)): Promise<AndroidDevice>;
- /**
- * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
- * it.
- */
- headers?: { [key: string]: string; };
+ /**
+ * Emitted when a new WebView instance is detected.
+ */
+ waitForEvent(event: 'webview', optionsOrPredicate?: { predicate?: (androidWebView: AndroidWebView) => boolean | Promise<boolean>, timeout?: number } | ((androidWebView: AndroidWebView) => boolean | Promise<boolean>)): Promise<AndroidWebView>;
- /**
- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
- */
- ignoreHTTPSErrors?: boolean;
+ /**
+ * This method waits until {@link AndroidWebView} matching the `selector` is opened and returns it. If there is
+ * already an open {@link AndroidWebView} matching the `selector`, returns immediately.
+ * @param selector
+ * @param options
+ */
+ webView(selector: {
/**
- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.
+ * Optional Package identifier.
*/
- maxRedirects?: number;
+ pkg?: string;
/**
- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
+ * Optional webview socket name.
*/
- maxRetries?: number;
-
+ socketName?: string;
+ }, options?: {
/**
- * If set changes the fetch method (e.g. [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) or
- * [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)). If not specified, GET method is used.
+ * Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed
+ * by using the
+ * [androidDevice.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-androiddevice#android-device-set-default-timeout)
+ * method.
*/
- method?: string;
+ timeout?: number;
+ }): Promise<AndroidWebView>;
- /**
- * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
- * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
- * explicitly provided. File values can be passed either as
- * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file
- * name, mime-type and its content.
- */
- multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{
- /**
- * File name
- */
- name: string;
+ /**
+ * Currently open WebViews.
+ */
+ webViews(): Array<AndroidWebView>;
- /**
- * File type
- */
- mimeType: string;
+ input: AndroidInput;
+
+ [Symbol.asyncDispose](): Promise<void>;
+}
+
+export interface AndroidInput {
+ /**
+ * Performs a drag between `from` and `to` points.
+ * @param from The start point of the drag.
+ * @param to The end point of the drag.
+ * @param steps The number of steps in the drag. Each step takes 5 milliseconds to complete.
+ */
+ drag(from: {
+ x: number;
+
+ y: number;
+ }, to: {
+ x: number;
+
+ y: number;
+ }, steps: number): Promise<void>;
+
+ /**
+ * Presses the `key`.
+ * @param key Key to press.
+ */
+ press(key: AndroidKey): Promise<void>;
+
+ /**
+ * Swipes following the path defined by `segments`.
+ * @param from The point to start swiping from.
+ * @param segments Points following the `from` point in the swipe gesture.
+ * @param steps The number of steps for each segment. Each step takes 5 milliseconds to complete, so 100 steps means half a second
+ * per each segment.
+ */
+ swipe(from: {
+ x: number;
+
+ y: number;
+ }, segments: ReadonlyArray<{
+ x: number;
+
+ y: number;
+ }>, steps: number): Promise<void>;
+
+ /**
+ * Taps at the specified `point`.
+ * @param point The point to tap at.
+ */
+ tap(point: {
+ x: number;
+
+ y: number;
+ }): Promise<void>;
+
+ /**
+ * Types `text` into currently focused widget.
+ * @param text Text to type.
+ */
+ type(text: string): Promise<void>;
+}
+
+/**
+ * {@link AndroidSocket} is a way to communicate with a process launched on the {@link AndroidDevice}. Use
+ * [androidDevice.open(command)](https://playwright.dev/docs/api/class-androiddevice#android-device-open) to open a
+ * socket.
+ */
+export interface AndroidSocket {
+ /**
+ * Emitted when the socket is closed.
+ */
+ on(event: 'close', listener: () => any): this;
+
+ /**
+ * Emitted when data is available to read from the socket.
+ */
+ on(event: 'data', listener: (buffer: Buffer) => any): this;
+
+ /**
+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.
+ */
+ once(event: 'close', listener: () => any): this;
+
+ /**
+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.
+ */
+ once(event: 'data', listener: (buffer: Buffer) => any): this;
- /**
- * File content
- */
- buffer: Buffer;
- }; };
+ /**
+ * Emitted when the socket is closed.
+ */
+ addListener(event: 'close', listener: () => any): this;
- /**
- * Query parameters to be sent with the URL.
- */
- params?: { [key: string]: string|number|boolean; };
+ /**
+ * Emitted when data is available to read from the socket.
+ */
+ addListener(event: 'data', listener: (buffer: Buffer) => any): this;
- /**
- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
- */
- timeout?: number;
- }): Promise<APIResponse>;
+ /**
+ * Removes an event listener added by `on` or `addListener`.
+ */
+ removeListener(event: 'close', listener: () => any): this;
/**
- * Sends HTTP(S) [GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET) request and returns its
- * response. The method will populate request cookies from the context and update context cookies from the response.
- * The method will automatically follow redirects.
- *
- * **Usage**
- *
- * Request parameters can be configured with `params` option, they will be serialized into the URL search parameters:
- *
- * ```js
- * await request.get('https://example.com/api/getText', {
- * params: {
- * 'isbn': '1234',
- * 'page': 23,
- * }
- * });
- * ```
- *
- * @param url Target URL.
- * @param options
+ * Removes an event listener added by `on` or `addListener`.
*/
- get(url: string, options?: {
- /**
- * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
- * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
- * header will be set to `application/octet-stream` if not explicitly set.
- */
- data?: string|Buffer|Serializable;
+ removeListener(event: 'data', listener: (buffer: Buffer) => any): this;
- /**
- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
- * codes.
- */
- failOnStatusCode?: boolean;
+ /**
+ * Removes an event listener added by `on` or `addListener`.
+ */
+ off(event: 'close', listener: () => any): 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; };
+ /**
+ * Removes an event listener added by `on` or `addListener`.
+ */
+ off(event: 'data', listener: (buffer: Buffer) => any): this;
- /**
- * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
- * it.
- */
- headers?: { [key: string]: string; };
+ /**
+ * Emitted when the socket is closed.
+ */
+ prependListener(event: 'close', listener: () => any): this;
- /**
- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
- */
- ignoreHTTPSErrors?: boolean;
+ /**
+ * Emitted when data is available to read from the socket.
+ */
+ prependListener(event: 'data', listener: (buffer: Buffer) => any): this;
- /**
- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.
- */
- maxRedirects?: number;
+ /**
+ * Closes the socket.
+ */
+ close(): Promise<void>;
- /**
- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
- */
- maxRetries?: number;
+ /**
+ * Writes some `data` to the socket.
+ * @param data Data to write.
+ */
+ write(data: Buffer): Promise<void>;
- /**
- * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
- * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
- * explicitly provided. File values can be passed either as
- * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file
- * name, mime-type and its content.
- */
- multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{
- /**
- * File name
- */
- name: string;
+ [Symbol.asyncDispose](): Promise<void>;
+}
- /**
- * File type
- */
- mimeType: string;
+/**
+ * {@link AndroidWebView} represents a WebView open on the {@link AndroidDevice}. WebView is usually obtained using
+ * [androidDevice.webView(selector[, options])](https://playwright.dev/docs/api/class-androiddevice#android-device-web-view).
+ */
+export interface AndroidWebView {
+ /**
+ * Emitted when the WebView is closed.
+ */
+ on(event: 'close', listener: () => any): this;
- /**
- * File content
- */
- buffer: Buffer;
- }; };
+ /**
+ * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.
+ */
+ once(event: 'close', listener: () => any): this;
- /**
- * Query parameters to be sent with the URL.
- */
- params?: { [key: string]: string|number|boolean; };
+ /**
+ * Emitted when the WebView is closed.
+ */
+ addListener(event: 'close', listener: () => any): this;
- /**
- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
- */
- timeout?: number;
- }): Promise<APIResponse>;
+ /**
+ * Removes an event listener added by `on` or `addListener`.
+ */
+ removeListener(event: 'close', listener: () => any): this;
/**
- * Sends HTTP(S) [HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD) request and returns its
- * response. The method will populate request cookies from the context and update context cookies from the response.
- * The method will automatically follow redirects.
- * @param url Target URL.
- * @param options
+ * Removes an event listener added by `on` or `addListener`.
*/
- head(url: string, options?: {
- /**
- * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
- * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
- * header will be set to `application/octet-stream` if not explicitly set.
- */
- data?: string|Buffer|Serializable;
+ off(event: 'close', listener: () => any): 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 WebView is closed.
+ */
+ prependListener(event: 'close', listener: () => any): 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; };
+ /**
+ * Connects to the WebView and returns a regular Playwright {@link Page} to interact with.
+ */
+ page(): Promise<Page>;
- /**
- * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
- * it.
- */
- headers?: { [key: string]: string; };
+ /**
+ * WebView process PID.
+ */
+ pid(): number;
- /**
- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
- */
- ignoreHTTPSErrors?: boolean;
+ /**
+ * WebView package identifier.
+ */
+ pkg(): string;
+}
+/**
+ * Exposes API that can be used for the Web API testing. This class is used for creating {@link APIRequestContext}
+ * instance which in turn can be used for sending web requests. An instance of this class can be obtained via
+ * [playwright.request](https://playwright.dev/docs/api/class-playwright#playwright-request). For more information see
+ * {@link APIRequestContext}.
+ */
+export interface APIRequest {
+ /**
+ * Creates new instances of {@link APIRequestContext}.
+ * @param options
+ */
+ newContext(options?: {
/**
- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.
+ * Methods like
+ * [apiRequestContext.get(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-get)
+ * take the base URL into consideration by using the
+ * [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL.
+ * Examples:
+ * - baseURL: `http://localhost:3000` and sending request to `/bar.html` results in `http://localhost:3000/bar.html`
+ * - baseURL: `http://localhost:3000/foo/` and sending request to `./bar.html` results in
+ * `http://localhost:3000/foo/bar.html`
+ * - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
+ * `http://localhost:3000/bar.html`
*/
- maxRedirects?: number;
+ baseURL?: string;
/**
- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
+ * TLS Client Authentication allows the server to request a client certificate and verify it.
+ *
+ * **Details**
+ *
+ * An array of client certificates to be used. Each certificate object must have both `certPath` and `keyPath` or a
+ * single `pfxPath` to load the client certificate. Optionally, `passphrase` property should be provided if the
+ * certficiate is encrypted. The `origin` property should be provided with an exact match to the request origin that
+ * the certificate is valid for.
+ *
+ * **NOTE** Using Client Certificates in combination with Proxy Servers is not supported.
+ *
+ * **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
+ * work by replacing `localhost` with `local.playwright`.
*/
- maxRetries?: number;
+ clientCertificates?: Array<{
+ /**
+ * Exact origin that the certificate is valid for. Origin includes `https` protocol, a hostname and optionally a port.
+ */
+ origin: string;
- /**
- * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
- * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
- * explicitly provided. File values can be passed either as
- * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file
- * name, mime-type and its content.
- */
- multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{
/**
- * File name
+ * Path to the file with the certificate in PEM format.
*/
- name: string;
+ certPath?: string;
/**
- * File type
+ * Path to the file with the private key in PEM format.
*/
- mimeType: string;
+ keyPath?: string;
/**
- * File content
+ * Path to the PFX or PKCS12 encoded private key and certificate chain.
*/
- buffer: Buffer;
- }; };
+ pfxPath?: string;
- /**
- * Query parameters to be sent with the URL.
- */
- params?: { [key: string]: string|number|boolean; };
+ /**
+ * Passphrase for the private key (PEM or PFX).
+ */
+ passphrase?: string;
+ }>;
/**
- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
+ * An object containing additional HTTP headers to be sent with every request. Defaults to none.
*/
- timeout?: number;
- }): Promise<APIResponse>;
+ extraHTTPHeaders?: { [key: string]: string; };
- /**
- * Sends HTTP(S) [PATCH](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) request and returns its
- * response. The method will populate request cookies from the context and update context cookies from the response.
- * The method will automatically follow redirects.
- * @param url Target URL.
- * @param options
- */
- patch(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.
+ * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
+ * origin is specified, the username and password are sent to any servers upon unauthorized responses.
*/
- data?: string|Buffer|Serializable;
+ httpCredentials?: {
+ username: string;
- /**
- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
- * codes.
- */
- failOnStatusCode?: boolean;
+ password: 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.
- */
- form?: { [key: string]: string|number|boolean; };
+ /**
+ * Restrain sending http credentials on specific origin (scheme://host:port).
+ */
+ origin?: string;
- /**
- * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
- * it.
- */
- headers?: { [key: string]: string; };
+ /**
+ * This option only applies to the requests sent from corresponding {@link APIRequestContext} and does not affect
+ * requests sent from the browser. `'always'` - `Authorization` header with basic authentication credentials will be
+ * sent with the each API request. `'unauthorized` - the credentials are only sent when 401 (Unauthorized) response
+ * with `WWW-Authenticate` header is received. Defaults to `'unauthorized'`.
+ */
+ send?: "unauthorized"|"always";
+ };
/**
* Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
@@ -16211,188 +16338,124 @@ export interface APIRequestContext {
ignoreHTTPSErrors?: boolean;
/**
- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.
- */
- maxRedirects?: number;
-
- /**
- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
- */
- maxRetries?: number;
-
- /**
- * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
- * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
- * explicitly provided. File values can be passed either as
- * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file
- * name, mime-type and its content.
+ * Network proxy settings.
*/
- multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{
+ proxy?: {
/**
- * File name
+ * 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.
*/
- name: string;
+ server: string;
/**
- * File type
+ * Optional comma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.
*/
- mimeType: string;
+ bypass?: string;
/**
- * File content
+ * Optional username to use if HTTP proxy requires authentication.
*/
- buffer: Buffer;
- }; };
-
- /**
- * Query parameters to be sent with the URL.
- */
- params?: { [key: string]: string|number|boolean; };
+ username?: string;
- /**
- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
- */
- timeout?: number;
- }): Promise<APIResponse>;
+ /**
+ * Optional password to use if HTTP proxy requires authentication.
+ */
+ password?: string;
+ };
- /**
- * Sends HTTP(S) [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) request and returns its
- * response. The method will populate request cookies from the context and update context cookies from the response.
- * The method will automatically follow redirects.
- *
- * **Usage**
- *
- * JSON objects can be passed directly to the request:
- *
- * ```js
- * await request.post('https://example.com/api/createBook', {
- * data: {
- * title: 'Book Title',
- * author: 'John Doe',
- * }
- * });
- * ```
- *
- * To send form data to the server use `form` option. Its value will be encoded into the request body with
- * `application/x-www-form-urlencoded` encoding (see below how to use `multipart/form-data` form encoding to send
- * files):
- *
- * ```js
- * await request.post('https://example.com/api/findBook', {
- * form: {
- * title: 'Book Title',
- * author: 'John Doe',
- * }
- * });
- * ```
- *
- * The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data`
- * encoding. Use [FormData] to construct request body and pass it to the request as `multipart` parameter:
- *
- * ```js
- * const form = new FormData();
- * form.set('name', 'John');
- * form.append('name', 'Doe');
- * // Send two file fields with the same name.
- * form.append('file', new File(['console.log(2024);'], 'f1.js', { type: 'text/javascript' }));
- * form.append('file', new File(['hello'], 'f2.txt', { type: 'text/plain' }));
- * await request.post('https://example.com/api/uploadForm', {
- * multipart: form
- * });
- * ```
- *
- * @param url Target URL.
- * @param options
- */
- post(url: string, options?: {
/**
- * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
- * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
- * header will be set to `application/octet-stream` if not explicitly set.
+ * 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.
*/
- data?: string|Buffer|Serializable;
+ storageState?: string|{
+ cookies: Array<{
+ name: string;
- /**
- * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
- * codes.
- */
- failOnStatusCode?: boolean;
+ value: 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.
- */
- form?: { [key: string]: string|number|boolean; };
+ domain: string;
- /**
- * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
- * it.
- */
- headers?: { [key: string]: string; };
+ path: string;
- /**
- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
- */
- ignoreHTTPSErrors?: boolean;
+ /**
+ * Unix time in seconds.
+ */
+ expires: number;
- /**
- * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
- * exceeded. Defaults to `20`. Pass `0` to not follow redirects.
- */
- maxRedirects?: number;
+ httpOnly: boolean;
- /**
- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
- */
- maxRetries?: number;
+ secure: 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?: FormData|{ [key: string]: string|number|boolean|ReadStream|{
- /**
- * File name
- */
- name: string;
+ sameSite: "Strict"|"Lax"|"None";
+ }>;
- /**
- * File type
- */
- mimeType: string;
+ origins: Array<{
+ origin: string;
- /**
- * File content
- */
- buffer: Buffer;
- }; };
+ localStorage: Array<{
+ name: string;
+
+ value: string;
+ }>;
+ }>;
+ };
/**
- * Query parameters to be sent with the URL.
+ * Maximum time in milliseconds to wait for the response. Defaults to `30000` (30 seconds). Pass `0` to disable
+ * timeout.
*/
- params?: { [key: string]: string|number|boolean; };
+ timeout?: number;
/**
- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
+ * Specific user agent to use in this context.
*/
- timeout?: number;
- }): Promise<APIResponse>;
+ userAgent?: string;
+ }): Promise<APIRequestContext>;
+}
+/**
+ * This API is used for the Web API testing. You can use it to trigger API endpoints, configure micro-services,
+ * prepare environment or the service to your e2e test.
+ *
+ * Each Playwright browser context has associated with it {@link APIRequestContext} instance which shares cookie
+ * storage with the browser context and can be accessed via
+ * [browserContext.request](https://playwright.dev/docs/api/class-browsercontext#browser-context-request) or
+ * [page.request](https://playwright.dev/docs/api/class-page#page-request). It is also possible to create a new
+ * APIRequestContext instance manually by calling
+ * [apiRequest.newContext([options])](https://playwright.dev/docs/api/class-apirequest#api-request-new-context).
+ *
+ * **Cookie management**
+ *
+ * {@link APIRequestContext} returned by
+ * [browserContext.request](https://playwright.dev/docs/api/class-browsercontext#browser-context-request) and
+ * [page.request](https://playwright.dev/docs/api/class-page#page-request) shares cookie storage with the
+ * corresponding {@link BrowserContext}. Each API request will have `Cookie` header populated with the values from the
+ * browser context. If the API response contains `Set-Cookie` header it will automatically update {@link
+ * BrowserContext} cookies and requests made from the page will pick them up. This means that if you log in using this
+ * API, your e2e test will be logged in and vice versa.
+ *
+ * If you want API requests to not interfere with the browser cookies you should create a new {@link
+ * APIRequestContext} by calling
+ * [apiRequest.newContext([options])](https://playwright.dev/docs/api/class-apirequest#api-request-new-context). Such
+ * `APIRequestContext` object will have its own isolated cookie storage.
+ */
+export interface APIRequestContext {
/**
- * Sends HTTP(S) [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) request and returns its
+ * Sends HTTP(S) [DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE) request and returns its
* response. The method will populate request cookies from the context and update context cookies from the response.
* The method will automatically follow redirects.
* @param url Target URL.
* @param options
*/
- put(url: string, options?: {
+ delete(url: string, options?: {
/**
* Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
* and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
@@ -16427,812 +16490,787 @@ export interface APIRequestContext {
/**
* Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
* exceeded. Defaults to `20`. Pass `0` to not follow redirects.
- */
- maxRedirects?: number;
-
- /**
- * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
- * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
- */
- maxRetries?: number;
-
- /**
- * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
- * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
- * explicitly provided. File values can be passed either as
- * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file
- * name, mime-type and its content.
- */
- multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{
- /**
- * File name
- */
- name: string;
-
- /**
- * File type
- */
- mimeType: string;
-
- /**
- * File content
- */
- buffer: Buffer;
- }; };
-
- /**
- * Query parameters to be sent with the URL.
- */
- params?: { [key: string]: string|number|boolean; };
-
- /**
- * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
- */
- timeout?: number;
- }): Promise<APIResponse>;
-
- /**
- * Returns storage state for this request context, contains current cookies and local storage snapshot if it was
- * passed to the constructor.
- * @param options
- */
- 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;
- }>;
- }>;
- }>;
-
- [Symbol.asyncDispose](): Promise<void>;
-}
-
-/**
- * {@link APIResponse} class represents responses returned by
- * [apiRequestContext.get(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-get)
- * and similar methods.
- */
-export interface APIResponse {
- /**
- * Returns the buffer with response body.
- */
- body(): Promise<Buffer>;
-
- /**
- * Disposes the body of this response. If not called then the body will stay in memory until the context closes.
- */
- dispose(): Promise<void>;
-
- /**
- * An object with all the response HTTP headers associated with this response.
- */
- headers(): { [key: string]: string; };
-
- /**
- * 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.
- */
- name: string;
-
- /**
- * Value of the header.
- */
- 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;
-
- [Symbol.asyncDispose](): Promise<void>;
-}
-
-/**
- * - 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 {@link Browser} to create a {@link 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();
- * })();
- * ```
- *
- */
-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([options])](https://playwright.dev/docs/api/class-browser#browser-close) method was called.
- */
- on(event: 'disconnected', listener: (browser: Browser) => any): this;
-
- /**
- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.
- */
- once(event: 'disconnected', listener: (browser: Browser) => any): this;
+ */
+ maxRedirects?: number;
- /**
- * 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([options])](https://playwright.dev/docs/api/class-browser#browser-close) method was called.
- */
- addListener(event: 'disconnected', listener: (browser: Browser) => any): this;
+ /**
+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
+ */
+ maxRetries?: number;
- /**
- * Removes an event listener added by `on` or `addListener`.
- */
- removeListener(event: 'disconnected', listener: (browser: Browser) => any): this;
+ /**
+ * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
+ * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
+ * explicitly provided. File values can be passed either as
+ * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file
+ * name, mime-type and its content.
+ */
+ multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{
+ /**
+ * File name
+ */
+ name: string;
- /**
- * Removes an event listener added by `on` or `addListener`.
- */
- off(event: 'disconnected', listener: (browser: Browser) => any): this;
+ /**
+ * File type
+ */
+ mimeType: string;
- /**
- * 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([options])](https://playwright.dev/docs/api/class-browser#browser-close) method was called.
- */
- prependListener(event: 'disconnected', listener: (browser: Browser) => any): this;
+ /**
+ * File content
+ */
+ buffer: Buffer;
+ }; };
- /**
- * Get the browser type (chromium, firefox or webkit) that the browser belongs to.
- */
- browserType(): BrowserType;
+ /**
+ * Query parameters to be sent with the URL.
+ */
+ params?: { [key: string]: string|number|boolean; };
+
+ /**
+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
+ */
+ timeout?: number;
+ }): Promise<APIResponse>;
/**
- * 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.
- *
- * **NOTE** This is similar to force quitting the browser. Therefore, you should call
- * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) on
- * any {@link BrowserContext}'s you explicitly created earlier with
- * [browser.newContext([options])](https://playwright.dev/docs/api/class-browser#browser-new-context) **before**
- * calling [browser.close([options])](https://playwright.dev/docs/api/class-browser#browser-close).
- *
- * The {@link Browser} object itself is considered to be disposed and cannot be used anymore.
+ * All responses returned by
+ * [apiRequestContext.get(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-get)
+ * and similar methods are stored in the memory, so that you can later call
+ * [apiResponse.body()](https://playwright.dev/docs/api/class-apiresponse#api-response-body).This method discards all
+ * its resources, calling any method on disposed {@link APIRequestContext} will throw an exception.
* @param options
*/
- close(options?: {
+ dispose(options?: {
/**
- * The reason to be reported to the operations interrupted by the browser closure.
+ * The reason to be reported to the operations interrupted by the context disposal.
*/
reason?: string;
}): Promise<void>;
/**
- * Returns an array of all open browser contexts. In a newly created browser, this will return zero browser contexts.
+ * Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and
+ * update context cookies from the response. The method will automatically follow redirects.
*
* **Usage**
*
+ * JSON objects can be passed directly to the request:
+ *
* ```js
- * const browser = await pw.webkit.launch();
- * console.log(browser.contexts().length); // prints `0`
+ * await request.fetch('https://example.com/api/createBook', {
+ * method: 'post',
+ * data: {
+ * title: 'Book Title',
+ * author: 'John Doe',
+ * }
+ * });
+ * ```
*
- * const context = await browser.newContext();
- * console.log(browser.contexts().length); // prints `1`
+ * The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data`
+ * encoding. Use [FormData] to construct request body and pass it to the request as `multipart` parameter:
+ *
+ * ```js
+ * const form = new FormData();
+ * form.set('name', 'John');
+ * form.append('name', 'Doe');
+ * // Send two file fields with the same name.
+ * form.append('file', new File(['console.log(2024);'], 'f1.js', { type: 'text/javascript' }));
+ * form.append('file', new File(['hello'], 'f2.txt', { type: 'text/plain' }));
+ * await request.fetch('https://example.com/api/uploadForm', {
+ * multipart: form
+ * });
* ```
*
+ * @param urlOrRequest Target URL or Request to get all parameters from.
+ * @param options
*/
- contexts(): Array<BrowserContext>;
+ 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;
- /**
- * Indicates that the browser is connected.
- */
- isConnected(): boolean;
+ /**
+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
+ * codes.
+ */
+ failOnStatusCode?: boolean;
- /**
- * **NOTE** CDP Sessions are only supported on Chromium-based browsers.
- *
- * Returns the newly created browser session.
- */
- newBrowserCDPSession(): Promise<CDPSession>;
+ /**
+ * 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. These headers will apply to the fetched request as well as any redirects initiated by
+ * it.
+ */
+ headers?: { [key: string]: string; };
+
+ /**
+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
+ */
+ ignoreHTTPSErrors?: boolean;
+
+ /**
+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.
+ */
+ maxRedirects?: number;
+
+ /**
+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
+ */
+ maxRetries?: number;
+
+ /**
+ * If set changes the fetch method (e.g. [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) or
+ * [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)). If not specified, GET method is used.
+ */
+ method?: string;
+
+ /**
+ * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
+ * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
+ * explicitly provided. File values can be passed either as
+ * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file
+ * name, mime-type and its content.
+ */
+ multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{
+ /**
+ * File name
+ */
+ name: string;
+
+ /**
+ * File type
+ */
+ mimeType: string;
+
+ /**
+ * File content
+ */
+ buffer: Buffer;
+ }; };
+
+ /**
+ * Query parameters to be sent with the URL.
+ */
+ params?: { [key: string]: string|number|boolean; };
+
+ /**
+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
+ */
+ timeout?: number;
+ }): Promise<APIResponse>;
/**
- * Creates a new browser context. It won't share cookies/cache with other browser contexts.
- *
- * **NOTE** If directly using this method to create {@link BrowserContext}s, it is best practice to explicitly close
- * the returned context via
- * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) when
- * your code is done with the {@link BrowserContext}, and before calling
- * [browser.close([options])](https://playwright.dev/docs/api/class-browser#browser-close). This will ensure the
- * `context` is closed gracefully and any artifacts—like HARs and videos—are fully flushed and saved.
+ * Sends HTTP(S) [GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET) request and returns its
+ * response. The method will populate request cookies from the context and update context cookies from the response.
+ * The method will automatically follow redirects.
*
* **Usage**
*
- * ```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');
- *
- * // Gracefully close up everything
- * await context.close();
- * await browser.close();
- * })();
- * ```
- *
- * @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.
+ * Request parameters can be configured with `params` option, they will be serialized into the URL search parameters:
*
- * 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.
+ * ```js
+ * await request.get('https://example.com/api/getText', {
+ * params: {
+ * 'isbn': '1234',
+ * 'page': 23,
+ * }
+ * });
+ * ```
+ *
+ * @param url Target URL.
* @param options
*/
- newPage(options?: {
+ get(url: string, options?: {
/**
- * Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.
+ * 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.
*/
- acceptDownloads?: boolean;
+ data?: string|Buffer|Serializable;
/**
- * When using [page.goto(url[, options])](https://playwright.dev/docs/api/class-page#page-goto),
- * [page.route(url, handler[, options])](https://playwright.dev/docs/api/class-page#page-route),
- * [page.waitForURL(url[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-url),
- * [page.waitForRequest(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-request),
- * or
- * [page.waitForResponse(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-response)
- * it takes the base URL in consideration by using the
- * [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL.
- * Unset by default. Examples:
- * - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`
- * - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in
- * `http://localhost:3000/foo/bar.html`
- * - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
- * `http://localhost:3000/bar.html`
+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
+ * codes.
*/
- baseURL?: string;
+ failOnStatusCode?: boolean;
/**
- * Toggles bypassing page's Content-Security-Policy. Defaults to `false`.
+ * 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.
*/
- bypassCSP?: boolean;
+ form?: { [key: string]: string|number|boolean; };
/**
- * TLS Client Authentication allows the server to request a client certificate and verify it.
- *
- * **Details**
- *
- * An array of client certificates to be used. Each certificate object must have both `certPath` and `keyPath` or a
- * single `pfxPath` to load the client certificate. Optionally, `passphrase` property should be provided if the
- * certficiate is encrypted. The `origin` property should be provided with an exact match to the request origin that
- * the certificate is valid for.
- *
- * **NOTE** Using Client Certificates in combination with Proxy Servers is not supported.
- *
- * **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
- * work by replacing `localhost` with `local.playwright`.
+ * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
+ * it.
*/
- clientCertificates?: Array<{
- /**
- * Exact origin that the certificate is valid for. Origin includes `https` protocol, a hostname and optionally a port.
- */
- origin: string;
+ headers?: { [key: string]: string; };
- /**
- * Path to the file with the certificate in PEM format.
- */
- certPath?: string;
+ /**
+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
+ */
+ ignoreHTTPSErrors?: boolean;
+
+ /**
+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.
+ */
+ maxRedirects?: number;
+
+ /**
+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
+ */
+ maxRetries?: number;
+ /**
+ * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
+ * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
+ * explicitly provided. File values can be passed either as
+ * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file
+ * name, mime-type and its content.
+ */
+ multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{
/**
- * Path to the file with the private key in PEM format.
+ * File name
*/
- keyPath?: string;
+ name: string;
/**
- * Path to the PFX or PKCS12 encoded private key and certificate chain.
+ * File type
*/
- pfxPath?: string;
+ mimeType: string;
/**
- * Passphrase for the private key (PEM or PFX).
+ * File content
*/
- passphrase?: string;
- }>;
+ buffer: Buffer;
+ }; };
/**
- * 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.
- * Passing `null` resets emulation to system defaults. Defaults to `'light'`.
+ * Query parameters to be sent with the URL.
*/
- colorScheme?: null|"light"|"dark"|"no-preference";
+ params?: { [key: string]: string|number|boolean; };
/**
- * Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about
- * [emulating devices with device scale factor](https://playwright.dev/docs/emulation#devices).
+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
*/
- deviceScaleFactor?: number;
+ timeout?: number;
+ }): Promise<APIResponse>;
+ /**
+ * Sends HTTP(S) [HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD) request and returns its
+ * response. The method will populate request cookies from the context and update context cookies from the response.
+ * The method will automatically follow redirects.
+ * @param url Target URL.
+ * @param options
+ */
+ head(url: string, options?: {
/**
- * An object containing additional HTTP headers to be sent with every request. Defaults to none.
+ * 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.
*/
- extraHTTPHeaders?: { [key: string]: string; };
+ data?: string|Buffer|Serializable;
/**
- * Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See
- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.
- * Passing `null` resets emulation to system defaults. Defaults to `'none'`.
+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
+ * codes.
*/
- forcedColors?: null|"active"|"none";
+ failOnStatusCode?: boolean;
- geolocation?: {
+ /**
+ * 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. These headers will apply to the fetched request as well as any redirects initiated by
+ * it.
+ */
+ headers?: { [key: string]: string; };
+
+ /**
+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
+ */
+ ignoreHTTPSErrors?: boolean;
+
+ /**
+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.
+ */
+ maxRedirects?: number;
+
+ /**
+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
+ */
+ maxRetries?: number;
+
+ /**
+ * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
+ * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
+ * explicitly provided. File values can be passed either as
+ * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file
+ * name, mime-type and its content.
+ */
+ multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{
/**
- * Latitude between -90 and 90.
+ * File name
*/
- latitude: number;
+ name: string;
/**
- * Longitude between -180 and 180.
+ * File type
*/
- longitude: number;
+ mimeType: string;
/**
- * Non-negative accuracy value. Defaults to `0`.
+ * File content
*/
- accuracy?: number;
- };
+ buffer: Buffer;
+ }; };
/**
- * Specifies if viewport supports touch events. Defaults to false. Learn more about
- * [mobile emulation](https://playwright.dev/docs/emulation#devices).
+ * Query parameters to be sent with the URL.
*/
- hasTouch?: boolean;
+ params?: { [key: string]: string|number|boolean; };
/**
- * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
- * origin is specified, the username and password are sent to any servers upon unauthorized responses.
+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
*/
- httpCredentials?: {
- username: string;
+ timeout?: number;
+ }): Promise<APIResponse>;
- password: string;
+ /**
+ * Sends HTTP(S) [PATCH](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) request and returns its
+ * response. The method will populate request cookies from the context and update context cookies from the response.
+ * The method will automatically follow redirects.
+ * @param url Target URL.
+ * @param options
+ */
+ patch(url: string, options?: {
+ /**
+ * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
+ * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
+ * header will be set to `application/octet-stream` if not explicitly set.
+ */
+ data?: string|Buffer|Serializable;
+
+ /**
+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
+ * codes.
+ */
+ failOnStatusCode?: boolean;
+
+ /**
+ * Provides an object that will be serialized as html form using `application/x-www-form-urlencoded` encoding and sent
+ * as this request body. If this parameter is specified `content-type` header will be set to
+ * `application/x-www-form-urlencoded` unless explicitly provided.
+ */
+ form?: { [key: string]: string|number|boolean; };
+
+ /**
+ * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
+ * it.
+ */
+ headers?: { [key: string]: string; };
+
+ /**
+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
+ */
+ ignoreHTTPSErrors?: boolean;
+
+ /**
+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.
+ */
+ maxRedirects?: number;
+
+ /**
+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
+ */
+ maxRetries?: number;
+
+ /**
+ * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
+ * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
+ * explicitly provided. File values can be passed either as
+ * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file
+ * name, mime-type and its content.
+ */
+ multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{
+ /**
+ * File name
+ */
+ name: string;
/**
- * Restrain sending http credentials on specific origin (scheme://host:port).
+ * File type
*/
- origin?: string;
+ mimeType: string;
/**
- * This option only applies to the requests sent from corresponding {@link APIRequestContext} and does not affect
- * requests sent from the browser. `'always'` - `Authorization` header with basic authentication credentials will be
- * sent with the each API request. `'unauthorized` - the credentials are only sent when 401 (Unauthorized) response
- * with `WWW-Authenticate` header is received. Defaults to `'unauthorized'`.
+ * File content
*/
- send?: "unauthorized"|"always";
- };
+ buffer: Buffer;
+ }; };
/**
- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
+ * Query parameters to be sent with the URL.
*/
- ignoreHTTPSErrors?: boolean;
+ params?: { [key: string]: string|number|boolean; };
/**
- * Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,
- * so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more
- * about [mobile emulation](https://playwright.dev/docs/emulation#ismobile).
+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
*/
- isMobile?: boolean;
+ timeout?: number;
+ }): Promise<APIResponse>;
+ /**
+ * Sends HTTP(S) [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) request and returns its
+ * response. The method will populate request cookies from the context and update context cookies from the response.
+ * The method will automatically follow redirects.
+ *
+ * **Usage**
+ *
+ * JSON objects can be passed directly to the request:
+ *
+ * ```js
+ * await request.post('https://example.com/api/createBook', {
+ * data: {
+ * title: 'Book Title',
+ * author: 'John Doe',
+ * }
+ * });
+ * ```
+ *
+ * To send form data to the server use `form` option. Its value will be encoded into the request body with
+ * `application/x-www-form-urlencoded` encoding (see below how to use `multipart/form-data` form encoding to send
+ * files):
+ *
+ * ```js
+ * await request.post('https://example.com/api/findBook', {
+ * form: {
+ * title: 'Book Title',
+ * author: 'John Doe',
+ * }
+ * });
+ * ```
+ *
+ * The common way to send file(s) in the body of a request is to upload them as form fields with `multipart/form-data`
+ * encoding. Use [FormData] to construct request body and pass it to the request as `multipart` parameter:
+ *
+ * ```js
+ * const form = new FormData();
+ * form.set('name', 'John');
+ * form.append('name', 'Doe');
+ * // Send two file fields with the same name.
+ * form.append('file', new File(['console.log(2024);'], 'f1.js', { type: 'text/javascript' }));
+ * form.append('file', new File(['hello'], 'f2.txt', { type: 'text/plain' }));
+ * await request.post('https://example.com/api/uploadForm', {
+ * multipart: form
+ * });
+ * ```
+ *
+ * @param url Target URL.
+ * @param options
+ */
+ post(url: string, options?: {
/**
- * Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about
- * [disabling JavaScript](https://playwright.dev/docs/emulation#javascript-enabled).
+ * 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.
*/
- javaScriptEnabled?: boolean;
+ data?: string|Buffer|Serializable;
/**
- * Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value,
- * `Accept-Language` request header value as well as number and date formatting rules. Defaults to the system default
- * locale. Learn more about emulation in our [emulation guide](https://playwright.dev/docs/emulation#locale--timezone).
+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
+ * codes.
*/
- locale?: string;
+ failOnStatusCode?: boolean;
/**
- * Logger sink for Playwright logging.
+ * 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.
*/
- logger?: Logger;
+ form?: { [key: string]: string|number|boolean; };
/**
- * Whether to emulate network being offline. Defaults to `false`. Learn more about
- * [network emulation](https://playwright.dev/docs/emulation#offline).
+ * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
+ * it.
*/
- offline?: boolean;
+ headers?: { [key: string]: string; };
/**
- * A list of permissions to grant to all pages in this context. See
- * [browserContext.grantPermissions(permissions[, options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-grant-permissions)
- * for more details. Defaults to none.
+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
*/
- permissions?: Array<string>;
+ ignoreHTTPSErrors?: boolean;
/**
- * Network proxy settings to use with this context. Defaults to none.
- *
- * **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' } })`.
+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.
*/
- 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;
+ maxRedirects?: number;
+
+ /**
+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
+ */
+ maxRetries?: number;
+ /**
+ * Provides an object that will be serialized as html form using `multipart/form-data` encoding and sent as this
+ * request body. If this parameter is specified `content-type` header will be set to `multipart/form-data` unless
+ * explicitly provided. File values can be passed either as
+ * [`fs.ReadStream`](https://nodejs.org/api/fs.html#fs_class_fs_readstream) or as file-like object containing file
+ * name, mime-type and its content.
+ */
+ multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{
/**
- * Optional comma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.
+ * File name
*/
- bypass?: string;
+ name: string;
/**
- * Optional username to use if HTTP proxy requires authentication.
+ * File type
*/
- username?: string;
+ mimeType: string;
/**
- * Optional password to use if HTTP proxy requires authentication.
+ * File content
*/
- password?: string;
- };
+ buffer: Buffer;
+ }; };
/**
- * Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into `recordHar.path` file.
- * If not specified, the HAR is not recorded. Make sure to await
- * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for
- * the HAR to be saved.
+ * Query parameters to be sent with the URL.
*/
- recordHar?: {
- /**
- * Optional setting to control whether to omit request content from the HAR. Defaults to `false`. Deprecated, use
- * `content` policy instead.
- */
- omitContent?: boolean;
+ params?: { [key: string]: string|number|boolean; };
- /**
- * Optional setting to control resource content management. If `omit` is specified, content is not persisted. If
- * `attach` is specified, resources are persisted as separate files or entries in the ZIP archive. If `embed` is
- * specified, content is stored inline the HAR file as per HAR specification. Defaults to `attach` for `.zip` output
- * files and to `embed` for all other file extensions.
- */
- content?: "omit"|"embed"|"attach";
+ /**
+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
+ */
+ timeout?: number;
+ }): Promise<APIResponse>;
- /**
- * Path on the filesystem to write the HAR file to. If the file name ends with `.zip`, `content: 'attach'` is used by
- * default.
- */
- path: string;
+ /**
+ * Sends HTTP(S) [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) request and returns its
+ * response. The method will populate request cookies from the context and update context cookies from the response.
+ * The method will automatically follow redirects.
+ * @param url Target URL.
+ * @param options
+ */
+ put(url: string, options?: {
+ /**
+ * Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
+ * and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type`
+ * header will be set to `application/octet-stream` if not explicitly set.
+ */
+ data?: string|Buffer|Serializable;
- /**
- * When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
- * cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.
- */
- mode?: "full"|"minimal";
+ /**
+ * Whether to throw on response codes other than 2xx and 3xx. By default response object is returned for all status
+ * codes.
+ */
+ failOnStatusCode?: boolean;
- /**
- * A glob or regex pattern to filter requests that are stored in the HAR. When a `baseURL` via the context options was
- * provided and the passed URL is a path, it gets merged via the
- * [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor. Defaults to none.
- */
- urlFilter?: string|RegExp;
- };
+ /**
+ * 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; };
/**
- * Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded.
- * Make sure to await
- * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for
- * videos to be saved.
+ * Allows to set HTTP headers. These headers will apply to the fetched request as well as any redirects initiated by
+ * it.
*/
- recordVideo?: {
- /**
- * Path to the directory to put videos into.
- */
- dir: string;
+ headers?: { [key: string]: 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;
+ /**
+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
+ */
+ ignoreHTTPSErrors?: boolean;
- /**
- * Video frame height.
- */
- height: number;
- };
- };
+ /**
+ * Maximum number of request redirects that will be followed automatically. An error will be thrown if the number is
+ * exceeded. Defaults to `20`. Pass `0` to not follow redirects.
+ */
+ maxRedirects?: number;
/**
- * Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See
- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.
- * Passing `null` resets emulation to system defaults. Defaults to `'no-preference'`.
+ * Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not
+ * retry based on HTTP response codes. An error will be thrown if the limit is exceeded. Defaults to `0` - no retries.
*/
- reducedMotion?: null|"reduce"|"no-preference";
+ maxRetries?: number;
/**
- * Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the
- * `viewport` is set.
+ * 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.
*/
- screen?: {
+ multipart?: FormData|{ [key: string]: string|number|boolean|ReadStream|{
/**
- * page width in pixels.
+ * File name
*/
- width: number;
+ name: string;
/**
- * page height in pixels.
+ * File type
*/
- height: number;
- };
+ mimeType: string;
+
+ /**
+ * File content
+ */
+ buffer: Buffer;
+ }; };
/**
- * Whether to allow sites to register Service workers. Defaults to `'allow'`.
- * - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be
- * registered.
- * - `'block'`: Playwright will block all registration of Service Workers.
+ * Query parameters to be sent with the URL.
*/
- serviceWorkers?: "allow"|"block";
+ params?: { [key: string]: string|number|boolean; };
/**
- * Learn more about [storage state and auth](https://playwright.dev/docs/auth).
- *
- * 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).
+ * Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
*/
- storageState?: string|{
- /**
- * Cookies to set for context
- */
- cookies: Array<{
- name: string;
+ timeout?: number;
+ }): Promise<APIResponse>;
- value: string;
+ /**
+ * 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.
+ */
+ path?: string;
+ }): Promise<{
+ cookies: Array<{
+ name: string;
- /**
- * Domain and path are required. For the cookie to apply to all subdomains as well, prefix domain with a dot, like
- * this: ".example.com"
- */
- domain: string;
+ value: string;
- /**
- * Domain and path are required
- */
- path: string;
+ domain: string;
- /**
- * Unix time in seconds.
- */
- expires: number;
+ path: string;
- httpOnly: boolean;
+ /**
+ * Unix time in seconds.
+ */
+ expires: number;
- secure: boolean;
+ httpOnly: boolean;
- /**
- * sameSite flag
- */
- sameSite: "Strict"|"Lax"|"None";
- }>;
+ secure: boolean;
- /**
- * localStorage to set for context
- */
- origins: Array<{
- origin: string;
+ sameSite: "Strict"|"Lax"|"None";
+ }>;
- localStorage: Array<{
- name: string;
+ origins: Array<{
+ origin: string;
- value: string;
- }>;
- }>;
- };
+ localStorage: Array<{
+ name: string;
- /**
- * If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on
- * selectors that imply single target DOM element will throw when more than one element matches the selector. This
- * option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See {@link Locator} to
- * learn more about the strict mode.
- */
- strictSelectors?: boolean;
+ value: 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. Defaults to the system timezone.
- */
- timezoneId?: string;
+ [Symbol.asyncDispose](): Promise<void>;
+}
- /**
- * Specific user agent to use in this context.
- */
- userAgent?: string;
+/**
+ * {@link APIResponse} class represents responses returned by
+ * [apiRequestContext.get(url[, options])](https://playwright.dev/docs/api/class-apirequestcontext#api-request-context-get)
+ * and similar methods.
+ */
+export interface APIResponse {
+ /**
+ * Returns the buffer with response body.
+ */
+ body(): Promise<Buffer>;
- /**
- * @deprecated Use `recordVideo` instead.
- */
- videoSize?: {
- /**
- * Video frame width.
- */
- width: number;
+ /**
+ * Disposes the body of this response. If not called then the body will stay in memory until the context closes.
+ */
+ dispose(): Promise<void>;
- /**
- * Video frame height.
- */
- height: number;
- };
+ /**
+ * An object with all the response HTTP headers associated with this response.
+ */
+ headers(): { [key: string]: string; };
+ /**
+ * 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<{
/**
- * @deprecated Use `recordVideo` instead.
+ * Name of the header.
*/
- videosPath?: string;
+ name: string;
/**
- * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use `null` to disable the consistent
- * viewport emulation. Learn more about [viewport emulation](https://playwright.dev/docs/emulation#viewport).
- *
- * **NOTE** The `null` value opts out from the default presets, makes viewport depend on the host window size defined
- * by the operating system. It makes the execution of the tests non-deterministic.
+ * Value of the header.
*/
- viewport?: null|{
- /**
- * page width in pixels.
- */
- width: number;
-
- /**
- * page height in pixels.
- */
- height: number;
- };
- }): Promise<Page>;
+ value: string;
+ }>;
/**
- * **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](https://playwright.dev/docs/trace-viewer) could be found
- * [here](https://playwright.dev/docs/api/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.
- *
- * **Usage**
- *
- * ```js
- * await browser.startTracing(page, { path: 'trace.json' });
- * await page.goto('https://www.google.com');
- * await browser.stopTracing();
- * ```
+ * Returns the JSON representation of response body.
*
- * @param page Optional, if specified, tracing includes screenshots of the given page.
- * @param options
+ * This method will throw if the response body is not parsable via `JSON.parse`.
*/
- startTracing(page?: Page, options?: {
- /**
- * specify custom categories to use instead of default.
- */
- categories?: Array<string>;
+ json(): Promise<Serializable>;
- /**
- * A path to write the trace file to.
- */
- path?: string;
+ /**
+ * Contains a boolean stating whether the response was successful (status in the range 200-299) or not.
+ */
+ ok(): boolean;
- /**
- * captures screenshots in the trace.
- */
- screenshots?: boolean;
- }): Promise<void>;
+ /**
+ * Contains the status code of the response (e.g., 200 for a success).
+ */
+ status(): number;
/**
- * **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](https://playwright.dev/docs/trace-viewer) could be found
- * [here](https://playwright.dev/docs/api/class-tracing).
- *
- * Returns the buffer with trace data.
+ * Contains the status text of the response (e.g. usually an "OK" for a success).
*/
- stopTracing(): Promise<Buffer>;
+ statusText(): string;
/**
- * Returns the browser version.
+ * Returns the text representation of response body.
+ */
+ text(): Promise<string>;
+
+ /**
+ * Contains the URL of the response.
*/
- version(): string;
+ url(): string;
[Symbol.asyncDispose](): Promise<void>;
}
@@ -20203,546 +20241,481 @@ export interface WebSocket {
}
-export interface BrowserContextOptions {
- /**
- * Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.
- */
- acceptDownloads?: boolean;
-
+interface AccessibilitySnapshotOptions {
/**
- * When using [page.goto(url[, options])](https://playwright.dev/docs/api/class-page#page-goto),
- * [page.route(url, handler[, options])](https://playwright.dev/docs/api/class-page#page-route),
- * [page.waitForURL(url[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-url),
- * [page.waitForRequest(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-request),
- * or
- * [page.waitForResponse(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-response)
- * it takes the base URL in consideration by using the
- * [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL.
- * Unset by default. Examples:
- * - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`
- * - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in
- * `http://localhost:3000/foo/bar.html`
- * - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
- * `http://localhost:3000/bar.html`
+ * Prune uninteresting nodes from the tree. Defaults to `true`.
*/
- baseURL?: string;
+ interestingOnly?: boolean;
/**
- * Toggles bypassing page's Content-Security-Policy. Defaults to `false`.
+ * The root DOM element for the snapshot. Defaults to the whole page.
*/
- bypassCSP?: boolean;
+ root?: ElementHandle;
+}
+export interface LaunchOptions {
/**
- * TLS Client Authentication allows the server to request a client certificate and verify it.
- *
- * **Details**
- *
- * An array of client certificates to be used. Each certificate object must have both `certPath` and `keyPath` or a
- * single `pfxPath` to load the client certificate. Optionally, `passphrase` property should be provided if the
- * certficiate is encrypted. The `origin` property should be provided with an exact match to the request origin that
- * the certificate is valid for.
- *
- * **NOTE** Using Client Certificates in combination with Proxy Servers is not supported.
+ * **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality.
*
- * **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
- * work by replacing `localhost` with `local.playwright`.
- */
- clientCertificates?: Array<{
- /**
- * Exact origin that the certificate is valid for. Origin includes `https` protocol, a hostname and optionally a port.
- */
- origin: string;
-
- /**
- * Path to the file with the certificate in PEM format.
- */
- certPath?: string;
-
- /**
- * Path to the file with the private key in PEM format.
- */
- keyPath?: string;
-
- /**
- * Path to the PFX or PKCS12 encoded private key and certificate chain.
- */
- pfxPath?: string;
-
- /**
- * Passphrase for the private key (PEM or PFX).
- */
- passphrase?: string;
- }>;
-
- /**
- * 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.
- * Passing `null` resets emulation to system defaults. Defaults to `'light'`.
- */
- colorScheme?: null|"light"|"dark"|"no-preference";
-
- /**
- * Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about
- * [emulating devices with device scale factor](https://playwright.dev/docs/emulation#devices).
- */
- deviceScaleFactor?: number;
-
- /**
- * An object containing additional HTTP headers to be sent with every request. Defaults to none.
- */
- extraHTTPHeaders?: { [key: string]: string; };
-
- /**
- * Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See
- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.
- * Passing `null` resets emulation to system defaults. Defaults to `'none'`.
+ * Additional arguments to pass to the browser instance. The list of Chromium flags can be found
+ * [here](https://peter.sh/experiments/chromium-command-line-switches/).
*/
- forcedColors?: null|"active"|"none";
-
- geolocation?: Geolocation;
+ args?: Array<string>;
/**
- * Specifies if viewport supports touch events. Defaults to false. Learn more about
- * [mobile emulation](https://playwright.dev/docs/emulation#devices).
+ * Browser distribution channel. Supported values are "chrome", "chrome-beta", "chrome-dev", "chrome-canary",
+ * "msedge", "msedge-beta", "msedge-dev", "msedge-canary". Read more about using
+ * [Google Chrome and Microsoft Edge](https://playwright.dev/docs/browsers#google-chrome--microsoft-edge).
*/
- hasTouch?: boolean;
+ channel?: string;
/**
- * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
- * origin is specified, the username and password are sent to any servers upon unauthorized responses.
+ * Enable Chromium sandboxing. Defaults to `false`.
*/
- httpCredentials?: HTTPCredentials;
+ chromiumSandbox?: boolean;
/**
- * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
+ * **Chromium-only** Whether to auto-open a Developer Tools panel for each tab. If this option is `true`, the
+ * `headless` option will be set `false`.
+ * @deprecated Use [debugging tools](https://playwright.dev/docs/debug) instead.
*/
- ignoreHTTPSErrors?: boolean;
+ devtools?: boolean;
/**
- * Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,
- * so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more
- * about [mobile emulation](https://playwright.dev/docs/emulation#ismobile).
+ * If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and
+ * is deleted when browser is closed. In either case, the downloads are deleted when the browser context they were
+ * created in is closed.
*/
- isMobile?: boolean;
+ downloadsPath?: string;
/**
- * Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about
- * [disabling JavaScript](https://playwright.dev/docs/emulation#javascript-enabled).
+ * Specify environment variables that will be visible to the browser. Defaults to `process.env`.
*/
- javaScriptEnabled?: boolean;
+ env?: { [key: string]: string|number|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. Defaults to the system default
- * locale. Learn more about emulation in our [emulation guide](https://playwright.dev/docs/emulation#locale--timezone).
+ * Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is
+ * resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium,
+ * Firefox or WebKit, use at your own risk.
*/
- locale?: string;
+ executablePath?: string;
/**
- * Logger sink for Playwright logging.
+ * Firefox user preferences. Learn more about the Firefox user preferences at
+ * [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox).
*/
- logger?: Logger;
+ firefoxUserPrefs?: { [key: string]: string|number|boolean; };
/**
- * Whether to emulate network being offline. Defaults to `false`. Learn more about
- * [network emulation](https://playwright.dev/docs/emulation#offline).
+ * Close the browser process on SIGHUP. Defaults to `true`.
*/
- offline?: boolean;
+ handleSIGHUP?: 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. Defaults to none.
+ * Close the browser process on Ctrl-C. Defaults to `true`.
*/
- permissions?: Array<string>;
+ handleSIGINT?: boolean;
/**
- * Network proxy settings to use with this context. Defaults to none.
- *
- * **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' } })`.
+ * Close the browser process on SIGTERM. Defaults to `true`.
*/
- 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 comma-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;
- };
+ handleSIGTERM?: boolean;
/**
- * Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into `recordHar.path` file.
- * If not specified, the HAR is not recorded. Make sure to await
- * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for
- * the HAR to be saved.
+ * Whether to run browser in headless mode. More details for
+ * [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and
+ * [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode). Defaults to `true` unless the
+ * `devtools` option is `true`.
*/
- recordHar?: {
- /**
- * Optional setting to control whether to omit request content from the HAR. Defaults to `false`. Deprecated, use
- * `content` policy instead.
- */
- omitContent?: boolean;
-
- /**
- * Optional setting to control resource content management. If `omit` is specified, content is not persisted. If
- * `attach` is specified, resources are persisted as separate files or entries in the ZIP archive. If `embed` is
- * specified, content is stored inline the HAR file as per HAR specification. Defaults to `attach` for `.zip` output
- * files and to `embed` for all other file extensions.
- */
- content?: "omit"|"embed"|"attach";
-
- /**
- * Path on the filesystem to write the HAR file to. If the file name ends with `.zip`, `content: 'attach'` is used by
- * default.
- */
- path: string;
-
- /**
- * When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
- * cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.
- */
- mode?: "full"|"minimal";
-
- /**
- * A glob or regex pattern to filter requests that are stored in the HAR. When a `baseURL` via the context options was
- * provided and the passed URL is a path, it gets merged via the
- * [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor. Defaults to none.
- */
- urlFilter?: string|RegExp;
- };
+ headless?: boolean;
/**
- * Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded.
- * Make sure to await
- * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for
- * videos to be saved.
- */
- 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;
- };
- };
+ * If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. If an array is
+ * given, then filters out the given default arguments. Dangerous option; use with care. Defaults to `false`.
+ */
+ ignoreDefaultArgs?: boolean|Array<string>;
/**
- * Emulates `'prefers-reduced-motion'` media feature, supported values are `'reduce'`, `'no-preference'`. See
- * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.
- * Passing `null` resets emulation to system defaults. Defaults to `'no-preference'`.
+ * Logger sink for Playwright logging.
*/
- reducedMotion?: null|"reduce"|"no-preference";
+ logger?: Logger;
/**
- * Emulates consistent window screen size available inside web page via `window.screen`. Is only used when the
- * `viewport` is set.
+ * Network proxy settings.
*/
- screen?: {
+ proxy?: {
/**
- * page width in pixels.
+ * 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.
*/
- width: number;
+ server: string;
/**
- * page height in pixels.
+ * Optional comma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.
*/
- height: number;
+ bypass?: string;
+
+ /**
+ * Optional username to use if HTTP proxy requires authentication.
+ */
+ username?: string;
+
+ /**
+ * Optional password to use if HTTP proxy requires authentication.
+ */
+ password?: string;
};
/**
- * Whether to allow sites to register Service workers. Defaults to `'allow'`.
- * - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be
- * registered.
- * - `'block'`: Playwright will block all registration of Service Workers.
+ * Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
+ * on.
*/
- serviceWorkers?: "allow"|"block";
+ slowMo?: number;
/**
- * Learn more about [storage state and auth](https://playwright.dev/docs/auth).
- *
- * 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).
+ * Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0`
+ * to disable timeout.
*/
- storageState?: string|{
- /**
- * Cookies to set for context
- */
- cookies: Array<{
- name: string;
-
- value: string;
+ timeout?: number;
- /**
- * Domain and path are required. For the cookie to apply to all subdomains as well, prefix domain with a dot, like
- * this: ".example.com"
- */
- domain: string;
+ /**
+ * If specified, traces are saved into this directory.
+ */
+ tracesDir?: string;
+}
- /**
- * Domain and path are required
- */
- path: string;
+export interface ConnectOverCDPOptions {
+ /**
+ * Deprecated, use the first argument instead. Optional.
+ */
+ endpointURL?: string;
- /**
- * Unix time in seconds.
- */
- expires: number;
+ /**
+ * Additional HTTP headers to be sent with connect request. Optional.
+ */
+ headers?: { [key: string]: string; };
- httpOnly: boolean;
+ /**
+ * Logger sink for Playwright logging. Optional.
+ */
+ logger?: Logger;
- secure: boolean;
+ /**
+ * Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
+ * on. Defaults to 0.
+ */
+ slowMo?: number;
- /**
- * sameSite flag
- */
- sameSite: "Strict"|"Lax"|"None";
- }>;
+ /**
+ * Maximum time in milliseconds to wait for the connection to be established. Defaults to `30000` (30 seconds). Pass
+ * `0` to disable timeout.
+ */
+ timeout?: number;
+}
- /**
- * localStorage to set for context
- */
- origins: Array<{
- origin: string;
+export interface ConnectOptions {
+ /**
+ * This option exposes network available on the connecting client to the browser being connected to. Consists of a
+ * list of rules separated by comma.
+ *
+ * Available rules:
+ * 1. Hostname pattern, for example: `example.com`, `*.org:99`, `x.*.y.com`, `*foo.org`.
+ * 1. IP literal, for example: `127.0.0.1`, `0.0.0.0:99`, `[::1]`, `[0:0::1]:99`.
+ * 1. `<loopback>` that matches local loopback interfaces: `localhost`, `*.localhost`, `127.0.0.1`, `[::1]`.
+ *
+ * Some common examples:
+ * 1. `"*"` to expose all network.
+ * 1. `"<loopback>"` to expose localhost network.
+ * 1. `"*.test.internal-domain,*.staging.internal-domain,<loopback>"` to expose test/staging deployments and
+ * localhost.
+ */
+ exposeNetwork?: string;
- localStorage: Array<{
- name: string;
+ /**
+ * Additional HTTP headers to be sent with web socket connect request. Optional.
+ */
+ headers?: { [key: string]: string; };
- value: string;
- }>;
- }>;
- };
+ /**
+ * Logger sink for Playwright logging. Optional.
+ */
+ logger?: Logger;
/**
- * If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on
- * selectors that imply single target DOM element will throw when more than one element matches the selector. This
- * option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See {@link Locator} to
- * learn more about the strict mode.
+ * Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
+ * on. Defaults to 0.
*/
- strictSelectors?: boolean;
+ slowMo?: 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. Defaults to the system timezone.
+ * Maximum time in milliseconds to wait for the connection to be established. Defaults to `0` (no timeout).
*/
- timezoneId?: string;
+ timeout?: number;
+}
+export interface LocatorScreenshotOptions {
/**
- * Specific user agent to use in this context.
+ * When set to `"disabled"`, stops CSS animations, CSS transitions and Web Animations. Animations get different
+ * treatment depending on their duration:
+ * - finite animations are fast-forwarded to completion, so they'll fire `transitionend` event.
+ * - infinite animations are canceled to initial state, and then played over after the screenshot.
+ *
+ * Defaults to `"allow"` that leaves animations untouched.
*/
- userAgent?: string;
+ animations?: "disabled"|"allow";
/**
- * @deprecated Use `recordVideo` instead.
+ * When set to `"hide"`, screenshot will hide text caret. When set to `"initial"`, text caret behavior will not be
+ * changed. Defaults to `"hide"`.
*/
- videoSize?: {
- /**
- * Video frame width.
- */
- width: number;
+ caret?: "hide"|"initial";
- /**
- * Video frame height.
- */
- height: number;
- };
+ /**
+ * Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink
+ * box `#FF00FF` (customized by `maskColor`) that completely covers its bounding box.
+ */
+ mask?: Array<Locator>;
/**
- * @deprecated Use `recordVideo` instead.
+ * Specify the color of the overlay box for masked elements, in
+ * [CSS color format](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). Default color is pink `#FF00FF`.
*/
- videosPath?: string;
+ maskColor?: string;
/**
- * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use `null` to disable the consistent
- * viewport emulation. Learn more about [viewport emulation](https://playwright.dev/docs/emulation#viewport).
- *
- * **NOTE** The `null` value opts out from the default presets, makes viewport depend on the host window size defined
- * by the operating system. It makes the execution of the tests non-deterministic.
+ * Hides default white background and allows capturing screenshots with transparency. Not applicable to `jpeg` images.
+ * Defaults to `false`.
*/
- viewport?: null|ViewportSize;
-}
+ omitBackground?: boolean;
-export interface ViewportSize {
/**
- * page width in pixels.
+ * The file path to save the image to. The screenshot type will be inferred from file extension. If `path` is a
+ * relative path, then it is resolved relative to the current working directory. If no path is provided, the image
+ * won't be saved to the disk.
*/
- width: number;
+ path?: string;
/**
- * page height in pixels.
+ * The quality of the image, between 0-100. Not applicable to `png` images.
*/
- height: number;
-}
+ quality?: number;
-export interface HTTPCredentials {
- username: string;
+ /**
+ * When set to `"css"`, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this
+ * will keep screenshots small. Using `"device"` option will produce a single pixel per each device pixel, so
+ * screenshots of high-dpi devices will be twice as large or even larger.
+ *
+ * Defaults to `"device"`.
+ */
+ scale?: "css"|"device";
- password: string;
+ /**
+ * Text of the stylesheet to apply while making the screenshot. This is where you can hide dynamic elements, make
+ * elements invisible or change their properties to help you creating repeatable screenshots. This stylesheet pierces
+ * the Shadow DOM and applies to the inner frames.
+ */
+ style?: string;
/**
- * Restrain sending http credentials on specific origin (scheme://host:port).
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
- origin?: string;
+ timeout?: number;
/**
- * This option only applies to the requests sent from corresponding {@link APIRequestContext} and does not affect
- * requests sent from the browser. `'always'` - `Authorization` header with basic authentication credentials will be
- * sent with the each API request. `'unauthorized` - the credentials are only sent when 401 (Unauthorized) response
- * with `WWW-Authenticate` header is received. Defaults to `'unauthorized'`.
+ * Specify screenshot type, defaults to `png`.
*/
- send?: "unauthorized"|"always";
+ type?: "png"|"jpeg";
}
-export interface Geolocation {
+interface ElementHandleWaitForSelectorOptions {
+ /**
+ * Defaults to `'visible'`. Can be either:
+ * - `'attached'` - wait for element to be present in DOM.
+ * - `'detached'` - wait for element to not be present in DOM.
+ * - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element
+ * without any content or with `display:none` has an empty bounding box and is not considered visible.
+ * - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or
+ * `visibility:hidden`. This is opposite to the `'visible'` option.
+ */
+ state?: "attached"|"detached"|"visible"|"hidden";
+
/**
- * Latitude between -90 and 90.
+ * When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
+ * element, the call throws an exception.
*/
- latitude: number;
+ strict?: boolean;
/**
- * Longitude between -180 and 180.
+ * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
+ * option in the config, or by using the
+ * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
+ * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
*/
- longitude: number;
+ timeout?: number;
+}
+export interface BrowserContextOptions {
/**
- * Non-negative accuracy value. Defaults to `0`.
+ * Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted.
*/
- accuracy?: number;
-}
+ acceptDownloads?: boolean;
-interface AccessibilitySnapshotOptions {
/**
- * Prune uninteresting nodes from the tree. Defaults to `true`.
+ * When using [page.goto(url[, options])](https://playwright.dev/docs/api/class-page#page-goto),
+ * [page.route(url, handler[, options])](https://playwright.dev/docs/api/class-page#page-route),
+ * [page.waitForURL(url[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-url),
+ * [page.waitForRequest(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-request),
+ * or
+ * [page.waitForResponse(urlOrPredicate[, options])](https://playwright.dev/docs/api/class-page#page-wait-for-response)
+ * it takes the base URL in consideration by using the
+ * [`URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor for building the corresponding URL.
+ * Unset by default. Examples:
+ * - baseURL: `http://localhost:3000` and navigating to `/bar.html` results in `http://localhost:3000/bar.html`
+ * - baseURL: `http://localhost:3000/foo/` and navigating to `./bar.html` results in
+ * `http://localhost:3000/foo/bar.html`
+ * - baseURL: `http://localhost:3000/foo` (without trailing slash) and navigating to `./bar.html` results in
+ * `http://localhost:3000/bar.html`
*/
- interestingOnly?: boolean;
+ baseURL?: string;
/**
- * The root DOM element for the snapshot. Defaults to the whole page.
+ * Toggles bypassing page's Content-Security-Policy. Defaults to `false`.
*/
- root?: ElementHandle;
-}
+ bypassCSP?: boolean;
-export interface LaunchOptions {
/**
- * **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality.
+ * TLS Client Authentication allows the server to request a client certificate and verify it.
*
- * Additional arguments to pass to the browser instance. The list of Chromium flags can be found
- * [here](https://peter.sh/experiments/chromium-command-line-switches/).
+ * **Details**
+ *
+ * An array of client certificates to be used. Each certificate object must have both `certPath` and `keyPath` or a
+ * single `pfxPath` to load the client certificate. Optionally, `passphrase` property should be provided if the
+ * certficiate is encrypted. The `origin` property should be provided with an exact match to the request origin that
+ * the certificate is valid for.
+ *
+ * **NOTE** Using Client Certificates in combination with Proxy Servers is not supported.
+ *
+ * **NOTE** When using WebKit on macOS, accessing `localhost` will not pick up client certificates. You can make it
+ * work by replacing `localhost` with `local.playwright`.
*/
- args?: Array<string>;
+ clientCertificates?: Array<{
+ /**
+ * Exact origin that the certificate is valid for. Origin includes `https` protocol, a hostname and optionally a port.
+ */
+ origin: string;
+
+ /**
+ * Path to the file with the certificate in PEM format.
+ */
+ certPath?: string;
+
+ /**
+ * Path to the file with the private key in PEM format.
+ */
+ keyPath?: string;
+
+ /**
+ * Path to the PFX or PKCS12 encoded private key and certificate chain.
+ */
+ pfxPath?: string;
+
+ /**
+ * Passphrase for the private key (PEM or PFX).
+ */
+ passphrase?: string;
+ }>;
/**
- * Browser distribution channel. Supported values are "chrome", "chrome-beta", "chrome-dev", "chrome-canary",
- * "msedge", "msedge-beta", "msedge-dev", "msedge-canary". Read more about using
- * [Google Chrome and Microsoft Edge](https://playwright.dev/docs/browsers#google-chrome--microsoft-edge).
+ * 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.
+ * Passing `null` resets emulation to system defaults. Defaults to `'light'`.
*/
- channel?: string;
+ colorScheme?: null|"light"|"dark"|"no-preference";
/**
- * Enable Chromium sandboxing. Defaults to `false`.
+ * Specify device scale factor (can be thought of as dpr). Defaults to `1`. Learn more about
+ * [emulating devices with device scale factor](https://playwright.dev/docs/emulation#devices).
*/
- chromiumSandbox?: boolean;
+ deviceScaleFactor?: number;
/**
- * **Chromium-only** Whether to auto-open a Developer Tools panel for each tab. If this option is `true`, the
- * `headless` option will be set `false`.
- * @deprecated Use [debugging tools](https://playwright.dev/docs/debug) instead.
+ * An object containing additional HTTP headers to be sent with every request. Defaults to none.
*/
- devtools?: boolean;
+ extraHTTPHeaders?: { [key: string]: string; };
/**
- * If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and
- * is deleted when browser is closed. In either case, the downloads are deleted when the browser context they were
- * created in is closed.
+ * Emulates `'forced-colors'` media feature, supported values are `'active'`, `'none'`. See
+ * [page.emulateMedia([options])](https://playwright.dev/docs/api/class-page#page-emulate-media) for more details.
+ * Passing `null` resets emulation to system defaults. Defaults to `'none'`.
*/
- downloadsPath?: string;
+ forcedColors?: null|"active"|"none";
+
+ geolocation?: Geolocation;
/**
- * Specify environment variables that will be visible to the browser. Defaults to `process.env`.
+ * Specifies if viewport supports touch events. Defaults to false. Learn more about
+ * [mobile emulation](https://playwright.dev/docs/emulation#devices).
*/
- env?: { [key: string]: string|number|boolean; };
+ hasTouch?: boolean;
/**
- * Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is
- * resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium,
- * Firefox or WebKit, use at your own risk.
+ * Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). If no
+ * origin is specified, the username and password are sent to any servers upon unauthorized responses.
*/
- executablePath?: string;
+ httpCredentials?: HTTPCredentials;
/**
- * Firefox user preferences. Learn more about the Firefox user preferences at
- * [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox).
+ * Whether to ignore HTTPS errors when sending network requests. Defaults to `false`.
*/
- firefoxUserPrefs?: { [key: string]: string|number|boolean; };
+ ignoreHTTPSErrors?: boolean;
/**
- * Close the browser process on SIGHUP. Defaults to `true`.
+ * Whether the `meta viewport` tag is taken into account and touch events are enabled. isMobile is a part of device,
+ * so you don't actually need to set it manually. Defaults to `false` and is not supported in Firefox. Learn more
+ * about [mobile emulation](https://playwright.dev/docs/emulation#ismobile).
*/
- handleSIGHUP?: boolean;
+ isMobile?: boolean;
/**
- * Close the browser process on Ctrl-C. Defaults to `true`.
+ * Whether or not to enable JavaScript in the context. Defaults to `true`. Learn more about
+ * [disabling JavaScript](https://playwright.dev/docs/emulation#javascript-enabled).
*/
- handleSIGINT?: boolean;
+ javaScriptEnabled?: boolean;
/**
- * Close the browser process on SIGTERM. Defaults to `true`.
+ * Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value,
+ * `Accept-Language` request header value as well as number and date formatting rules. Defaults to the system default
+ * locale. Learn more about emulation in our [emulation guide](https://playwright.dev/docs/emulation#locale--timezone).
*/
- handleSIGTERM?: boolean;
+ locale?: string;
/**
- * Whether to run browser in headless mode. More details for
- * [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and
- * [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode). Defaults to `true` unless the
- * `devtools` option is `true`.
+ * Logger sink for Playwright logging.
*/
- headless?: boolean;
+ logger?: Logger;
/**
- * If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. If an array is
- * given, then filters out the given default arguments. Dangerous option; use with care. Defaults to `false`.
+ * Whether to emulate network being offline. Defaults to `false`. Learn more about
+ * [network emulation](https://playwright.dev/docs/emulation#offline).
*/
- ignoreDefaultArgs?: boolean|Array<string>;
+ offline?: boolean;
/**
- * Logger sink for Playwright logging.
+ * A list of permissions to grant to all pages in this context. See
+ * [browserContext.grantPermissions(permissions[, options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-grant-permissions)
+ * for more details. Defaults to none.
*/
- logger?: Logger;
+ permissions?: Array<string>;
/**
- * Network proxy settings.
+ * Network proxy settings to use with this context. Defaults to none.
+ *
+ * **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?: {
/**
@@ -20757,205 +20730,270 @@ export interface LaunchOptions {
bypass?: string;
/**
- * Optional username to use if HTTP proxy requires authentication.
+ * Optional username to use if HTTP proxy requires authentication.
+ */
+ username?: string;
+
+ /**
+ * Optional password to use if HTTP proxy requires authentication.
+ */
+ password?: string;
+ };
+
+ /**
+ * Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into `recordHar.path` file.
+ * If not specified, the HAR is not recorded. Make sure to await
+ * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for
+ * the HAR to be saved.
+ */
+ recordHar?: {
+ /**
+ * Optional setting to control whether to omit request content from the HAR. Defaults to `false`. Deprecated, use
+ * `content` policy instead.
+ */
+ omitContent?: boolean;
+
+ /**
+ * Optional setting to control resource content management. If `omit` is specified, content is not persisted. If
+ * `attach` is specified, resources are persisted as separate files or entries in the ZIP archive. If `embed` is
+ * specified, content is stored inline the HAR file as per HAR specification. Defaults to `attach` for `.zip` output
+ * files and to `embed` for all other file extensions.
+ */
+ content?: "omit"|"embed"|"attach";
+
+ /**
+ * Path on the filesystem to write the HAR file to. If the file name ends with `.zip`, `content: 'attach'` is used by
+ * default.
+ */
+ path: string;
+
+ /**
+ * When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
+ * cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `full`.
+ */
+ mode?: "full"|"minimal";
+
+ /**
+ * A glob or regex pattern to filter requests that are stored in the HAR. When a `baseURL` via the context options was
+ * provided and the passed URL is a path, it gets merged via the
+ * [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor. Defaults to none.
+ */
+ urlFilter?: string|RegExp;
+ };
+
+ /**
+ * Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded.
+ * Make sure to await
+ * [browserContext.close([options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-close) for
+ * videos to be saved.
+ */
+ 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.
+ * Passing `null` resets emulation to system defaults. Defaults to `'no-preference'`.
+ */
+ reducedMotion?: null|"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.
*/
- username?: string;
+ width: number;
/**
- * Optional password to use if HTTP proxy requires authentication.
+ * page height in pixels.
*/
- password?: string;
+ height: number;
};
/**
- * Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
- * on.
+ * Whether to allow sites to register Service workers. Defaults to `'allow'`.
+ * - `'allow'`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be
+ * registered.
+ * - `'block'`: Playwright will block all registration of Service Workers.
*/
- slowMo?: number;
+ serviceWorkers?: "allow"|"block";
/**
- * Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0`
- * to disable timeout.
+ * Learn more about [storage state and auth](https://playwright.dev/docs/auth).
+ *
+ * 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).
*/
- timeout?: number;
+ storageState?: string|{
+ /**
+ * Cookies to set for context
+ */
+ cookies: Array<{
+ name: string;
- /**
- * If specified, traces are saved into this directory.
- */
- tracesDir?: string;
-}
+ value: string;
-export interface ConnectOverCDPOptions {
- /**
- * Deprecated, use the first argument instead. Optional.
- */
- endpointURL?: string;
+ /**
+ * Domain and path are required. For the cookie to apply to all subdomains as well, prefix domain with a dot, like
+ * this: ".example.com"
+ */
+ domain: string;
- /**
- * Additional HTTP headers to be sent with connect request. Optional.
- */
- headers?: { [key: string]: string; };
+ /**
+ * Domain and path are required
+ */
+ path: string;
- /**
- * Logger sink for Playwright logging. Optional.
- */
- logger?: Logger;
+ /**
+ * Unix time in seconds.
+ */
+ expires: number;
- /**
- * Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
- * on. Defaults to 0.
- */
- slowMo?: number;
+ httpOnly: boolean;
- /**
- * Maximum time in milliseconds to wait for the connection to be established. Defaults to `30000` (30 seconds). Pass
- * `0` to disable timeout.
- */
- timeout?: number;
-}
+ secure: boolean;
-export interface ConnectOptions {
- /**
- * This option exposes network available on the connecting client to the browser being connected to. Consists of a
- * list of rules separated by comma.
- *
- * Available rules:
- * 1. Hostname pattern, for example: `example.com`, `*.org:99`, `x.*.y.com`, `*foo.org`.
- * 1. IP literal, for example: `127.0.0.1`, `0.0.0.0:99`, `[::1]`, `[0:0::1]:99`.
- * 1. `<loopback>` that matches local loopback interfaces: `localhost`, `*.localhost`, `127.0.0.1`, `[::1]`.
- *
- * Some common examples:
- * 1. `"*"` to expose all network.
- * 1. `"<loopback>"` to expose localhost network.
- * 1. `"*.test.internal-domain,*.staging.internal-domain,<loopback>"` to expose test/staging deployments and
- * localhost.
- */
- exposeNetwork?: string;
+ /**
+ * sameSite flag
+ */
+ sameSite: "Strict"|"Lax"|"None";
+ }>;
- /**
- * Additional HTTP headers to be sent with web socket connect request. Optional.
- */
- headers?: { [key: string]: string; };
+ /**
+ * localStorage to set for context
+ */
+ origins: Array<{
+ origin: string;
- /**
- * Logger sink for Playwright logging. Optional.
- */
- logger?: Logger;
+ localStorage: Array<{
+ name: string;
- /**
- * Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going
- * on. Defaults to 0.
- */
- slowMo?: number;
+ value: string;
+ }>;
+ }>;
+ };
/**
- * Maximum time in milliseconds to wait for the connection to be established. Defaults to `0` (no timeout).
+ * If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on
+ * selectors that imply single target DOM element will throw when more than one element matches the selector. This
+ * option does not affect any Locator APIs (Locators are always strict). Defaults to `false`. See {@link Locator} to
+ * learn more about the strict mode.
*/
- timeout?: number;
-}
+ strictSelectors?: boolean;
-export interface LocatorScreenshotOptions {
/**
- * When set to `"disabled"`, stops CSS animations, CSS transitions and Web Animations. Animations get different
- * treatment depending on their duration:
- * - finite animations are fast-forwarded to completion, so they'll fire `transitionend` event.
- * - infinite animations are canceled to initial state, and then played over after the screenshot.
- *
- * Defaults to `"allow"` that leaves animations untouched.
+ * Changes the timezone of the context. See
+ * [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1)
+ * for a list of supported timezone IDs. Defaults to the system timezone.
*/
- animations?: "disabled"|"allow";
+ timezoneId?: string;
/**
- * When set to `"hide"`, screenshot will hide text caret. When set to `"initial"`, text caret behavior will not be
- * changed. Defaults to `"hide"`.
+ * Specific user agent to use in this context.
*/
- caret?: "hide"|"initial";
+ userAgent?: string;
/**
- * Specify locators that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink
- * box `#FF00FF` (customized by `maskColor`) that completely covers its bounding box.
+ * @deprecated Use `recordVideo` instead.
*/
- mask?: Array<Locator>;
+ videoSize?: {
+ /**
+ * Video frame width.
+ */
+ width: number;
- /**
- * Specify the color of the overlay box for masked elements, in
- * [CSS color format](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). Default color is pink `#FF00FF`.
- */
- maskColor?: string;
+ /**
+ * Video frame height.
+ */
+ height: number;
+ };
/**
- * Hides default white background and allows capturing screenshots with transparency. Not applicable to `jpeg` images.
- * Defaults to `false`.
+ * @deprecated Use `recordVideo` instead.
*/
- omitBackground?: boolean;
+ videosPath?: string;
/**
- * The file path to save the image to. The screenshot type will be inferred from file extension. If `path` is a
- * relative path, then it is resolved relative to the current working directory. If no path is provided, the image
- * won't be saved to the disk.
+ * Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use `null` to disable the consistent
+ * viewport emulation. Learn more about [viewport emulation](https://playwright.dev/docs/emulation#viewport).
+ *
+ * **NOTE** The `null` value opts out from the default presets, makes viewport depend on the host window size defined
+ * by the operating system. It makes the execution of the tests non-deterministic.
*/
- path?: string;
+ viewport?: null|ViewportSize;
+}
+export interface ViewportSize {
/**
- * The quality of the image, between 0-100. Not applicable to `png` images.
+ * page width in pixels.
*/
- quality?: number;
+ width: number;
/**
- * When set to `"css"`, screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this
- * will keep screenshots small. Using `"device"` option will produce a single pixel per each device pixel, so
- * screenshots of high-dpi devices will be twice as large or even larger.
- *
- * Defaults to `"device"`.
+ * page height in pixels.
*/
- scale?: "css"|"device";
+ height: number;
+}
- /**
- * Text of the stylesheet to apply while making the screenshot. This is where you can hide dynamic elements, make
- * elements invisible or change their properties to help you creating repeatable screenshots. This stylesheet pierces
- * the Shadow DOM and applies to the inner frames.
- */
- style?: string;
+export interface HTTPCredentials {
+ username: string;
+
+ password: string;
/**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
+ * Restrain sending http credentials on specific origin (scheme://host:port).
*/
- timeout?: number;
+ origin?: string;
/**
- * Specify screenshot type, defaults to `png`.
+ * This option only applies to the requests sent from corresponding {@link APIRequestContext} and does not affect
+ * requests sent from the browser. `'always'` - `Authorization` header with basic authentication credentials will be
+ * sent with the each API request. `'unauthorized` - the credentials are only sent when 401 (Unauthorized) response
+ * with `WWW-Authenticate` header is received. Defaults to `'unauthorized'`.
*/
- type?: "png"|"jpeg";
+ send?: "unauthorized"|"always";
}
-interface ElementHandleWaitForSelectorOptions {
+export interface Geolocation {
/**
- * Defaults to `'visible'`. Can be either:
- * - `'attached'` - wait for element to be present in DOM.
- * - `'detached'` - wait for element to not be present in DOM.
- * - `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element
- * without any content or with `display:none` has an empty bounding box and is not considered visible.
- * - `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or
- * `visibility:hidden`. This is opposite to the `'visible'` option.
+ * Latitude between -90 and 90.
*/
- state?: "attached"|"detached"|"visible"|"hidden";
+ latitude: number;
/**
- * When true, the call requires selector to resolve to a single element. If given selector resolves to more than one
- * element, the call throws an exception.
+ * Longitude between -180 and 180.
*/
- strict?: boolean;
+ longitude: number;
/**
- * Maximum time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout`
- * option in the config, or by using the
- * [browserContext.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout)
- * or [page.setDefaultTimeout(timeout)](https://playwright.dev/docs/api/class-page#page-set-default-timeout) methods.
+ * Non-negative accuracy value. Defaults to `0`.
*/
- timeout?: number;
+ accuracy?: number;
}
export interface Cookie {
diff --git a/tests/library/events/listener-count.spec.ts b/tests/library/events/listener-count.spec.ts
index 8fae8cdfad..d8aaf867a3 100644
--- a/tests/library/events/listener-count.spec.ts
+++ b/tests/library/events/listener-count.spec.ts
@@ -20,7 +20,6 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
-import events from 'events';
import { EventEmitter } from '../../../packages/playwright-core/lib/client/eventEmitter';
import { test, expect } from '@playwright/test';
@@ -32,7 +31,6 @@ test('Listener count test', () => {
// Allow any type
emitter.on(123, () => {});
- expect(events.listenerCount(emitter, 'foo')).toEqual(2);
expect(emitter.listenerCount('foo')).toEqual(2);
expect(emitter.listenerCount('bar')).toEqual(0);
expect(emitter.listenerCount('baz')).toEqual(1);
diff --git a/tests/library/events/listeners.spec.ts b/tests/library/events/listeners.spec.ts
index 4553ed92aa..86803af178 100644
--- a/tests/library/events/listeners.spec.ts
+++ b/tests/library/events/listeners.spec.ts
@@ -40,7 +40,7 @@ test('EventEmitter listeners with one listener', () => {
expect(listeners).toHaveLength(1);
expect(listeners[0]).toEqual(listener);
- ee.removeAllListeners('foo');
+ void ee.removeAllListeners('foo');
expect<Array<any>>(ee.listeners('foo')).toHaveLength(0);
expect(Array.isArray(fooListeners)).toBeTruthy();
diff --git a/tests/library/events/modify-in-emit.spec.ts b/tests/library/events/modify-in-emit.spec.ts
index 1d832aa650..25937977f4 100644
--- a/tests/library/events/modify-in-emit.spec.ts
+++ b/tests/library/events/modify-in-emit.spec.ts
@@ -72,7 +72,7 @@ test('add and remove listeners', () => {
e.on('foo', callback1);
e.on('foo', callback2);
expect(e.listeners('foo')).toHaveLength(2);
- e.removeAllListeners('foo');
+ void e.removeAllListeners('foo');
expect(e.listeners('foo')).toHaveLength(0);
});
diff --git a/tests/library/events/remove-all-listeners-wait.spec.ts b/tests/library/events/remove-all-listeners-wait.spec.ts
new file mode 100644
index 0000000000..1f8dcc8dd0
--- /dev/null
+++ b/tests/library/events/remove-all-listeners-wait.spec.ts
@@ -0,0 +1,80 @@
+/**
+ * Copyright 2018 Google Inc. All rights reserved.
+ * Modifications copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { ManualPromise } from '../../../packages/playwright-core/lib/utils/manualPromise';
+import { EventEmitter } from '../../../packages/playwright-core/lib/client/eventEmitter';
+import { test, expect } from '@playwright/test';
+
+test('should not throw with ignoreErrors', async () => {
+ const ee = new EventEmitter();
+ const releaseHandler = new ManualPromise();
+ ee.on('console', async () => {
+ await releaseHandler;
+ throw new Error('Error in console handler');
+ });
+ ee.emit('console');
+ await ee.removeAllListeners('console', { behavior: 'ignoreErrors' });
+ releaseHandler.resolve();
+});
+
+test('should wait', async () => {
+ const ee = new EventEmitter();
+ const releaseHandler = new ManualPromise();
+ let value = 0;
+ ee.on('console', async () => {
+ await releaseHandler;
+ value = 42;
+ });
+ ee.emit('console');
+ const removePromise = ee.removeAllListeners('console', { behavior: 'wait' });
+ releaseHandler.resolve();
+ await removePromise;
+ expect(value).toBe(42);
+});
+
+test('should wait all', async () => {
+ const ee = new EventEmitter();
+ const releaseHandler = new ManualPromise();
+ const values = [];
+ ee.on('a', async () => {
+ await releaseHandler;
+ values.push(42);
+ });
+ ee.on('b', async () => {
+ await releaseHandler;
+ values.push(43);
+ });
+ ee.emit('a');
+ ee.emit('b');
+ const removePromise = ee.removeAllListeners(undefined, { behavior: 'wait' });
+ releaseHandler.resolve();
+ await removePromise;
+ expect(values).toEqual([42, 43]);
+});
+
+test('wait should throw', async () => {
+ const ee = new EventEmitter();
+ const releaseHandler = new ManualPromise();
+ ee.on('console', async () => {
+ await releaseHandler;
+ throw new Error('Error in handler');
+ });
+ ee.emit('console');
+ const removePromise = ee.removeAllListeners('console', { behavior: 'wait' });
+ releaseHandler.resolve();
+ await expect(removePromise).rejects.toThrow('Error in handler');
+});
diff --git a/tests/library/events/remove-all-listeners.spec.ts b/tests/library/events/remove-all-listeners.spec.ts
index 116b9e768c..275c0700ff 100644
--- a/tests/library/events/remove-all-listeners.spec.ts
+++ b/tests/library/events/remove-all-listeners.spec.ts
@@ -58,8 +58,8 @@ test('listeners', () => {
const barListeners = ee.listeners('bar');
const bazListeners = ee.listeners('baz');
ee.on('removeListener', expectWrapper(['bar', 'baz', 'baz']));
- ee.removeAllListeners('bar');
- ee.removeAllListeners('baz');
+ void ee.removeAllListeners('bar');
+ void ee.removeAllListeners('baz');
let listeners = ee.listeners('foo');
expect(Array.isArray(listeners)).toBeTruthy();
@@ -91,7 +91,7 @@ test('removeAllListeners removes all listeners', () => {
ee.on('bar', () => { });
ee.on('removeListener', expectWrapper(['foo', 'bar', 'removeListener']));
ee.on('removeListener', expectWrapper(['foo', 'bar']));
- ee.removeAllListeners();
+ void ee.removeAllListeners();
let listeners = ee.listeners('foo');
expect(Array.isArray(listeners)).toBeTruthy();
@@ -120,7 +120,7 @@ test('listener count after removeAllListeners', () => {
ee.on('baz', () => { });
ee.on('baz', () => { });
expect(ee.listeners('baz').length).toEqual(expectLength + 1);
- ee.removeAllListeners('baz');
+ void ee.removeAllListeners('baz');
expect(ee.listeners('baz').length).toEqual(0);
});
diff --git a/tests/library/events/subclass.spec.ts b/tests/library/events/subclass.spec.ts
index 37b548a92a..3852657b8d 100644
--- a/tests/library/events/subclass.spec.ts
+++ b/tests/library/events/subclass.spec.ts
@@ -28,7 +28,7 @@ class MyEE extends EventEmitter {
super();
this.once(1, cb);
this.emit(1);
- this.removeAllListeners();
+ void this.removeAllListeners();
}
}
diff --git a/tests/library/events/symbols.spec.ts b/tests/library/events/symbols.spec.ts
index 7efb00f189..1c143def37 100644
--- a/tests/library/events/symbols.spec.ts
+++ b/tests/library/events/symbols.spec.ts
@@ -34,7 +34,7 @@ test('should support symbols', () => {
ee.emit(foo);
- ee.removeAllListeners();
+ void ee.removeAllListeners();
expect(ee.listeners(foo).length).toEqual(0);
ee.on(foo, listener);
diff --git a/tests/page/page-listeners.spec.ts b/tests/page/page-listeners.spec.ts
new file mode 100644
index 0000000000..c22be64553
--- /dev/null
+++ b/tests/page/page-listeners.spec.ts
@@ -0,0 +1,67 @@
+/**
+ * Copyright 2018 Google Inc. All rights reserved.
+ * Modifications copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { ManualPromise } from '../../packages/playwright-core/lib/utils/manualPromise';
+import { test as it, expect } from './pageTest';
+
+// This test is mostly for type checking, the actual tests are in the library/events.
+
+it('should not throw with ignoreErrors', async ({ page }) => {
+ const reachedHandler = new ManualPromise();
+ const releaseHandler = new ManualPromise();
+ page.on('console', async () => {
+ reachedHandler.resolve();
+ await releaseHandler;
+ throw new Error('Error in console handler');
+ });
+ await page.evaluate('console.log(1)');
+ await reachedHandler;
+ await page.removeAllListeners('console', { behavior: 'ignoreErrors' });
+ releaseHandler.resolve();
+ await page.waitForTimeout(1000);
+});
+
+it('should wait', async ({ page }) => {
+ const reachedHandler = new ManualPromise();
+ const releaseHandler = new ManualPromise();
+ let value = 0;
+ page.on('console', async () => {
+ reachedHandler.resolve();
+ value = 42;
+ });
+ await page.evaluate('console.log(1)');
+ await reachedHandler;
+ const removePromise = page.removeAllListeners('console', { behavior: 'wait' });
+ releaseHandler.resolve();
+ await removePromise;
+ expect(value).toBe(42);
+});
+
+it('wait should throw', async ({ page }) => {
+ const reachedHandler = new ManualPromise();
+ const releaseHandler = new ManualPromise();
+ page.on('console', async () => {
+ reachedHandler.resolve();
+ await releaseHandler;
+ throw new Error('Error in handler');
+ });
+ await page.evaluate('console.log(1)');
+ await reachedHandler;
+ const removePromise = page.removeAllListeners('console', { behavior: 'wait' });
+ releaseHandler.resolve();
+ await expect(removePromise).rejects.toThrow('Error in handler');
+});
diff --git a/utils/doclint/missingDocs.js b/utils/doclint/missingDocs.js
index 8042bc4222..7fffc156dc 100644
--- a/utils/doclint/missingDocs.js
+++ b/utils/doclint/missingDocs.js
@@ -56,7 +56,7 @@ module.exports = function lint(documentation, jsSources, apiFileName) {
continue;
}
for (const member of cls.membersArray) {
- if (member.kind === 'event')
+ if (member.kind === 'event' || member.alias === 'removeAllListeners')
continue;
const params = methods.get(member.alias);
if (!params) {
diff --git a/utils/generate_types/overrides.d.ts b/utils/generate_types/overrides.d.ts
index 1f90713e92..578602959a 100644
--- a/utils/generate_types/overrides.d.ts
+++ b/utils/generate_types/overrides.d.ts
@@ -62,6 +62,9 @@ export interface Page {
exposeBinding(name: string, playwrightBinding: (source: BindingSource, arg: JSHandle) => any, options: { handle: true }): Promise<void>;
exposeBinding(name: string, playwrightBinding: (source: BindingSource, ...args: any[]) => any, options?: { handle?: boolean }): Promise<void>;
+
+ removeAllListeners(type?: string): this;
+ removeAllListeners(type: string | undefined, options: { behavior?: 'wait'|'ignoreErrors'|'default' }): Promise<void>;
}
export interface Frame {
@@ -101,6 +104,14 @@ export interface BrowserContext {
exposeBinding(name: string, playwrightBinding: (source: BindingSource, ...args: any[]) => any, options?: { handle?: boolean }): Promise<void>;
addInitScript<Arg>(script: PageFunction<Arg, any> | { path?: string, content?: string }, arg?: Arg): Promise<void>;
+
+ removeAllListeners(type?: string): this;
+ removeAllListeners(type: string | undefined, options: { behavior?: 'wait'|'ignoreErrors'|'default' }): Promise<void>;
+}
+
+export interface Browser {
+ removeAllListeners(type?: string): this;
+ removeAllListeners(type: string | undefined, options: { behavior?: 'wait'|'ignoreErrors'|'default' }): Promise<void>;
}
export interface Worker {