Skip to content

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

docs: pretty-print api.md (#4588)

Pavel Feldman0eb6f856175c
diff --git a/docs-src/api-body.md b/docs-src/api-body.md
index 25c2343790..8b8f8c95af 100644
--- a/docs-src/api-body.md
+++ b/docs-src/api-body.md
@@ -1,10 +1,11 @@
### class: Browser
-
* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
-A Browser is created when Playwright connects to a browser instance, either through [`browserType.launch`](#browsertypelaunchoptions) or [`browserType.connect`](#browsertypeconnectoptions).
+A Browser is created when Playwright connects to a browser instance, either through
+[`browserType.launch`](#browsertypelaunchoptions) or [`browserType.connect`](#browsertypeconnectoptions).
An example of using a [Browser] to create a [Page]:
+
```js
const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
@@ -16,7 +17,10 @@ const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
})();
```
-See [ChromiumBrowser], [FirefoxBrowser] and [WebKitBrowser] for browser-specific features. Note that [browserType.connect(options)](#browsertypeconnectoptions) and [browserType.launch([options])](#browsertypelaunchoptions) always return a specific browser instance, based on the browser being connected to or launched.
+See [ChromiumBrowser], [FirefoxBrowser] and [WebKitBrowser] for browser-specific features. Note that
+[browserType.connect(options)](#browsertypeconnectoptions) and
+[browserType.launch([options])](#browsertypelaunchoptions) always return a specific browser instance, based on the
+browser being connected to or launched.
<!-- GEN:toc -->
- [event: 'disconnected'](#event-disconnected)
@@ -29,6 +33,7 @@ See [ChromiumBrowser], [FirefoxBrowser] and [WebKitBrowser] for browser-specific
<!-- GEN:stop -->
#### event: 'disconnected'
+
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`](#browserclose) method was called.
@@ -36,17 +41,18 @@ Emitted when Browser gets disconnected from the browser application. This might
#### browser.close()
- returns: <[Promise]>
-In case this browser is obtained using [browserType.launch](#browsertypelaunchoptions), closes the browser and all of its pages (if any were opened).
+In case this browser is obtained using [browserType.launch](#browsertypelaunchoptions), closes the browser and all of
+its pages (if any were opened).
-In case this browser is obtained using [browserType.connect](#browsertypeconnectoptions), clears all created contexts belonging to this browser and disconnects from the browser server.
+In case this browser is obtained using [browserType.connect](#browsertypeconnectoptions), clears all created contexts
+belonging to this browser and disconnects from the browser server.
The [Browser] object itself is considered to be disposed and cannot be used anymore.
#### browser.contexts()
- returns: <[Array]<[BrowserContext]>>
-Returns an array of all open browser contexts. In a newly created browser, this will return zero
-browser contexts.
+Returns an array of all open browser contexts. In a newly created browser, this will return zero browser contexts.
```js
const browser = await pw.webkit.launch();
@@ -90,16 +96,16 @@ Creates a new browser context. It won't share cookies/cache with other browser c
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](#browsernewcontextoptions) followed by the [browserContext.newPage](#browsercontextnewpage) to control their exact life times.
+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](#browsernewcontextoptions) followed by the
+[browserContext.newPage](#browsercontextnewpage) to control their exact life times.
#### browser.version()
-
- returns: <[string]>
Returns the browser version.
### class: BrowserContext
-
* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
BrowserContexts provide a way to operate multiple independent browser sessions.
@@ -107,8 +113,8 @@ BrowserContexts provide a way to operate multiple independent browser sessions.
If a page opens another page, e.g. with a `window.open` call, the popup will belong to the parent page's browser
context.
-Playwright allows creation of "incognito" browser contexts with `browser.newContext()` method.
-"Incognito" browser contexts don't write any browsing data to disk.
+Playwright allows creation of "incognito" browser contexts with `browser.newContext()` method. "Incognito" browser
+contexts don't write any browsing data to disk.
```js
// Create a new incognito browser context
@@ -157,9 +163,13 @@ Emitted when Browser context gets closed. This might happen because of one of th
#### event: 'page'
- <[Page]>
-The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event will also fire for popup pages. See also [`Page.on('popup')`](#event-popup) to receive events about popups relevant to a specific page.
+The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event will
+also fire for popup pages. See also [`Page.on('popup')`](#event-popup) to receive events about popups relevant to a
+specific page.
-The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a popup with `window.open('http://example.com')`, this event will fire when the network request to "http://example.com" is done and its response has started loading in the popup.
+The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
+popup with `window.open('http://example.com')`, this event will fire when the network request to "http://example.com" is
+done and its response has started loading in the popup.
```js
const [page] = await Promise.all([
@@ -169,7 +179,8 @@ const [page] = await Promise.all([
console.log(await page.evaluate('location.href'));
```
-> **NOTE** Use [`page.waitForLoadState([state[, options]])`](#pagewaitforloadstatestate-options) to wait until the page gets to a particular state (you should not need it in most cases).
+> **NOTE** Use [`page.waitForLoadState([state[, options]])`](#pagewaitforloadstatestate-options) to wait until the page
+gets to a particular state (you should not need it in most cases).
#### browserContext.addCookies(cookies)
- `cookies` <[Array]<[Object]>>
@@ -199,7 +210,8 @@ Adds a script which would be evaluated in one of the following scenarios:
- Whenever a page is created in the browser context or is navigated.
- Whenever a child frame is attached or navigated in any page in the browser context. In this case, the script is evaluated in the context of the newly attached frame.
-The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed `Math.random`.
+The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend
+the JavaScript environment, e.g. to seed `Math.random`.
An example of overriding `Math.random` before the page loads:
@@ -215,7 +227,9 @@ await browserContext.addInitScript({
});
```
-> **NOTE** The order of evaluation of multiple scripts installed via [browserContext.addInitScript(script[, arg])](#browsercontextaddinitscriptscript-arg) and [page.addInitScript(script[, arg])](#pageaddinitscriptscript-arg) is not defined.
+> **NOTE** The order of evaluation of multiple scripts installed via [browserContext.addInitScript(script[,
+arg])](#browsercontextaddinitscriptscript-arg) and [page.addInitScript(script[, arg])](#pageaddinitscriptscript-arg) is
+not defined.
#### browserContext.browser()
- returns: <[null]|[Browser]> Returns the browser instance of the context. If it was launched as a persistent context null gets returned.
@@ -240,8 +254,7 @@ context.clearPermissions();
#### browserContext.close()
- returns: <[Promise]>
-Closes the browser context. All the pages that belong to the browser context
-will be closed.
+Closes the browser context. All the pages that belong to the browser context will be closed.
> **NOTE** the default browser context cannot be closed.
@@ -257,8 +270,8 @@ will be closed.
- `secure` <[boolean]>
- `sameSite` <"Strict"|"Lax"|"None">
-If no URLs are specified, this method returns all cookies.
-If URLs are specified, only cookies that affect those URLs are returned.
+If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs
+are returned.
#### browserContext.exposeBinding(name, playwrightBinding[, options])
- `name` <[string]> Name of the function on the window object.
@@ -267,16 +280,18 @@ If URLs are specified, only cookies that affect those URLs are returned.
- `handle` <[boolean]> Whether to pass the argument as a handle, instead of passing by value. When passing a handle, only one argument is supported. When passing by value, multiple arguments are supported.
- returns: <[Promise]>
-The method adds a function called `name` on the `window` object of every frame in every page in the context.
-When called, the function executes `playwrightBinding` in Node.js and returns a [Promise] which resolves to the return value of `playwrightBinding`.
-If the `playwrightBinding` returns a [Promise], it will be awaited.
+The method adds a function called `name` on the `window` object of every frame in every page in the context. When
+called, the function executes `playwrightBinding` in Node.js and returns a [Promise] which resolves to the return value
+of `playwrightBinding`. If the `playwrightBinding` returns a [Promise], it will be awaited.
-The first argument of the `playwrightBinding` function contains information about the caller:
-`{ browserContext: BrowserContext, page: Page, frame: Frame }`.
+The first argument of the `playwrightBinding` function contains information about the caller: `{ browserContext:
+BrowserContext, page: Page, frame: Frame }`.
-See [page.exposeBinding(name, playwrightBinding)](#pageexposebindingname-playwrightbinding-options) for page-only version.
+See [page.exposeBinding(name, playwrightBinding)](#pageexposebindingname-playwrightbinding-options) for page-only
+version.
An example of exposing page URL to all frames in all pages in the context:
+
```js
const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
@@ -299,6 +314,7 @@ const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
```
An example of passing an element handle:
+
```js
await context.exposeBinding('clicked', async (source, element) => {
console.log(await element.textContent());
@@ -317,14 +333,16 @@ await page.setContent(`
- `playwrightFunction` <[function]> Callback function that will be called in the Playwright's context.
- returns: <[Promise]>
-The method adds a function called `name` on the `window` object of every frame in every page in the context.
-When called, the function executes `playwrightFunction` in Node.js and returns a [Promise] which resolves to the return value of `playwrightFunction`.
+The method adds a function called `name` on the `window` object of every frame in every page in the context. When
+called, the function executes `playwrightFunction` in Node.js and returns a [Promise] which resolves to the return value
+of `playwrightFunction`.
If the `playwrightFunction` returns a [Promise], it will be awaited.
See [page.exposeFunction(name, playwrightFunction)](#pageexposefunctionname-playwrightfunction) for page-only version.
An example of adding an `md5` function to all pages in the context:
+
```js
const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
const crypto = require('crypto');
@@ -349,27 +367,28 @@ const crypto = require('crypto');
#### browserContext.grantPermissions(permissions[][, options])
- `permissions` <[Array]<[string]>> A permission or an array of permissions to grant. Permissions can be one of the following values:
- - `'geolocation'`
- - `'midi'`
- - `'midi-sysex'` (system-exclusive midi)
- - `'notifications'`
- - `'push'`
- - `'camera'`
- - `'microphone'`
- - `'background-sync'`
- - `'ambient-light-sensor'`
- - `'accelerometer'`
- - `'gyroscope'`
- - `'magnetometer'`
- - `'accessibility-events'`
- - `'clipboard-read'`
- - `'clipboard-write'`
- - `'payment-handler'`
+ - `'geolocation'`
+ - `'midi'`
+ - `'midi-sysex'` (system-exclusive midi)
+ - `'notifications'`
+ - `'push'`
+ - `'camera'`
+ - `'microphone'`
+ - `'background-sync'`
+ - `'ambient-light-sensor'`
+ - `'accelerometer'`
+ - `'gyroscope'`
+ - `'magnetometer'`
+ - `'accessibility-events'`
+ - `'clipboard-read'`
+ - `'clipboard-write'`
+ - `'payment-handler'`
- `options` <[Object]>
- `origin` <[string]> The [origin] to grant permissions to, e.g. "https://example.com".
- returns: <[Promise]>
-Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if specified.
+Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if
+specified.
#### browserContext.newPage()
- returns: <[Promise]<[Page]>>
@@ -384,8 +403,8 @@ Creates a new page in the browser context.
- `handler` <[function]\([Route], [Request]\)> handler function to route the request.
- returns: <[Promise]>
-Routing provides the capability to modify network requests that are made by any page in the browser context.
-Once route is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
+Routing provides the capability to modify network requests that are made by any page in the browser context. Once route
+is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
An example of a naïve handler that aborts all image requests:
@@ -407,7 +426,8 @@ await page.goto('https://example.com');
await browser.close();
```
-Page routes (set up with [page.route(url, handler)](#pagerouteurl-handler)) take precedence over browser context routes when request matches both handlers.
+Page routes (set up with [page.route(url, handler)](#pagerouteurl-handler)) take precedence over browser context routes
+when request matches both handlers.
> **NOTE** Enabling routing disables http cache.
@@ -422,20 +442,27 @@ This setting will change the default maximum navigation time for the following m
- [page.setContent(html[, options])](#pagesetcontenthtml-options)
- [page.waitForNavigation([options])](#pagewaitfornavigationoptions)
-> **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout) and [`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout) take priority over [`browserContext.setDefaultNavigationTimeout`](#browsercontextsetdefaultnavigationtimeouttimeout).
+> **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout) and
+[`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout) take priority over
+[`browserContext.setDefaultNavigationTimeout`](#browsercontextsetdefaultnavigationtimeouttimeout).
#### browserContext.setDefaultTimeout(timeout)
- `timeout` <[number]> Maximum time in milliseconds
This setting will change the default maximum time for all the methods accepting `timeout` option.
-> **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout), [`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout) and [`browserContext.setDefaultNavigationTimeout`](#browsercontextsetdefaultnavigationtimeouttimeout) take priority over [`browserContext.setDefaultTimeout`](#browsercontextsetdefaulttimeouttimeout).
+> **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout),
+[`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout) and
+[`browserContext.setDefaultNavigationTimeout`](#browsercontextsetdefaultnavigationtimeouttimeout) take priority over
+[`browserContext.setDefaultTimeout`](#browsercontextsetdefaulttimeouttimeout).
#### browserContext.setExtraHTTPHeaders(headers)
- `headers` <[Object]<[string], [string]>> An object containing additional HTTP headers to be sent with every request. All header values must be strings.
- returns: <[Promise]>
-The extra HTTP headers will be sent with every request initiated by any page in the context. These headers are merged with page-specific extra HTTP headers set with [page.setExtraHTTPHeaders()](#pagesetextrahttpheadersheaders). If page overrides a particular header, page-specific header value will be used instead of the browser context header value.
+The extra HTTP headers will be sent with every request initiated by any page in the context. These headers are merged
+with page-specific extra HTTP headers set with [page.setExtraHTTPHeaders()](#pagesetextrahttpheadersheaders). If page
+overrides a particular header, page-specific header value will be used instead of the browser context header value.
> **NOTE** `browserContext.setExtraHTTPHeaders` does not guarantee the order of headers in the outgoing requests.
@@ -452,7 +479,8 @@ Sets the context's geolocation. Passing `null` or `undefined` emulates position
await browserContext.setGeolocation({latitude: 59.95, longitude: 30.31667});
```
-> **NOTE** Consider using [browserContext.grantPermissions](#browsercontextgrantpermissionspermissions-options) to grant permissions for the browser context pages to read its geolocation.
+> **NOTE** Consider using [browserContext.grantPermissions](#browsercontextgrantpermissionspermissions-options) to grant
+permissions for the browser context pages to read its geolocation.
#### browserContext.setHTTPCredentials(httpCredentials)
- `httpCredentials` <[null]|[Object]>
@@ -462,7 +490,9 @@ await browserContext.setGeolocation({latitude: 59.95, longitude: 30.31667});
Provide credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
-> **NOTE** Browsers may cache credentials after successful authentication. Passing different credentials or passing `null` to disable authentication will be unreliable. To remove or replace credentials, create a new browser context instead.
+> **NOTE** Browsers may cache credentials after successful authentication. Passing different credentials or passing
+`null` to disable authentication will be unreliable. To remove or replace credentials, create a new browser context
+instead.
#### browserContext.setOffline(offline)
- `offline` <[boolean]> Whether to emulate network being offline for the browser context.
@@ -492,7 +522,8 @@ Returns storage state for this browser context, contains current cookies and loc
- `handler` <[function]\([Route], [Request]\)> Handler function used to register a routing with [browserContext.route(url, handler)](#browsercontextrouteurl-handler).
- returns: <[Promise]>
-Removes a route created with [browserContext.route(url, handler)](#browsercontextrouteurl-handler). When `handler` is not specified, removes all routes for the `url`.
+Removes a route created with [browserContext.route(url, handler)](#browsercontextrouteurl-handler). When `handler` is
+not specified, removes all routes for the `url`.
#### browserContext.waitForEvent(event[, optionsOrPredicate])
- `event` <[string]> Event name, same one would pass into `browserContext.on(event)`.
@@ -501,8 +532,8 @@ Removes a route created with [browserContext.route(url, handler)](#browsercontex
- %%-wait-for-timeout-%%
- returns: <[Promise]<[Object]>> Promise which resolves to the event data value.
-Waits for event to fire and passes its value into the predicate function. Resolves when the predicate returns truthy value. Will throw an error if the context closes before the event
-is fired.
+Waits for event to fire and passes its value into the predicate function. Resolves when the predicate returns truthy
+value. Will throw an error if the context closes before the event is fired.
```js
const context = await browser.newContext();
@@ -510,12 +541,14 @@ await context.grantPermissions(['geolocation']);
```
### class: Page
-
* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
-Page provides methods to interact with a single tab in a [Browser], or an [extension background page](https://developer.chrome.com/extensions/background_pages) in Chromium. One [Browser] instance might have multiple [Page] instances.
+Page provides methods to interact with a single tab in a [Browser], or an [extension background
+page](https://developer.chrome.com/extensions/background_pages) in Chromium. One [Browser] instance might have multiple
+[Page] instances.
This example creates a page, navigates it to a URL, and then saves a screenshot:
+
```js
const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
@@ -529,9 +562,12 @@ const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
})();
```
-The Page class emits various events (described below) which can be handled using any of Node's native [`EventEmitter`](https://nodejs.org/api/events.html#events_class_eventemitter) methods, such as `on`, `once` or `removeListener`.
+The Page class emits various events (described below) which can be handled using any of Node's native
+[`EventEmitter`](https://nodejs.org/api/events.html#events_class_eventemitter) methods, such as `on`, `once` or
+`removeListener`.
This example logs a message for a single page `load` event:
+
```js
page.once('load', () => console.log('Page loaded!'));
```
@@ -645,11 +681,13 @@ Emitted when the page closes.
#### event: 'console'
- <[ConsoleMessage]>
-Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`. Also emitted if the page throws an error or a warning.
+Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`. Also
+emitted if the page throws an error or a warning.
The arguments passed into `console.log` appear as arguments on the event handler.
An example of handling `console` event:
+
```js
page.on('console', msg => {
for (let i = 0; i < msg.args().length; ++i)
@@ -660,9 +698,11 @@ page.evaluate(() => console.log('hello', 5, {foo: 'bar'}));
#### event: 'crash'
-Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page crashes, ongoing and subsequent operations will throw.
+Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page crashes,
+ongoing and subsequent operations will throw.
The most common way to deal with crashes is to catch an exception:
+
```js
try {
// Crash might happen during a click.
@@ -674,7 +714,8 @@ try {
}
```
-However, when manually listening to events, it might be useful to avoid stalling when the page crashes. In this case, handling `crash` event helps:
+However, when manually listening to events, it might be useful to avoid stalling when the page crashes. In this case,
+handling `crash` event helps:
```js
await new Promise((resolve, reject) => {
@@ -689,23 +730,30 @@ await new Promise((resolve, reject) => {
#### event: 'dialog'
- <[Dialog]>
-Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Playwright can respond to the dialog via [Dialog]'s [accept](#dialogacceptprompttext) or [dismiss](#dialogdismiss) methods.
+Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Playwright can respond
+to the dialog via [Dialog]'s [accept](#dialogacceptprompttext) or [dismiss](#dialogdismiss) methods.
#### event: 'domcontentloaded'
-Emitted when the JavaScript [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) event is dispatched.
+Emitted when the JavaScript [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded)
+event is dispatched.
#### event: 'download'
- <[Download]>
-Emitted when attachment download started. User can access basic file operations on downloaded content via the passed [Download] instance.
+Emitted when attachment download started. User can access basic file operations on downloaded content via the passed
+[Download] instance.
-> **NOTE** Browser context **must** be created with the `acceptDownloads` set to `true` when user needs access to the downloaded content. If `acceptDownloads` is not set or set to `false`, download events are emitted, but the actual download is not performed and user has no access to the downloaded files.
+> **NOTE** Browser context **must** be created with the `acceptDownloads` set to `true` when user needs access to the
+downloaded content. If `acceptDownloads` is not set or set to `false`, download events are emitted, but the actual
+download is not performed and user has no access to the downloaded files.
#### event: 'filechooser'
- <[FileChooser]>
-Emitted when a file chooser is supposed to appear, such as after clicking the `<input type=file>`. Playwright can respond to it via setting the input files using [`fileChooser.setFiles`](#filechoosersetfilesfiles-options) that can be uploaded after that.
+Emitted when a file chooser is supposed to appear, such as after clicking the `<input type=file>`. Playwright can
+respond to it via setting the input files using [`fileChooser.setFiles`](#filechoosersetfilesfiles-options) that can be
+uploaded after that.
```js
page.on('filechooser', async (fileChooser) => {
@@ -740,9 +788,12 @@ Emitted when an uncaught exception happens within the page.
#### event: 'popup'
- <[Page]> Page corresponding to "popup" window
-Emitted when the page opens a new tab or window. This event is emitted in addition to the [`browserContext.on('page')`](#event-page), but only for popups relevant to this page.
+Emitted when the page opens a new tab or window. This event is emitted in addition to the
+[`browserContext.on('page')`](#event-page), but only for popups relevant to this page.
-The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a popup with `window.open('http://example.com')`, this event will fire when the network request to "http://example.com" is done and its response has started loading in the popup.
+The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
+popup with `window.open('http://example.com')`, this event will fire when the network request to "http://example.com" is
+done and its response has started loading in the popup.
```js
const [popup] = await Promise.all([
@@ -752,30 +803,35 @@ const [popup] = await Promise.all([
console.log(await popup.evaluate('location.href'));
```
-> **NOTE** Use [`page.waitForLoadState([state[, options]])`](#pagewaitforloadstatestate-options) to wait until the page gets to a particular state (you should not need it in most cases).
+> **NOTE** Use [`page.waitForLoadState([state[, options]])`](#pagewaitforloadstatestate-options) to wait until the page
+gets to a particular state (you should not need it in most cases).
#### event: 'request'
- <[Request]>
-Emitted when a page issues a request. The [request] object is read-only.
-In order to intercept and mutate requests, see [`page.route()`](#pagerouteurl-handler) or [`browserContext.route()`](#browsercontextrouteurl-handler).
+Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests, see
+[`page.route()`](#pagerouteurl-handler) or [`browserContext.route()`](#browsercontextrouteurl-handler).
#### event: 'requestfailed'
- <[Request]>
Emitted when a request fails, for example by timing out.
-> **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with [`'requestfinished'`](#event-requestfinished) event and not with [`'requestfailed'`](#event-requestfailed).
+> **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
+will complete with [`'requestfinished'`](#event-requestfinished) event and not with
+[`'requestfailed'`](#event-requestfailed).
#### event: 'requestfinished'
- <[Request]>
-Emitted when a request finishes successfully after downloading the response body. For a successful response, the sequence of events is `request`, `response` and `requestfinished`.
+Emitted when a request finishes successfully after downloading the response body. For a successful response, the
+sequence of events is `request`, `response` and `requestfinished`.
#### event: 'response'
- <[Response]>
-Emitted when [response] status and headers are received for a request. For a successful response, the sequence of events is `request`, `response` and `requestfinished`.
+Emitted when [response] status and headers are received for a request. For a successful response, the sequence of events
+is `request`, `response` and `requestfinished`.
#### event: 'websocket'
- <[WebSocket]> websocket
@@ -785,13 +841,15 @@ Emitted when <[WebSocket]> request is sent.
#### event: 'worker'
- <[Worker]>
-Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned by the page.
+Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned by the
+page.
#### page.$(selector)
- %%-query-selector-%%
- returns: <[Promise]<[null]|[ElementHandle]>>
-The method finds an element matching the specified selector within the page. If no elements match the selector, the return value resolves to `null`.
+The method finds an element matching the specified selector within the page. If no elements match the selector, the
+return value resolves to `null`.
Shortcut for [page.mainFrame().$(selector)](#frameselector).
@@ -799,7 +857,8 @@ Shortcut for [page.mainFrame().$(selector)](#frameselector).
- %%-query-selector-%%
- returns: <[Promise]<[Array]<[ElementHandle]>>>
-The method finds all elements matching the specified selector within the page. If no elements match the selector, the return value resolves to `[]`.
+The method finds all elements matching the specified selector within the page. If no elements match the selector, the
+return value resolves to `[]`.
Shortcut for [page.mainFrame().$$(selector)](#frameselector-1).
@@ -809,11 +868,13 @@ Shortcut for [page.mainFrame().$$(selector)](#frameselector-1).
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
-The method finds an element matching the specified selector within the page and passes it as a first argument to `pageFunction`. If no elements match the selector, the method throws an error.
+The method finds an element matching the specified selector within the page 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 `page.$eval` would wait for the promise to resolve and return its value.
Examples:
+
```js
const searchValue = await page.$eval('#search', el => el.value);
const preloadHref = await page.$eval('link[rel=preload]', el => el.href);
@@ -828,11 +889,13 @@ Shortcut for [page.mainFrame().$eval(selector, pageFunction)](#frameevalselector
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
-The method finds all elements matching the specified selector within the page and passes an array of matched elements as a first argument to `pageFunction`.
+The method finds all elements matching the specified selector within the page and passes an array of matched elements as
+a first argument to `pageFunction`.
If `pageFunction` returns a [Promise], then `page.$$eval` would wait for the promise to resolve and return its value.
Examples:
+
```js
const divsCounts = await page.$$eval('div', (divs, min) => divs.length >= min, 10);
```
@@ -851,7 +914,8 @@ Adds a script which would be evaluated in one of the following scenarios:
- Whenever the page is navigated.
- Whenever the child frame is attached or navigated. In this case, the script is evaluated in the context of the newly attached frame.
-The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed `Math.random`.
+The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend
+the JavaScript environment, e.g. to seed `Math.random`.
An example of overriding `Math.random` before the page loads:
@@ -864,7 +928,9 @@ const preloadFile = fs.readFileSync('./preload.js', 'utf8');
await page.addInitScript(preloadFile);
```
-> **NOTE** The order of evaluation of multiple scripts installed via [browserContext.addInitScript(script[, arg])](#browsercontextaddinitscriptscript-arg) and [page.addInitScript(script[, arg])](#pageaddinitscriptscript-arg) is not defined.
+> **NOTE** The order of evaluation of multiple scripts installed via [browserContext.addInitScript(script[,
+arg])](#browsercontextaddinitscriptscript-arg) and [page.addInitScript(script[, arg])](#pageaddinitscriptscript-arg) is
+not defined.
#### page.addScriptTag(options)
- `options` <[Object]>
@@ -885,18 +951,16 @@ Shortcut for [page.mainFrame().addScriptTag(options)](#frameaddscripttagoptions)
- `content` <[string]> Raw CSS content to be injected into frame.
- returns: <[Promise]<[ElementHandle]>> which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
-Adds a `<link rel="stylesheet">` tag into the page with the desired url or a `<style type="text/css">` tag with the content.
+Adds a `<link rel="stylesheet">` tag into the page with the desired url or a `<style type="text/css">` tag with the
+content.
Shortcut for [page.mainFrame().addStyleTag(options)](#frameaddstyletagoptions).
-
#### page.bringToFront()
-
- returns: <[Promise]>
Brings page to front (activates tab).
-
#### page.check(selector, [options])
- %%-input-selector-%%
- `options` <[Object]>
@@ -914,7 +978,8 @@ This method checks an element matching `selector` by performing the following st
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
1. Ensure that the element is now checked. If not, this method rejects.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
Shortcut for [page.mainFrame().check(selector[, options])](#framecheckselector-options).
@@ -938,20 +1003,19 @@ This method clicks an element matching `selector` by performing the following st
1. Use [page.mouse](#pagemouse) 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.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
Shortcut for [page.mainFrame().click(selector[, options])](#frameclickselector-options).
#### page.close([options])
- `options` <[Object]>
- - `runBeforeUnload` <[boolean]> Defaults to `false`. Whether to run the
- [before unload](https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload)
- page handlers.
+ - `runBeforeUnload` <[boolean]> Defaults to `false`. Whether to run the [before unload](https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload) page handlers.
- returns: <[Promise]>
-If `runBeforeUnload` is `false` the result will resolve only after the page has been closed.
-If `runBeforeUnload` is `true` the method will **not** wait for the page to close.
-By default, `page.close()` **does not** run beforeunload handlers.
+If `runBeforeUnload` is `false` the result will resolve only after the page has been closed. If `runBeforeUnload` is
+`true` the method will **not** wait for the page to close. By default, `page.close()` **does not** run beforeunload
+handlers.
> **NOTE** if `runBeforeUnload` is passed as true, a `beforeunload` dialog might be summoned
> and should be handled manually via page's ['dialog'](#event-dialog) event.
@@ -962,16 +1026,15 @@ By default, `page.close()` **does not** run beforeunload handlers.
Gets the full HTML contents of the page, including the doctype.
#### page.context()
-
- returns: <[BrowserContext]>
Get the browser context that the page belongs to.
#### page.coverage
-
- returns: <[null]|[ChromiumCoverage]>
-Browser-specific Coverage implementation, only available for Chromium atm. See [ChromiumCoverage](#class-chromiumcoverage) for more details.
+Browser-specific Coverage implementation, only available for Chromium atm. See
+[ChromiumCoverage](#class-chromiumcoverage) for more details.
#### page.dblclick(selector[, options])
- %%-input-selector-%%
@@ -992,13 +1055,13 @@ This method double clicks an element matching `selector` by performing the follo
1. Use [page.mouse](#pagemouse) 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. Note that if the first click of the `dblclick()` triggers a navigation event, this method will reject.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
> **NOTE** `page.dblclick()` dispatches two `click` events and a single `dblclick` event.
Shortcut for [page.mainFrame().dblclick(selector[, options])](#framedblclickselector-options).
-
#### page.dispatchEvent(selector, type[, eventInit, options])
- %%-input-selector-%%
- `type` <[string]> DOM event type: `"click"`, `"dragstart"`, etc.
@@ -1007,13 +1070,16 @@ Shortcut for [page.mainFrame().dblclick(selector[, options])](#framedblclicksele
- %%-input-timeout-%%
- returns: <[Promise]>
-The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the elment, `click` is dispatched. This is equivalend to calling [`element.click()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
+The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the elment, `click`
+is dispatched. This is equivalend to calling
+[`element.click()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
```js
await page.dispatchEvent('button#submit', '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.
+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:
- [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
@@ -1024,7 +1090,7 @@ Since `eventInit` is event-specific, please refer to the events documentation fo
- [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
- [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
- You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
+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
@@ -1072,11 +1138,15 @@ await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').ma
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
-If the function passed to the `page.evaluate` returns a [Promise], then `page.evaluate` would wait for the promise to resolve and return its value.
+If the function passed to the `page.evaluate` returns a [Promise], then `page.evaluate` would wait for the promise to
+resolve and return its value.
-If the function passed to the `page.evaluate` returns a non-[Serializable] value, then `page.evaluate` resolves to `undefined`. DevTools Protocol also supports transferring some additional values that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.
+If the function passed to the `page.evaluate` returns a non-[Serializable] value, then `page.evaluate` resolves to
+`undefined`. DevTools Protocol also supports transferring some additional values that are not serializable by `JSON`:
+`-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.
Passing argument to `pageFunction`:
+
```js
const result = await page.evaluate(([x, y]) => {
return Promise.resolve(x * y);
@@ -1085,6 +1155,7 @@ console.log(result); // prints "56"
```
A string can also be passed in instead of a function:
+
```js
console.log(await page.evaluate('1 + 2')); // prints "3"
const x = 10;
@@ -1092,6 +1163,7 @@ console.log(await page.evaluate(`1 + ${x}`)); // prints "11"
```
[ElementHandle] instances can be passed as an argument to the `page.evaluate`:
+
```js
const bodyHandle = await page.$('body');
const html = await page.evaluate(([body, suffix]) => body.innerHTML + suffix, [bodyHandle, 'hello']);
@@ -1105,16 +1177,20 @@ Shortcut for [page.mainFrame().evaluate(pageFunction[, arg])](#frameevaluatepage
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[JSHandle]>> Promise which resolves to the return value of `pageFunction` as in-page object (JSHandle)
-The only difference between `page.evaluate` and `page.evaluateHandle` is that `page.evaluateHandle` returns in-page object (JSHandle).
+The only difference between `page.evaluate` and `page.evaluateHandle` is that `page.evaluateHandle` returns in-page
+object (JSHandle).
-If the function passed to the `page.evaluateHandle` returns a [Promise], then `page.evaluateHandle` would wait for the promise to resolve and return its value.
+If the function passed to the `page.evaluateHandle` returns a [Promise], then `page.evaluateHandle` would wait for the
+promise to resolve and return its value.
A string can also be passed in instead of a function:
+
```js
const aHandle = await page.evaluateHandle('document'); // Handle for the 'document'
```
[JSHandle] instances can be passed as an argument to the `page.evaluateHandle`:
+
```js
const aHandle = await page.evaluateHandle(() => document.body);
const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle);
@@ -1129,18 +1205,20 @@ await resultHandle.dispose();
- `handle` <[boolean]> Whether to pass the argument as a handle, instead of passing by value. When passing a handle, only one argument is supported. When passing by value, multiple arguments are supported.
- returns: <[Promise]>
-The method adds a function called `name` on the `window` object of every frame in this page.
-When called, the function executes `playwrightBinding` in Node.js and returns a [Promise] which resolves to the return value of `playwrightBinding`.
-If the `playwrightBinding` returns a [Promise], it will be awaited.
+The method adds a function called `name` on the `window` object of every frame in this page. When called, the function
+executes `playwrightBinding` in Node.js and returns a [Promise] which resolves to the return value of
+`playwrightBinding`. If the `playwrightBinding` returns a [Promise], it will be awaited.
-The first argument of the `playwrightBinding` function contains information about the caller:
-`{ browserContext: BrowserContext, page: Page, frame: Frame }`.
+The first argument of the `playwrightBinding` function contains information about the caller: `{ browserContext:
+BrowserContext, page: Page, frame: Frame }`.
-See [browserContext.exposeBinding(name, playwrightBinding)](#browsercontextexposebindingname-playwrightbinding-options) for the context-wide version.
+See [browserContext.exposeBinding(name, playwrightBinding)](#browsercontextexposebindingname-playwrightbinding-options)
+for the context-wide version.
> **NOTE** Functions installed via `page.exposeBinding` survive navigations.
An example of exposing page URL to all frames in a page:
+
```js
const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
@@ -1163,6 +1241,7 @@ const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
```
An example of passing an element handle:
+
```js
await page.exposeBinding('clicked', async (source, element) => {
console.log(await element.textContent());
@@ -1181,16 +1260,19 @@ await page.setContent(`
- `playwrightFunction` <[function]> Callback function which will be called in Playwright's context.
- returns: <[Promise]>
-The method adds a function called `name` on the `window` object of every frame in the page.
-When called, the function executes `playwrightFunction` in Node.js and returns a [Promise] which resolves to the return value of `playwrightFunction`.
+The method adds a function called `name` on the `window` object of every frame in the page. When called, the function
+executes `playwrightFunction` in Node.js and returns a [Promise] which resolves to the return value of
+`playwrightFunction`.
If the `playwrightFunction` returns a [Promise], it will be awaited.
-See [browserContext.exposeFunction(name, playwrightFunction)](#browsercontextexposefunctionname-playwrightfunction) for context-wide exposed function.
+See [browserContext.exposeFunction(name, playwrightFunction)](#browsercontextexposefunctionname-playwrightfunction) for
+context-wide exposed function.
> **NOTE** Functions installed via `page.exposeFunction` survive navigations.
An example of adding an `md5` function to the page:
+
```js
const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
const crypto = require('crypto');
@@ -1249,9 +1331,10 @@ const fs = require('fs');
- %%-input-timeout-%%
- returns: <[Promise]>
-This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks, focuses the element, fills it and triggers an `input` event after filling.
-If the element matching `selector` is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an error.
-Note that you can pass an empty string to clear the input field.
+This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks, focuses the
+element, fills it and triggers an `input` event after filling. If the element matching `selector` is not an `<input>`,
+`<textarea>` or `[contenteditable]` element, this method throws an error. Note that you can pass an empty string to
+clear the input field.
To send fine-grained keyboard events, use [`page.type`](#pagetypeselector-text-options).
@@ -1263,8 +1346,8 @@ Shortcut for [page.mainFrame().fill()](#framefillselector-value-options)
- %%-input-timeout-%%
- returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully focused. The promise will be rejected if there is no element matching `selector`.
-This method fetches an element with `selector` and focuses it.
-If there's no element matching `selector`, the method waits until a matching element appears in the DOM.
+This method fetches an element with `selector` and focuses it. If there's no element matching `selector`, the method
+waits until a matching element appears in the DOM.
Shortcut for [page.mainFrame().focus(selector)](#framefocusselector-options).
@@ -1297,26 +1380,24 @@ Returns frame matching the specified criteria. Either `name` or `url` must be sp
Returns element attribute value.
#### page.goBack([options])
-- `options` <[Object]> Navigation parameters which might have the following properties:
+- `options` <[Object]>
- %%-navigation-timeout-%%
- %%-navigation-wait-until-%%
-- returns: <[Promise]<[null]|[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If
-can not go back, resolves to `null`.
+- returns: <[Promise]<[null]|[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go back, resolves to `null`.
Navigate to the previous page in history.
#### page.goForward([options])
-- `options` <[Object]> Navigation parameters which might have the following properties:
+- `options` <[Object]>
- %%-navigation-timeout-%%
- %%-navigation-wait-until-%%
-- returns: <[Promise]<[null]|[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If
-can not go forward, resolves to `null`.
+- returns: <[Promise]<[null]|[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go forward, resolves to `null`.
Navigate to the next page in history.
#### page.goto(url[, options])
- `url` <[string]> URL to navigate page to. The url should include scheme, e.g. `https://`.
-- `options` <[Object]> Navigation parameters which might have the following properties:
+- `options` <[Object]>
- %%-navigation-timeout-%%
- %%-navigation-wait-until-%%
- `referer` <[string]> Referer header value. If provided it will take preference over the referer header value set by [page.setExtraHTTPHeaders()](#pagesetextrahttpheadersheaders).
@@ -1329,11 +1410,14 @@ Navigate to the next page in history.
* the remote server does not respond or is unreachable.
* the main resource failed to load.
-`page.goto` will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling [response.status()](#responsestatus).
-
-> **NOTE** `page.goto` either throws an error or returns a main resource response. The only exceptions are navigation to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
+`page.goto` will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not
+Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling
+[response.status()](#responsestatus).
-> **NOTE** Headless mode doesn't support navigation to a PDF document. See the [upstream issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).
+> **NOTE** `page.goto` either throws an error or returns a main resource response. The only exceptions are navigation to
+`about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
+> **NOTE** Headless mode doesn't support navigation to a PDF document. See the [upstream
+issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).
Shortcut for [page.mainFrame().goto(url[, options])](#framegotourl-options)
@@ -1353,7 +1437,8 @@ This method hovers over an element matching `selector` by performing the followi
1. Use [page.mouse](#pagemouse) to hover over the center of the element, or the specified `position`.
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
Shortcut for [page.mainFrame().hover(selector[, options])](#framehoverselector-options).
@@ -1374,13 +1459,11 @@ Resolves to the `element.innerHTML`.
Resolves to the `element.innerText`.
#### page.isClosed()
-
- returns: <[boolean]>
Indicates that the page has been closed.
#### page.keyboard
-
- returns: <[Keyboard]>
#### page.mainFrame()
@@ -1389,15 +1472,13 @@ Indicates that the page has been closed.
Page is guaranteed to have a main frame which persists during navigations.
#### page.mouse
-
- returns: <[Mouse]>
#### page.opener()
-
- returns: <[Promise]<[null]|[Page]>> Promise which resolves to the opener for popup pages and `null` for others. If the opener has been closed already the promise may resolve to `null`.
#### page.pdf([options])
-- `options` <[Object]> Options object which might have the following properties:
+- `options` <[Object]>
- `path` <[string]> The file path to save the PDF to. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). If no path is provided, the PDF won't be saved to the disk.
- `scale` <[number]> Scale of the webpage rendering. Defaults to `1`. Scale amount must be between 0.1 and 2.
- `displayHeaderFooter` <[boolean]> Display header and footer. Defaults to `false`.
@@ -1424,9 +1505,12 @@ Page is guaranteed to have a main frame which persists during navigations.
> **NOTE** Generating a pdf is currently only supported in Chromium headless.
-`page.pdf()` generates a pdf of the page with `print` css media. To generate a pdf with `screen` media, call [page.emulateMedia({ media: 'screen' })](#pageemulatemediaoptions) before calling `page.pdf()`:
+`page.pdf()` generates a pdf of the page with `print` css media. To generate a pdf with `screen` media, call
+[page.emulateMedia({ media: 'screen' })](#pageemulatemediaoptions) before calling `page.pdf()`:
-> **NOTE** By default, `page.pdf()` generates a pdf with modified colors for printing. Use the [`-webkit-print-color-adjust`](https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-print-color-adjust) property to force rendering of exact colors.
+> **NOTE** By default, `page.pdf()` generates a pdf with modified colors for printing. Use the
+[`-webkit-print-color-adjust`](https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-print-color-adjust) property to
+force rendering of exact colors.
```js
// Generates a PDF with 'screen' media type.
@@ -1475,17 +1559,22 @@ The `format` options are:
Focuses the element, and then uses [`keyboard.down`](#keyboarddownkey) and [`keyboard.up`](#keyboardupkey).
-`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:
+`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.
+`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 suported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
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.
+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"` or `key: "Control+Shift+T"` are supported as well. When speficied with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
+Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When speficied with the
+modifier, modifier is pressed and being held while the subsequent key is being pressed.
```js
const page = await browser.newPage();
@@ -1500,7 +1589,7 @@ await browser.close();
```
#### page.reload([options])
-- `options` <[Object]> Navigation parameters which might have the following properties:
+- `options` <[Object]>
- %%-navigation-timeout-%%
- %%-navigation-wait-until-%%
- returns: <[Promise]<[null]|[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
@@ -1534,12 +1623,13 @@ await page.goto('https://example.com');
await browser.close();
```
-Page routes take precedence over browser context routes (set up with [browserContext.route(url, handler)](#browsercontextrouteurl-handler)) when request matches both handlers.
+Page routes take precedence over browser context routes (set up with [browserContext.route(url,
+handler)](#browsercontextrouteurl-handler)) when request matches both handlers.
> **NOTE** Enabling routing disables http cache.
#### page.screenshot([options])
-- `options` <[Object]> Options object which might have the following properties:
+- `options` <[Object]>
- `path` <[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 [current working directory](https://nodejs.org/api/process.html#process_process_cwd). If no path is provided, the image won't be saved to the disk.
- `type` <"png"|"jpeg"> Specify screenshot type, defaults to `png`.
- `quality` <[number]> The quality of the image, between 0-100. Not applicable to `png` images.
@@ -1553,7 +1643,8 @@ Page routes take precedence over browser context routes (set up with [browserCon
- %%-input-timeout-%%
- returns: <[Promise]<[Buffer]>> Promise which resolves to buffer with the captured screenshot.
-> **NOTE** Screenshots take at least 1/6 second on Chromium OS X and Chromium Windows. See https://crbug.com/741689 for discussion.
+> **NOTE** Screenshots take at least 1/6 second on Chromium OS X and Chromium Windows. See https://crbug.com/741689 for
+discussion.
#### page.selectOption(selector, values[, options])
- %%-input-selector-%%
@@ -1566,8 +1657,8 @@ Page routes take precedence over browser context routes (set up with [browserCon
- %%-input-timeout-%%
- returns: <[Promise]<[Array]<[string]>>> An array of option values that have been successfully selected.
-Triggers a `change` and `input` event once all the provided options have been selected.
-If there's no `<select>` element matching `selector`, the method throws an error.
+Triggers a `change` and `input` event once all the provided options have been selected. If there's no `<select>` element
+matching `selector`, the method throws an error.
```js
// single selection matching the value
@@ -1585,7 +1676,7 @@ Shortcut for [page.mainFrame().selectOption()](#frameselectoptionselector-values
#### page.setContent(html[, options])
- `html` <[string]> HTML markup to assign to the page.
-- `options` <[Object]> Parameters which might have the following properties:
+- `options` <[Object]>
- %%-navigation-timeout-%%
- %%-navigation-wait-until-%%
- returns: <[Promise]>
@@ -1601,15 +1692,18 @@ This setting will change the default maximum navigation time for the following m
- [page.setContent(html[, options])](#pagesetcontenthtml-options)
- [page.waitForNavigation([options])](#pagewaitfornavigationoptions)
-> **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout) takes priority over [`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout), [`browserContext.setDefaultTimeout`](#browsercontextsetdefaulttimeouttimeout) and [`browserContext.setDefaultNavigationTimeout`](#browsercontextsetdefaultnavigationtimeouttimeout).
-
+> **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout) takes priority over
+[`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout),
+[`browserContext.setDefaultTimeout`](#browsercontextsetdefaulttimeouttimeout) and
+[`browserContext.setDefaultNavigationTimeout`](#browsercontextsetdefaultnavigationtimeouttimeout).
#### page.setDefaultTimeout(timeout)
- `timeout` <[number]> Maximum time in milliseconds
This setting will change the default maximum time for all the methods accepting `timeout` option.
-> **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout) takes priority over [`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout).
+> **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout) takes priority over
+[`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout).
#### page.setExtraHTTPHeaders(headers)
- `headers` <[Object]<[string], [string]>> An object containing additional HTTP headers to be sent with every request. All header values must be strings.
@@ -1627,10 +1721,12 @@ The extra HTTP headers will be sent with every request the page initiates.
- %%-input-timeout-%%
- returns: <[Promise]>
-This method expects `selector` to point to an [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
-
-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](https://nodejs.org/api/process.html#process_process_cwd). For empty array, clears the selected files.
+This method expects `selector` to point to an [input
+element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
+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](https://nodejs.org/api/process.html#process_process_cwd). For
+empty array, clears the selected files.
#### page.setViewportSize(viewportSize)
- `viewportSize` <[Object]>
@@ -1638,9 +1734,12 @@ Sets the value of the file input to these file paths or files. If some of the `f
- `height` <[number]> page height in pixels. **required**
- returns: <[Promise]>
-In the case of multiple pages in a single browser, each page can have its own viewport size. However, [browser.newContext([options])](#browsernewcontextoptions) allows to set viewport size (and more) for all pages in the context at once.
+In the case of multiple pages in a single browser, each page can have its own viewport size. However,
+[browser.newContext([options])](#browsernewcontextoptions) allows to set viewport size (and more) for all pages in the
+context at once.
-`page.setViewportSize` will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport size before navigating to the page.
+`page.setViewportSize` will resize the page. A lot of websites don't expect phones to change size, so you should set the
+viewport size before navigating to the page.
```js
const page = await browser.newPage();
@@ -1668,7 +1767,8 @@ This method taps an element matching `selector` by performing the following step
1. Use [page.touchscreen](#pagemouse) to tap the center of the element, or the specified `position`.
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
> **NOTE** `page.tap()` requires that the `hasTouch` option of the browser context be set to true.
@@ -1688,7 +1788,6 @@ Resolves to the `element.textContent`.
Shortcut for [page.mainFrame().title()](#frametitle).
#### page.touchscreen
-
- returns: <[Touchscreen]>
#### page.type(selector, text[, options])
@@ -1700,7 +1799,8 @@ Shortcut for [page.mainFrame().title()](#frametitle).
- %%-input-timeout-%%
- returns: <[Promise]>
-Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `page.type` can be used to send fine-grained keyboard events. To fill values in form fields, use [`page.fill`](#pagefillselector-value-options).
+Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `page.type` can be used to send
+fine-grained keyboard events. To fill values in form fields, use [`page.fill`](#pagefillselector-value-options).
To press a special key, like `Control` or `ArrowDown`, use [`keyboard.press`](#keyboardpresskey-options).
@@ -1728,7 +1828,8 @@ This method unchecks an element matching `selector` by performing the following
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
1. Ensure that the element is now unchecked. If not, this method rejects.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
Shortcut for [page.mainFrame().uncheck(selector[, options])](#frameuncheckselector-options).
@@ -1737,7 +1838,8 @@ Shortcut for [page.mainFrame().uncheck(selector[, options])](#frameuncheckselect
- `handler` <[function]\([Route], [Request]\)> Handler function to route the request.
- returns: <[Promise]>
-Removes a route created with [page.route(url, handler)](#pagerouteurl-handler). When `handler` is not specified, removes all routes for the `url`.
+Removes a route created with [page.route(url, handler)](#pagerouteurl-handler). When `handler` is not specified, removes
+all routes for the `url`.
#### page.url()
- returns: <[string]>
@@ -1761,18 +1863,19 @@ Video object associated with this page.
- %%-wait-for-timeout-%%
- returns: <[Promise]<[Object]>> Promise which resolves to the event data value.
-Waits for event to fire and passes its value into the predicate function. Resolves when the predicate returns truthy value. Will throw an error if the page is closed before the event
-is fired.
+Waits for event to fire and passes its value into the predicate function. Resolves when the predicate returns truthy
+value. Will throw an error if the page is closed before the event is fired.
#### page.waitForFunction(pageFunction[, arg, options])
- `pageFunction` <[function]|[string]> Function to be evaluated in browser context
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
-- `options` <[Object]> Optional waiting parameters
+- `options` <[Object]>
- `polling` <[number]|"raf"> If `polling` is `'raf'`, then `pageFunction` is constantly executed in `requestAnimationFrame` callback. If `polling` is a number, then it is treated as an interval in milliseconds at which the function would be executed. Defaults to `raf`.
- %%-wait-for-timeout-%%
- returns: <[Promise]<[JSHandle]>> Promise which resolves when the `pageFunction` returns a truthy value. It resolves to a JSHandle of the truthy value.
The `waitForFunction` can be used to observe viewport size change:
+
```js
const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
@@ -1793,7 +1896,8 @@ const selector = '.foo';
await page.waitForFunction(selector => !!document.querySelector(selector), selector);
```
-Shortcut for [page.mainFrame().waitForFunction(pageFunction[, arg, options])](#framewaitforfunctionpagefunction-arg-options).
+Shortcut for [page.mainFrame().waitForFunction(pageFunction[, arg,
+options])](#framewaitforfunctionpagefunction-arg-options).
#### page.waitForLoadState([state[, options]])
- `state` <"load"|"domcontentloaded"|"networkidle"> Load state to wait for, defaults to `load`. If the state has been already reached while loading current document, the method resolves immediately.
@@ -1804,7 +1908,8 @@ Shortcut for [page.mainFrame().waitForFunction(pageFunction[, arg, options])](#f
- %%-navigation-timeout-%%
- returns: <[Promise]> Promise which resolves when the required load state has been reached.
-This resolves when the page reaches a required load state, `load` by default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.
+This resolves when the page reaches a required load state, `load` by default. The navigation must have been committed
+when this method is called. If current document has already reached the required state, resolves immediately.
```js
await page.click('button'); // Click triggers navigation.
@@ -1823,14 +1928,15 @@ console.log(await popup.title()); // Popup is ready to use.
Shortcut for [page.mainFrame().waitForLoadState([options])](#framewaitforloadstatestate-options).
#### page.waitForNavigation([options])
-- `options` <[Object]> Navigation parameters which might have the following properties:
+- `options` <[Object]>
- %%-navigation-timeout-%%
- `url` <[string]|[RegExp]|[Function]> A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation.
- %%-navigation-wait-until-%%
- returns: <[Promise]<[null]|[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with `null`.
-This resolves when the page navigates to a new URL or reloads. It is useful for when you run code
-which will indirectly cause the page to navigate. e.g. The click target has an `onclick` handler that triggers navigation from a `setTimeout`. Consider this example:
+This resolves when the page navigates to a new URL or reloads. It is useful for when you run code which will indirectly
+cause the page to navigate. e.g. The click target has an `onclick` handler that triggers navigation from a `setTimeout`.
+Consider this example:
```js
const [response] = await Promise.all([
@@ -1839,13 +1945,14 @@ const [response] = await Promise.all([
]);
```
-**NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL is considered a navigation.
+**NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL is
+considered a navigation.
Shortcut for [page.mainFrame().waitForNavigation(options)](#framewaitfornavigationoptions).
#### page.waitForRequest(urlOrPredicate[, options])
- `urlOrPredicate` <[string]|[RegExp]|[Function]> Request URL string, regex or predicate receiving [Request] object.
-- `options` <[Object]> Optional waiting parameters
+- `options` <[Object]>
- `timeout` <[number]> Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to disable the timeout. The default value can be changed by using the [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) method.
- returns: <[Promise]<[Request]>> Promise which resolves to the matched request.
@@ -1861,7 +1968,7 @@ await page.waitForRequest(request => request.url().searchParams.get('foo') === '
#### page.waitForResponse(urlOrPredicate[, options])
- `urlOrPredicate` <[string]|[RegExp]|[function]\([Response]\):[boolean]> Request URL string, regex or predicate receiving [Response] object.
-- `options` <[Object]> Optional waiting parameters
+- `options` <[Object]>
- `timeout` <[number]> Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to disable the timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]<[Response]>> Promise which resolves to the matched response.
@@ -1878,9 +1985,12 @@ return finalResponse.ok();
- %%-input-timeout-%%
- returns: <[Promise]<[null]|[ElementHandle]>> Promise which resolves when element specified by selector satisfies `state` option. Resolves to `null` if waiting for `hidden` or `detached`.
-Wait for the `selector` 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.
+Wait for the `selector` 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.
This method works across navigations:
+
```js
const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
@@ -1897,7 +2007,6 @@ const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
await browser.close();
})();
```
-Shortcut for [page.mainFrame().waitForSelector(selector[, options])](#framewaitforselectorselector-options).
#### page.waitForTimeout(timeout)
- `timeout` <[number]> A timeout to wait for
@@ -1905,7 +2014,8 @@ Shortcut for [page.mainFrame().waitForSelector(selector[, options])](#framewaitf
Returns a promise that resolves after the timeout.
-Note that `page.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going to be flaky. Use signals such as network events, selectors becoming visible and others instead.
+Note that `page.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going to be
+flaky. Use signals such as network events, selectors becoming visible and others instead.
```js
// wait for 1 second
@@ -1915,14 +2025,14 @@ await page.waitForTimeout(1000);
Shortcut for [page.mainFrame().waitForTimeout(timeout)](#pagewaitfortimeouttimeout).
#### page.workers()
-- returns: <[Array]<[Worker]>>
-This method returns all of the dedicated [WebWorkers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) associated with the page.
+- returns: <[Array]<[Worker]>> This method returns all of the dedicated [WebWorkers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) associated with the page.
> **NOTE** This does not contain ServiceWorkers
### class: Frame
-At every point of time, page exposes its current frame tree via the [page.mainFrame()](#pagemainframe) and [frame.childFrames()](#framechildframes) methods.
+At every point of time, page exposes its current frame tree via the [page.mainFrame()](#pagemainframe) and
+[frame.childFrames()](#framechildframes) methods.
[Frame] object's lifecycle is controlled by three events, dispatched on the page object:
- ['frameattached'](#event-frameattached) - fired when the frame gets attached to the page. A Frame can be attached to the page only once.
@@ -2006,13 +2116,17 @@ console.log(text);
- %%-query-selector-%%
- returns: <[Promise]<[null]|[ElementHandle]>> Promise which resolves to ElementHandle pointing to the frame element.
-The method finds an element matching the specified selector within the frame. See [Working with selectors](#working-with-selectors) for more details. If no elements match the selector, the return value resolves to `null`.
+The method finds an element matching the specified selector within the frame. See [Working with
+selectors](#working-with-selectors) for more details. If no elements match the selector, the return value resolves to
+`null`.
#### frame.$$(selector)
- %%-query-selector-%%
- returns: <[Promise]<[Array]<[ElementHandle]>>> Promise which resolves to ElementHandles pointing to the frame elements.
-The method finds all elements matching the specified selector within the frame. See [Working with selectors](#working-with-selectors) for more details. If no elements match the selector, the return value resolves to `[]`.
+The method finds all elements matching the specified selector within the frame. See [Working with
+selectors](#working-with-selectors) for more details. If no elements match the selector, the return value resolves to
+`[]`.
#### frame.$eval(selector, pageFunction[, arg])
- %%-query-selector-%%
@@ -2020,11 +2134,14 @@ The method finds all elements matching the specified selector within the frame.
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
-The method finds an element matching the specified selector within the frame and passes it as a first argument to `pageFunction`. See [Working with selectors](#working-with-selectors) for more details. If no elements match the selector, the method throws an error.
+The method finds an element matching the specified selector within the frame and passes it as a first argument to
+`pageFunction`. See [Working with selectors](#working-with-selectors) for more details. If no elements match the
+selector, the method throws an error.
If `pageFunction` returns a [Promise], then `frame.$eval` would wait for the promise to resolve and return its value.
Examples:
+
```js
const searchValue = await frame.$eval('#search', el => el.value);
const preloadHref = await frame.$eval('link[rel=preload]', el => el.href);
@@ -2037,11 +2154,13 @@ const html = await frame.$eval('.main-container', (e, suffix) => e.outerHTML + s
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
-The method finds all elements matching the specified selector within the frame and passes an array of matched elements as a first argument to `pageFunction`. See [Working with selectors](#working-with-selectors) for more details.
+The method finds all elements matching the specified selector within the frame and passes an array of matched elements
+as a first argument to `pageFunction`. See [Working with selectors](#working-with-selectors) for more details.
If `pageFunction` returns a [Promise], then `frame.$$eval` would wait for the promise to resolve and return its value.
Examples:
+
```js
const divsCounts = await frame.$$eval('div', (divs, min) => divs.length >= min, 10);
```
@@ -2063,7 +2182,8 @@ Adds a `<script>` tag into the page with the desired url or content.
- `content` <[string]> Raw CSS content to be injected into frame.
- returns: <[Promise]<[ElementHandle]>> which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
-Adds a `<link rel="stylesheet">` tag into the page with the desired url or a `<style type="text/css">` tag with the content.
+Adds a `<link rel="stylesheet">` tag into the page with the desired url or a `<style type="text/css">` tag with the
+content.
#### frame.check(selector, [options])
- %%-input-selector-%%
@@ -2082,7 +2202,8 @@ This method checks an element matching `selector` by performing the following st
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
1. Ensure that the element is now checked. If not, this method rejects.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
#### frame.childFrames()
- returns: <[Array]<[Frame]>>
@@ -2107,7 +2228,8 @@ This method clicks an element matching `selector` by performing the following st
1. Use [page.mouse](#pagemouse) 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.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
#### frame.content()
- returns: <[Promise]<[string]>>
@@ -2133,7 +2255,8 @@ This method double clicks an element matching `selector` by performing the follo
1. Use [page.mouse](#pagemouse) 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. Note that if the first click of the `dblclick()` triggers a navigation event, this method will reject.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
> **NOTE** `frame.dblclick()` dispatches two `click` events and a single `dblclick` event.
@@ -2145,13 +2268,16 @@ When all steps combined have not finished during the specified `timeout`, this m
- %%-input-timeout-%%
- returns: <[Promise]>
-The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the elment, `click` is dispatched. This is equivalend to calling [`element.click()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
+The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the elment, `click`
+is dispatched. This is equivalend to calling
+[`element.click()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
```js
await frame.dispatchEvent('button#submit', '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.
+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:
- [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
@@ -2162,7 +2288,7 @@ Since `eventInit` is event-specific, please refer to the events documentation fo
- [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
- [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
- You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
+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
@@ -2175,9 +2301,12 @@ await frame.dispatchEvent('#source', 'dragstart', { dataTransfer });
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
-If the function passed to the `frame.evaluate` returns a [Promise], then `frame.evaluate` would wait for the promise to resolve and return its value.
+If the function passed to the `frame.evaluate` returns a [Promise], then `frame.evaluate` would wait for the promise to
+resolve and return its value.
-If the function passed to the `frame.evaluate` returns a non-[Serializable] value, then `frame.evaluate` resolves to `undefined`. DevTools Protocol also supports transferring some additional values that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.
+If the function passed to the `frame.evaluate` returns a non-[Serializable] value, then `frame.evaluate` resolves to
+`undefined`. DevTools Protocol also supports transferring some additional values that are not serializable by `JSON`:
+`-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.
```js
const result = await frame.evaluate(([x, y]) => {
@@ -2193,6 +2322,7 @@ console.log(await frame.evaluate('1 + 2')); // prints "3"
```
[ElementHandle] instances can be passed as an argument to the `frame.evaluate`:
+
```js
const bodyHandle = await frame.$('body');
const html = await frame.evaluate(([body, suffix]) => body.innerHTML + suffix, [bodyHandle, 'hello']);
@@ -2204,9 +2334,11 @@ await bodyHandle.dispose();
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[JSHandle]>> Promise which resolves to the return value of `pageFunction` as in-page object (JSHandle)
-The only difference between `frame.evaluate` and `frame.evaluateHandle` is that `frame.evaluateHandle` returns in-page object (JSHandle).
+The only difference between `frame.evaluate` and `frame.evaluateHandle` is that `frame.evaluateHandle` returns in-page
+object (JSHandle).
-If the function, passed to the `frame.evaluateHandle`, returns a [Promise], then `frame.evaluateHandle` would wait for the promise to resolve and return its value.
+If the function, passed to the `frame.evaluateHandle`, returns a [Promise], then `frame.evaluateHandle` would wait for
+the promise to resolve and return its value.
```js
const aWindowHandle = await frame.evaluateHandle(() => Promise.resolve(window));
@@ -2220,6 +2352,7 @@ const aHandle = await frame.evaluateHandle('document'); // Handle for the 'docum
```
[JSHandle] instances can be passed as an argument to the `frame.evaluateHandle`:
+
```js
const aHandle = await frame.evaluateHandle(() => document.body);
const resultHandle = await frame.evaluateHandle(([body, suffix]) => body.innerHTML + suffix, [aHandle, 'hello']);
@@ -2235,9 +2368,10 @@ await resultHandle.dispose();
- %%-input-timeout-%%
- returns: <[Promise]>
-This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks, focuses the element, fills it and triggers an `input` event after filling.
-If the element matching `selector` is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an error.
-Note that you can pass an empty string to clear the input field.
+This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks, focuses the
+element, fills it and triggers an `input` event after filling. If the element matching `selector` is not an `<input>`,
+`<textarea>` or `[contenteditable]` element, this method throws an error. Note that you can pass an empty string to
+clear the input field.
To send fine-grained keyboard events, use [`frame.type`](#frametypeselector-text-options).
@@ -2247,13 +2381,14 @@ To send fine-grained keyboard events, use [`frame.type`](#frametypeselector-text
- %%-input-timeout-%%
- returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully focused. The promise will be rejected if there is no element matching `selector`.
-This method fetches an element with `selector` and focuses it.
-If there's no element matching `selector`, the method waits until a matching element appears in the DOM.
+This method fetches an element with `selector` and focuses it. If there's no element matching `selector`, the method
+waits until a matching element appears in the DOM.
#### frame.frameElement()
- returns: <[Promise]<[ElementHandle]>> Promise that resolves with a `frame` or `iframe` element handle which corresponds to this frame.
-This is an inverse of [elementHandle.contentFrame()](#elementhandlecontentframe). Note that returned handle actually belongs to the parent frame.
+This is an inverse of [elementHandle.contentFrame()](#elementhandlecontentframe). Note that returned handle actually
+belongs to the parent frame.
This method throws an error if the frame has been detached before `frameElement()` returns.
@@ -2274,7 +2409,7 @@ Returns element attribute value.
#### frame.goto(url[, options])
- `url` <[string]> URL to navigate frame to. The url should include scheme, e.g. `https://`.
-- `options` <[Object]> Navigation parameters which might have the following properties:
+- `options` <[Object]>
- %%-navigation-timeout-%%
- %%-navigation-wait-until-%%
- `referer` <[string]> Referer header value. If provided it will take preference over the referer header value set by [page.setExtraHTTPHeaders()](#pagesetextrahttpheadersheaders).
@@ -2287,12 +2422,14 @@ Returns element attribute value.
* the remote server does not respond or is unreachable.
* the main resource failed to load.
-`frame.goto` will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling [response.status()](#responsestatus).
-
-> **NOTE** `frame.goto` either throws an error or returns a main resource response. The only exceptions are navigation to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
-
-> **NOTE** Headless mode doesn't support navigation to a PDF document. See the [upstream issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).
+`frame.goto` will not throw an error when any valid HTTP status code is returned by the remote server, including 404
+"Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling
+[response.status()](#responsestatus).
+> **NOTE** `frame.goto` either throws an error or returns a main resource response. The only exceptions are navigation
+to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
+> **NOTE** Headless mode doesn't support navigation to a PDF document. See the [upstream
+issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).
#### frame.hover(selector[, options])
- %%-input-selector-%%
@@ -2310,7 +2447,8 @@ This method hovers over an element matching `selector` by performing the followi
1. Use [page.mouse](#pagemouse) to hover over the center of the element, or the specified `position`.
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
#### frame.innerHTML(selector[, options])
- %%-input-selector-%%
@@ -2340,7 +2478,8 @@ Returns frame's name attribute as specified in the tag.
If the name is empty, returns the id attribute instead.
-> **NOTE** This value is calculated once when the frame is created, and will not update if the attribute is changed later.
+> **NOTE** This value is calculated once when the frame is created, and will not update if the attribute is changed
+later.
#### frame.page()
- returns: <[Page]>
@@ -2359,17 +2498,22 @@ Returns the page containing this frame.
- %%-input-timeout-%%
- returns: <[Promise]>
-`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:
+`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.
+`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 suported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
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.
+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"` or `key: "Control+Shift+T"` are supported as well. When speficied with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
+Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When speficied with the
+modifier, modifier is pressed and being held while the subsequent key is being pressed.
#### frame.selectOption(selector, values[, options])
- %%-query-selector-%%
@@ -2382,8 +2526,8 @@ Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported a
- %%-input-timeout-%%
- returns: <[Promise]<[Array]<[string]>>> An array of option values that have been successfully selected.
-Triggers a `change` and `input` event once all the provided options have been selected.
-If there's no `<select>` element matching `selector`, the method throws an error.
+Triggers a `change` and `input` event once all the provided options have been selected. If there's no `<select>` element
+matching `selector`, the method throws an error.
```js
// single selection matching the value
@@ -2398,7 +2542,7 @@ frame.selectOption('select#colors', 'red', 'green', 'blue');
#### frame.setContent(html[, options])
- `html` <[string]> HTML markup to assign to the page.
-- `options` <[Object]> Parameters which might have the following properties:
+- `options` <[Object]>
- %%-navigation-timeout-%%
- %%-navigation-wait-until-%%
- returns: <[Promise]>
@@ -2411,9 +2555,12 @@ frame.selectOption('select#colors', 'red', 'green', 'blue');
- %%-input-timeout-%%
- returns: <[Promise]>
-This method expects `selector` to point to an [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
+This method expects `selector` to point to an [input
+element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
-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](https://nodejs.org/api/process.html#process_process_cwd). For empty array, clears the selected files.
+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](https://nodejs.org/api/process.html#process_process_cwd). For
+empty array, clears the selected files.
#### frame.tap(selector[, options])
- %%-input-selector-%%
@@ -2432,7 +2579,8 @@ This method taps an element matching `selector` by performing the following step
1. Use [page.touchscreen](#pagemouse) to tap the center of the element, or the specified `position`.
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
> **NOTE** `frame.tap()` requires that the `hasTouch` option of the browser context be set to true.
@@ -2456,7 +2604,8 @@ Resolves to the `element.textContent`.
- %%-input-timeout-%%
- returns: <[Promise]>
-Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `frame.type` can be used to send fine-grained keyboard events. To fill values in form fields, use [`frame.fill`](#framefillselector-value-options).
+Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `frame.type` can be used to
+send fine-grained keyboard events. To fill values in form fields, use [`frame.fill`](#framefillselector-value-options).
To press a special key, like `Control` or `ArrowDown`, use [`keyboard.press`](#keyboardpresskey-options).
@@ -2482,7 +2631,8 @@ This method checks an element matching `selector` by performing the following st
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
1. Ensure that the element is now unchecked. If not, this method rejects.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
#### frame.url()
- returns: <[string]>
@@ -2492,12 +2642,13 @@ Returns frame's url.
#### frame.waitForFunction(pageFunction[, arg, options])
- `pageFunction` <[function]|[string]> Function to be evaluated in browser context
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
-- `options` <[Object]> Optional waiting parameters
+- `options` <[Object]>
- `polling` <[number]|"raf"> If `polling` is `'raf'`, then `pageFunction` is constantly executed in `requestAnimationFrame` callback. If `polling` is a number, then it is treated as an interval in milliseconds at which the function would be executed. Defaults to `raf`.
- %%-wait-for-timeout-%%
- returns: <[Promise]<[JSHandle]>> Promise which resolves when the `pageFunction` returns a truthy value. It resolves to a JSHandle of the truthy value.
The `waitForFunction` can be used to observe viewport size change:
+
```js
const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
@@ -2527,7 +2678,8 @@ await frame.waitForFunction(selector => !!document.querySelector(selector), sele
- %%-navigation-timeout-%%
- returns: <[Promise]> Promise which resolves when the required load state has been reached.
-This resolves when the frame reaches a required load state, `load` by default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.
+This resolves when the frame reaches a required load state, `load` by default. The navigation must have been committed
+when this method is called. If current document has already reached the required state, resolves immediately.
```js
await frame.click('button'); // Click triggers navigation.
@@ -2535,14 +2687,14 @@ await frame.waitForLoadState(); // The promise resolves after 'load' event.
```
#### frame.waitForNavigation([options])
-- `options` <[Object]> Navigation parameters which might have the following properties:
+- `options` <[Object]>
- %%-navigation-timeout-%%
- `url` <[string]|[RegExp]|[Function]> URL string, URL regex pattern or predicate receiving [URL] to match while waiting for the navigation.
- %%-navigation-wait-until-%%
- returns: <[Promise]<[null]|[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with `null`.
-This resolves when the frame navigates to a new URL. It is useful for when you run code
-which will indirectly cause the frame to navigate. Consider this example:
+This resolves when the frame navigates to a new URL. It is useful for when you run code which will indirectly cause the
+frame to navigate. Consider this example:
```js
const [response] = await Promise.all([
@@ -2551,7 +2703,8 @@ const [response] = await Promise.all([
]);
```
-**NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL is considered a navigation.
+**NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL is
+considered a navigation.
#### frame.waitForSelector(selector[, options])
- %%-query-selector-%%
@@ -2560,9 +2713,12 @@ const [response] = await Promise.all([
- %%-input-timeout-%%
- returns: <[Promise]<[null]|[ElementHandle]>> Promise which resolves when element specified by selector satisfies `state` option. Resolves to `null` if waiting for `hidden` or `detached`.
-Wait for the `selector` 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.
+Wait for the `selector` 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.
This method works across navigations:
+
```js
const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
@@ -2586,7 +2742,8 @@ const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
Returns a promise that resolves after the timeout.
-Note that `frame.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going to be flaky. Use signals such as network events, selectors becoming visible and others instead.
+Note that `frame.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going to
+be flaky. Use signals such as network events, selectors becoming visible and others instead.
### class: ElementHandle
* extends: [JSHandle]
@@ -2606,9 +2763,11 @@ const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
})();
```
-ElementHandle prevents DOM element from garbage collection unless the handle is [disposed](#jshandledispose). ElementHandles are auto-disposed when their origin frame gets navigated.
+ElementHandle prevents DOM element from garbage collection unless the handle is [disposed](#jshandledispose).
+ElementHandles are auto-disposed when their origin frame gets navigated.
-ElementHandle instances can be used as an argument in [`page.$eval()`](#pageevalselector-pagefunction-arg) and [`page.evaluate()`](#pageevaluatepagefunction-arg) methods.
+ElementHandle instances can be used as an argument in [`page.$eval()`](#pageevalselector-pagefunction-arg) and
+[`page.evaluate()`](#pageevaluatepagefunction-arg) methods.
<!-- GEN:toc -->
- [elementHandle.$(selector)](#elementhandleselector)
@@ -2642,6 +2801,7 @@ ElementHandle instances can be used as an argument in [`page.$eval()`](#pageeval
- [elementHandle.waitForElementState(state[, options])](#elementhandlewaitforelementstatestate-options)
- [elementHandle.waitForSelector(selector[, options])](#elementhandlewaitforselectorselector-options)
<!-- GEN:stop -->
+
<!-- GEN:toc-extends-JSHandle -->
- [jsHandle.asElement()](#jshandleaselement)
- [jsHandle.dispose()](#jshandledispose)
@@ -2656,13 +2816,17 @@ ElementHandle instances can be used as an argument in [`page.$eval()`](#pageeval
- %%-query-selector-%%
- returns: <[Promise]<[null]|[ElementHandle]>>
-The method finds an element matching the specified selector in the `ElementHandle`'s subtree. See [Working with selectors](#working-with-selectors) for more details. If no elements match the selector, the return value resolves to `null`.
+The method finds an element matching the specified selector in the `ElementHandle`'s subtree. See [Working with
+selectors](#working-with-selectors) for more details. If no elements match the selector, the return value resolves to
+`null`.
#### elementHandle.$$(selector)
- %%-query-selector-%%
- returns: <[Promise]<[Array]<[ElementHandle]>>>
-The method finds all elements matching the specified selector in the `ElementHandle`s subtree. See [Working with selectors](#working-with-selectors) for more details. If no elements match the selector, the return value resolves to `[]`.
+The method finds all elements matching the specified selector in the `ElementHandle`s subtree. See [Working with
+selectors](#working-with-selectors) for more details. If no elements match the selector, the return value resolves to
+`[]`.
#### elementHandle.$eval(selector, pageFunction[, arg])
- %%-query-selector-%%
@@ -2670,11 +2834,14 @@ The method finds all elements matching the specified selector in the `ElementHan
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>> Promise which resolves to 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`. See [Working with selectors](#working-with-selectors) for more details. If no elements match the selector, the method throws an error.
+The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a first
+argument to `pageFunction`. See [Working with selectors](#working-with-selectors) for more details. If no elements match
+the selector, the method throws an error.
If `pageFunction` returns a [Promise], then `frame.$eval` would wait for the promise to resolve and return its value.
Examples:
+
```js
const tweetHandle = await page.$('.tweet');
expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');
@@ -2687,17 +2854,21 @@ expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>> Promise which resolves to 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`. See [Working with selectors](#working-with-selectors) for more details.
+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`. See [Working with selectors](#working-with-selectors) for more
+details.
If `pageFunction` returns a [Promise], then `frame.$$eval` would wait for the promise to resolve and return its value.
Examples:
+
```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!']);
@@ -2710,13 +2881,18 @@ expect(await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText))).
- width <[number]> the width of the element in pixels.
- height <[number]> the height of the element in pixels.
-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.
+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 bonding 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.
+Scrolling affects the returned bonding 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).
+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.
+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.
```js
const box = await elementHandle.boundingBox();
@@ -2740,7 +2916,8 @@ This method checks the element by performing the following steps:
If the element is detached from the DOM at any moment during the action, this method rejects.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
#### elementHandle.click([options])
- `options` <[Object]>
@@ -2762,7 +2939,8 @@ This method clicks the element by performing the following steps:
If the element is detached from the DOM at any moment during the action, this method rejects.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
#### elementHandle.contentFrame()
- returns: <[Promise]<[null]|[Frame]>> Resolves to the content frame for element handles referencing iframe nodes, or `null` otherwise
@@ -2786,7 +2964,8 @@ This method double clicks the element by performing the following steps:
If the element is detached from the DOM at any moment during the action, this method rejects.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
> **NOTE** `elementHandle.dblclick()` dispatches two `click` events and a single `dblclick` event.
@@ -2795,13 +2974,16 @@ When all steps combined have not finished during the specified `timeout`, this m
- `eventInit` <[EvaluationArgument]> event-specific initialization properties.
- returns: <[Promise]>
-The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the elment, `click` is dispatched. This is equivalend to calling [`element.click()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
+The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the elment, `click`
+is dispatched. This is equivalend to calling
+[`element.click()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
```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.
+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:
- [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
@@ -2812,7 +2994,7 @@ Since `eventInit` is event-specific, please refer to the events documentation fo
- [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
- [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
- You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
+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
@@ -2827,9 +3009,9 @@ await elementHandle.dispatchEvent('dragstart', { dataTransfer });
- %%-input-timeout-%%
- returns: <[Promise]>
-This method waits for [actionability](./actionability.md) checks, focuses the element, fills it and triggers an `input` event after filling.
-If the element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an error.
-Note that you can pass an empty string to clear the input field.
+This method waits for [actionability](./actionability.md) checks, focuses the element, fills it and triggers an `input`
+event after filling. If the element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws
+an error. Note that you can pass an empty string to clear the input field.
#### elementHandle.focus()
- returns: <[Promise]>
@@ -2858,7 +3040,8 @@ This method hovers over the element by performing the following steps:
If the element is detached from the DOM at any moment during the action, this method rejects.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
#### elementHandle.innerHTML()
- returns: <[Promise]<[string]>> Resolves to the `element.innerHTML`.
@@ -2879,20 +3062,25 @@ When all steps combined have not finished during the specified `timeout`, this m
Focuses the element, and then uses [`keyboard.down`](#keyboarddownkey) and [`keyboard.up`](#keyboardupkey).
-`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:
+`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.
+`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 suported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
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.
+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"` or `key: "Control+Shift+T"` are supported as well. When speficied with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
+Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When speficied with the
+modifier, modifier is pressed and being held while the subsequent key is being pressed.
#### elementHandle.screenshot([options])
-- `options` <[Object]> Screenshot options.
+- `options` <[Object]>
- `path` <[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 [current working directory](https://nodejs.org/api/process.html#process_process_cwd). If no path is provided, the image won't be saved to the disk.
- `type` <"png"|"jpeg"> Specify screenshot type, defaults to `png`.
- `quality` <[number]> The quality of the image, between 0-100. Not applicable to `png` images.
@@ -2900,16 +3088,20 @@ Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported a
- %%-input-timeout-%%
- returns: <[Promise]<[Buffer]>> Promise which resolves to buffer with the captured screenshot.
-This method waits for the [actionability](./actionability.md) checks, then scrolls element into view before taking a screenshot. If the element is detached from DOM, the method throws an error.
+This method waits for the [actionability](./actionability.md) checks, then scrolls element into view before taking a
+screenshot. If the element is detached from DOM, the method throws an error.
#### elementHandle.scrollIntoViewIfNeeded([options])
- `options` <[Object]>
- %%-input-timeout-%%
- returns: <[Promise]>
-This method waits for [actionability](./actionability.md) 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 waits for [actionability](./actionability.md) 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```.
-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.
+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.
#### elementHandle.selectOption(values[, options])
- `values` <[null]|[string]|[ElementHandle]|[Array]<[string]>|[Object]|[Array]<[ElementHandle]>|[Array]<[Object]>> 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 equivalent to `{value:'string'}`. Option is considered matching if all specified properties match.
@@ -2921,8 +3113,8 @@ Throws when ```elementHandle``` does not point to an element [connected](https:/
- %%-input-timeout-%%
- returns: <[Promise]<[Array]<[string]>>> An array of option values that have been successfully selected.
-Triggers a `change` and `input` event once all the provided options have been selected.
-If element is not a `<select>` element, the method throws an error.
+Triggers a `change` and `input` event once all the provided options have been selected. If element is not a `<select>`
+element, the method throws an error.
```js
// single selection matching the value
@@ -2943,7 +3135,8 @@ handle.selectOption({ value: 'blue' }, { index: 2 }, 'red');
- %%-input-timeout-%%
- returns: <[Promise]>
-This method waits for [actionability](./actionability.md) checks, then focuses the element and selects all its text content.
+This method waits for [actionability](./actionability.md) checks, then focuses the element and selects all its text
+content.
#### elementHandle.setInputFiles(files[, options])
- %%-input-files-%%
@@ -2952,9 +3145,12 @@ This method waits for [actionability](./actionability.md) checks, then focuses t
- %%-input-timeout-%%
- returns: <[Promise]>
-This method expects `elementHandle` to point to an [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
+This method expects `elementHandle` to point to an [input
+element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
-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](https://nodejs.org/api/process.html#process_process_cwd). For empty array, clears the selected files.
+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](https://nodejs.org/api/process.html#process_process_cwd). For
+empty array, clears the selected files.
#### elementHandle.tap([options])
- `options` <[Object]>
@@ -2973,7 +3169,8 @@ This method taps the element by performing the following steps:
If the element is detached from the DOM at any moment during the action, this method rejects.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
> **NOTE** `elementHandle.tap()` requires that the `hasTouch` option of the browser context be set to true.
@@ -3001,6 +3198,7 @@ await elementHandle.type('World', {delay: 100}); // Types slower, like a user
```
An example of typing into a text field and then submitting the form:
+
```js
const elementHandle = await page.$('input');
await elementHandle.type('some text');
@@ -3024,7 +3222,8 @@ This method checks the element by performing the following steps:
If the element is detached from the DOM at any moment during the action, this method rejects.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
#### elementHandle.waitForElementState(state[, options])
- `state` <"visible"|"hidden"|"stable"|"enabled"|"disabled"> A state to wait for, see below for more details.
@@ -3032,7 +3231,8 @@ When all steps combined have not finished during the specified `timeout`, this m
- %%-input-timeout-%%
- returns: <[Promise]> Promise that resolves when the element satisfies the `state`.
-Depending on the `state` parameter, this method waits for one of the [actionability](./actionability.md) checks to pass. This method throws when the element is detached while waiting, unless waiting for the `"hidden"` state.
+Depending on the `state` parameter, this method waits for one of the [actionability](./actionability.md) 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](./actionability.md#visible).
* `"hidden"` Wait until the element is [not visible](./actionability.md#visible) or [not attached](./actionability.md#attached). Note that waiting for hidden does not throw when the element detaches.
* `"stable"` Wait until the element is both [visible](./actionability.md#visible) and [stable](./actionability.md#stable).
@@ -3041,7 +3241,6 @@ Depending on the `state` parameter, this method waits for one of the [actionabil
If the element does not satisfy the condition for the `timeout` milliseconds, this method will throw.
-
#### elementHandle.waitForSelector(selector[, options])
- %%-query-selector-%%
- `options` <[Object]>
@@ -3049,7 +3248,10 @@ If the element does not satisfy the condition for the `timeout` milliseconds, th
- %%-input-timeout-%%
- returns: <[Promise]<[null]|[ElementHandle]>> Promise that resolves when element specified by selector satisfies `state` option. Resolves to `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.
+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.
```js
await page.setContent(`<div><span></span></div>`);
@@ -3058,20 +3260,26 @@ const div = await page.$('div');
const span = await div.waitForSelector('span', { state: 'attached' });
```
-> **NOTE** This method does not work across navigations, use [page.waitForSelector(selector[, options])](#pagewaitforselectorselector-options) instead.
+> **NOTE** This method does not work across navigations, use [page.waitForSelector(selector[,
+options])](#pagewaitforselectorselector-options) instead.
### class: JSHandle
-JSHandle represents an in-page JavaScript object. JSHandles can be created with the [page.evaluateHandle](#pageevaluatehandlepagefunction-arg) method.
+JSHandle represents an in-page JavaScript object. JSHandles can be created with the
+[page.evaluateHandle](#pageevaluatehandlepagefunction-arg) method.
```js
const windowHandle = await page.evaluateHandle(() => window);
// ...
```
-JSHandle prevents the referenced JavaScript object being garbage collected unless the handle is [disposed](#jshandledispose). JSHandles are auto-disposed when their origin frame gets navigated or the parent context gets destroyed.
+JSHandle prevents the referenced JavaScript object being garbage collected unless the handle is
+[disposed](#jshandledispose). 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()`](#pageevalselector-pagefunction-arg), [`page.evaluate()`](#pageevaluatepagefunction-arg) and [`page.evaluateHandle()`](#pageevaluatehandlepagefunction-arg) methods.
+JSHandle instances can be used as an argument in [`page.$eval()`](#pageevalselector-pagefunction-arg),
+[`page.evaluate()`](#pageevaluatepagefunction-arg) and [`page.evaluateHandle()`](#pageevaluatehandlepagefunction-arg)
+methods.
<!-- GEN:toc -->
- [jsHandle.asElement()](#jshandleaselement)
@@ -3100,9 +3308,11 @@ The `jsHandle.dispose` method stops referencing the element handle.
This method passes this handle as the first argument to `pageFunction`.
-If `pageFunction` returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return its value.
+If `pageFunction` returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return its
+value.
Examples:
+
```js
const tweetHandle = await page.$('.tweet .retweets');
expect(await tweetHandle.evaluate((node, suffix) => node.innerText, ' retweets')).toBe('10 retweets');
@@ -3115,9 +3325,11 @@ expect(await tweetHandle.evaluate((node, suffix) => node.innerText, ' retweets')
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 in-page object (JSHandle).
+The only difference between `jsHandle.evaluate` and `jsHandle.evaluateHandle` is that `jsHandle.evaluateHandle` returns
+in-page object (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.
+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()](#pageevaluatehandlepagefunction-arg) for more details.
@@ -3147,7 +3359,8 @@ Returns a JSON representation of the object. If the object has a
[`toJSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON()_behavior)
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.
+> **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.
### class: ConsoleMessage
@@ -3175,13 +3388,16 @@ function, it **will not be called**.
#### consoleMessage.type()
- returns: <[string]>
-One of the following values: `'log'`, `'debug'`, `'info'`, `'error'`, `'warning'`, `'dir'`, `'dirxml'`, `'table'`, `'trace'`, `'clear'`, `'startGroup'`, `'startGroupCollapsed'`, `'endGroup'`, `'assert'`, `'profile'`, `'profileEnd'`, `'count'`, `'timeEnd'`.
+One of the following values: `'log'`, `'debug'`, `'info'`, `'error'`, `'warning'`, `'dir'`, `'dirxml'`, `'table'`,
+`'trace'`, `'clear'`, `'startGroup'`, `'startGroupCollapsed'`, `'endGroup'`, `'assert'`, `'profile'`, `'profileEnd'`,
+`'count'`, `'timeEnd'`.
### class: Dialog
[Dialog] objects are dispatched by page via the ['dialog'](#event-dialog) event.
An example of using `Dialog` class:
+
```js
const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
@@ -3221,15 +3437,14 @@ const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
#### dialog.type()
- returns: <[string]> Dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`.
-
### class: Download
[Download] objects are dispatched by page via the ['download'](#event-download) event.
-All the downloaded files belonging to the browser context are deleted when the browser context is closed. All downloaded files are deleted when the browser closes.
+All the downloaded files belonging to the browser context are deleted when the browser context is closed. All downloaded
+files are deleted when the browser closes.
-Download event is emitted once the download starts. Download path becomes available
-once download completes:
+Download event is emitted once the download starts. Download path becomes available once download completes:
```js
const [ download ] = await Promise.all([
@@ -3241,7 +3456,9 @@ const path = await download.path();
...
```
-> **NOTE** Browser context **must** be created with the `acceptDownloads` set to `true` when user needs access to the downloaded content. If `acceptDownloads` is not set or set to `false`, download events are emitted, but the actual download is not performed and user has no access to the downloaded files.
+> **NOTE** Browser context **must** be created with the `acceptDownloads` set to `true` when user needs access to the
+downloaded content. If `acceptDownloads` is not set or set to `false`, download events are emitted, but the actual
+download is not performed and user has no access to the downloaded files.
<!-- GEN:toc -->
- [download.createReadStream()](#downloadcreatereadstream)
@@ -3282,14 +3499,16 @@ Saves the download to a user-specified path.
#### download.suggestedFilename()
- returns: <[string]>
-Returns suggested filename for this download. It is typically computed by the browser from the [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) response header or the `download` attribute. See the spec on [whatwg](https://html.spec.whatwg.org/#downloading-resources). Different browsers can use different logic for computing it.
+Returns suggested filename for this download. It is typically computed by the browser from the
+[`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) response header
+or the `download` attribute. See the spec on [whatwg](https://html.spec.whatwg.org/#downloading-resources). Different
+browsers can use different logic for computing it.
#### download.url()
- returns: <[string]>
Returns downloaded url.
-
### class: Video
When browser context is created with the `videosPath` option, each page has a video object associated with it.
@@ -3305,8 +3524,8 @@ console.log(await page.video().path());
#### video.path()
- returns: <[Promise]<[string]>>
-Returns the file system path this video will be recorded to. The video is guaranteed to be written to the filesystem upon closing the browser context.
-
+Returns the file system path this video will be recorded to. The video is guaranteed to be written to the filesystem
+upon closing the browser context.
### class: FileChooser
@@ -3347,15 +3566,21 @@ Returns page this file chooser belongs to.
- %%-input-timeout-%%
- returns: <[Promise]>
-Sets the value of the file input this chooser is associated with. If some of the `filePaths` are relative paths, then they are resolved relative to the [current working directory](https://nodejs.org/api/process.html#process_process_cwd). For empty array, clears the selected files.
+Sets the value of the file input this chooser is associated with. If some of the `filePaths` are relative paths, then
+they are resolved relative to the [current working directory](https://nodejs.org/api/process.html#process_process_cwd).
+For empty array, clears the selected files.
### class: Keyboard
-Keyboard provides an api for managing a virtual keyboard. The high level api is [`keyboard.type`](#keyboardtypetext-options), which takes raw characters and generates proper keydown, keypress/input, and keyup events on your page.
+Keyboard provides an api for managing a virtual keyboard. The high level api is
+[`keyboard.type`](#keyboardtypetext-options), which takes raw characters and generates proper keydown, keypress/input,
+and keyup events on your page.
-For finer control, you can use [`keyboard.down`](#keyboarddownkey), [`keyboard.up`](#keyboardupkey), and [`keyboard.insertText`](#keyboardinserttexttext) to manually fire events as if they were generated from a real keyboard.
+For finer control, you can use [`keyboard.down`](#keyboarddownkey), [`keyboard.up`](#keyboardupkey), and
+[`keyboard.insertText`](#keyboardinserttexttext) to manually fire events as if they were generated from a real keyboard.
An example of holding down `Shift` in order to select and delete some text:
+
```js
await page.keyboard.type('Hello World!');
await page.keyboard.press('ArrowLeft');
@@ -3370,6 +3595,7 @@ await page.keyboard.press('Backspace');
```
An example of pressing uppercase `A`
+
```js
await page.keyboard.press('Shift+KeyA');
// or
@@ -3377,6 +3603,7 @@ await page.keyboard.press('Shift+A');
```
An example to trigger select-all with the keyboard
+
```js
// on Windows and Linux
await page.keyboard.press('Control+A');
@@ -3398,19 +3625,26 @@ await page.keyboard.press('Meta+A');
Dispatches a `keydown` event.
-`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:
+`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.
+`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 suported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
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.
+If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
+texts.
-If `key` is a modifier key, `Shift`, `Meta`, `Control`, or `Alt`, subsequent key presses will be sent with that modifier active. To release the modifier key, use [`keyboard.up`](#keyboardupkey).
+If `key` is a modifier key, `Shift`, `Meta`, `Control`, or `Alt`, subsequent key presses will be sent with that modifier
+active. To release the modifier key, use [`keyboard.up`](#keyboardupkey).
-After the key is pressed once, subsequent calls to [`keyboard.down`](#keyboarddownkey) will have [repeat](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat) set to true. To release the key, use [`keyboard.up`](#keyboardupkey).
+After the key is pressed once, subsequent calls to [`keyboard.down`](#keyboarddownkey) will have
+[repeat](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat) set to true. To release the key, use
+[`keyboard.up`](#keyboardupkey).
> **NOTE** Modifier keys DO influence `keyboard.down`. Holding down `Shift` will type the text in upper case.
@@ -3432,17 +3666,22 @@ page.keyboard.insertText('嗨');
- `delay` <[number]> Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
- returns: <[Promise]>
-`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:
+`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.
+`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 suported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
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.
+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"` or `key: "Control+Shift+T"` are supported as well. When speficied with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
+Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When speficied with the
+modifier, modifier is pressed and being held while the subsequent key is being pressed.
```js
const page = await browser.newPage();
@@ -3525,7 +3764,8 @@ Shortcut for [`mouse.move`](#mousemovex-y-options), [`mouse.down`](#mousedownopt
- %%-input-down-up-delay-%%
- returns: <[Promise]>
-Shortcut for [`mouse.move`](#mousemovex-y-options), [`mouse.down`](#mousedownoptions), [`mouse.up`](#mouseupoptions), [`mouse.down`](#mousedownoptions) and [`mouse.up`](#mouseupoptions).
+Shortcut for [`mouse.move`](#mousemovex-y-options), [`mouse.down`](#mousedownoptions), [`mouse.up`](#mouseupoptions),
+[`mouse.down`](#mousedownoptions) and [`mouse.up`](#mouseupoptions).
#### mouse.down([options])
- `options` <[Object]>
@@ -3571,11 +3811,14 @@ Whenever the page sends a request for a network resource the following sequence
- [`'response'`](#event-response) emitted when/if the response status and headers are received for the request.
- [`'requestfinished'`](#event-requestfinished) emitted when the response body is downloaded and the request is complete.
-If request fails at some point, then instead of `'requestfinished'` event (and possibly instead of 'response' event), the [`'requestfailed'`](#event-requestfailed) event is emitted.
+If request fails at some point, then instead of `'requestfinished'` event (and possibly instead of 'response' event),
+the [`'requestfailed'`](#event-requestfailed) event is emitted.
-> **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with `'requestfinished'` event.
+> **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
+will complete with `'requestfinished'` event.
-If request gets a 'redirect' response, the request is successfully finished with the 'requestfinished' event, and a new request is issued to a redirected url.
+If request gets a 'redirect' response, the request is successfully finished with the 'requestfinished' event, and a new
+request is issued to a redirected url.
<!-- GEN:toc -->
- [request.failure()](#requestfailure)
@@ -3598,8 +3841,7 @@ If request gets a 'redirect' response, the request is successfully finished with
- returns: <[null]|[Object]> Object describing request failure, if any
- `errorText` <[string]> Human-readable error message, e.g. `'net::ERR_FAILED'`.
-The method returns `null` unless this request has failed, as reported by
-`requestfailed` event.
+The method returns `null` unless this request has failed, as reported by `requestfailed` event.
Example of logging of all the failed requests:
@@ -3632,20 +3874,25 @@ Whether this request is driving frame's navigation.
#### request.postDataJSON()
- returns: <[null]|[Object]> Parsed request's body for `form-urlencoded` and JSON as a fallback if any.
-When the response is `application/x-www-form-urlencoded` then a key/value object of the values will be returned. Otherwise it will be parsed as JSON.
+When the response is `application/x-www-form-urlencoded` then a key/value object of the values will be returned.
+Otherwise it will be parsed as JSON.
#### request.redirectedFrom()
- returns: <[null]|[Request]> Request that was redirected by the server to this one, if any.
-When the server responds with a redirect, Playwright creates a new [Request] object. The two requests are connected by `redirectedFrom()` and `redirectedTo()` methods. When multiple server redirects has happened, it is possible to construct the whole redirect chain by repeatedly calling `redirectedFrom()`.
+When the server responds with a redirect, Playwright creates a new [Request] object. The two requests are connected by
+`redirectedFrom()` and `redirectedTo()` methods. When multiple server redirects has happened, it is possible to
+construct the whole redirect chain by repeatedly calling `redirectedFrom()`.
For example, if the website `http://example.com` redirects to `https://example.com`:
+
```js
const response = await page.goto('http://example.com');
console.log(response.request().redirectedFrom().url()); // 'http://example.com'
```
If the website `https://google.com` has no redirects:
+
```js
const response = await page.goto('https://google.com');
console.log(response.request().redirectedFrom()); // null
@@ -3655,6 +3902,7 @@ console.log(response.request().redirectedFrom()); // null
- returns: <[null]|[Request]> New request issued by the browser if the server responded with redirect.
This method is the opposite of [request.redirectedFrom()](#requestredirectedfrom):
+
```js
console.log(request.redirectedFrom().redirectedTo() === request); // true
```
@@ -3662,8 +3910,9 @@ console.log(request.redirectedFrom().redirectedTo() === request); // true
#### request.resourceType()
- returns: <[string]>
-Contains the request's resource type as it was perceived by the rendering engine.
-ResourceType will be one of the following: `document`, `stylesheet`, `image`, `media`, `font`, `script`, `texttrack`, `xhr`, `fetch`, `eventsource`, `websocket`, `manifest`, `other`.
+Contains the request's resource type as it was perceived by the rendering engine. ResourceType will be one of the
+following: `document`, `stylesheet`, `image`, `media`, `font`, `script`, `texttrack`, `xhr`, `fetch`, `eventsource`,
+`websocket`, `manifest`, `other`.
#### request.response()
- returns: <[Promise]<[null]|[Response]>> A matching [Response] object, or `null` if the response was not received due to error.
@@ -3680,7 +3929,9 @@ ResourceType will be one of the following: `document`, `stylesheet`, `image`, `m
- `responseStart` <[number]> Time immediately after the browser starts requesting the resource from the server, cache, or local resource. The value is given in milliseconds relative to `startTime`, -1 if not available.
- `responseEnd` <[number]> Time immediately after the browser receives the last byte of the resource or immediately before the transport connection is closed, whichever comes first. The value is given in milliseconds relative to `startTime`, -1 if not available.
-Returns resource timing information for given request. Most of the timing values become available upon the response, `responseEnd` becomes available when request finishes. Find more information at [Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming).
+Returns resource timing information for given request. Most of the timing values become available upon the response,
+`responseEnd` becomes available when request finishes. Find more information at [Resource Timing
+API](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming).
```js
const [request] = await Promise.all([
@@ -3756,7 +4007,8 @@ Contains the URL of the response.
### class: Selectors
-Selectors can be used to install custom selector engines. See [Working with selectors](#working-with-selectors) for more information.
+Selectors can be used to install custom selector engines. See [Working with selectors](#working-with-selectors) for more
+information.
<!-- GEN:toc -->
- [selectors.register(name, script[, options])](#selectorsregistername-script-options)
@@ -3772,6 +4024,7 @@ Selectors can be used to install custom selector engines. See [Working with sele
- returns: <[Promise]>
An example of registering selector engine that queries elements based on a tag name:
+
```js
const { selectors, firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
@@ -3813,10 +4066,10 @@ const { selectors, firefox } = require('playwright'); // Or 'chromium' or 'webk
})();
```
-
### class: Route
-Whenever a network route is set up with [page.route(url, handler)](#pagerouteurl-handler) or [browserContext.route(url, handler)](#browsercontextrouteurl-handler), the `Route` object allows to handle the route.
+Whenever a network route is set up with [page.route(url, handler)](#pagerouteurl-handler) or [browserContext.route(url,
+handler)](#browsercontextrouteurl-handler), the `Route` object allows to handle the route.
<!-- GEN:toc -->
- [route.abort([errorCode])](#routeaborterrorcode)
@@ -3826,12 +4079,10 @@ Whenever a network route is set up with [page.route(url, handler)](#pagerouteurl
<!-- GEN:stop -->
#### route.abort([errorCode])
-- `errorCode` <[string]> Optional error code. Defaults to `failed`, could be
- one of the following:
+- `errorCode` <[string]> Optional error code. Defaults to `failed`, could be one of the following:
- `'aborted'` - An operation was aborted (due to user action)
- `'accessdenied'` - Permission to access a resource, other than the network, was denied
- - `'addressunreachable'` - The IP address is unreachable. This usually means
- that there is no route to the specified host or network.
+ - `'addressunreachable'` - The IP address is unreachable. This usually means that there is no route to the specified host or network.
- `'blockedbyclient'` - The client chose to block the request.
- `'blockedbyresponse'` - The request failed because the response was delivered along with requirements which are not met ('X-Frame-Options' and 'Content-Security-Policy' ancestor checks, for instance).
- `'connectionaborted'` - A connection timed out as a result of not receiving an ACK for data sent.
@@ -3901,7 +4152,6 @@ await page.route('**/xhr_endpoint', route => route.fulfill({ path: 'mock_data.js
#### route.request()
- returns: <[Request]> A request to be routed.
-
### class: WebSocket
The [WebSocket] class represents websocket connections in the page.
@@ -3954,25 +4204,30 @@ Contains the URL of the WebSocket.
- %%-wait-for-timeout-%%
- returns: <[Promise]<[Object]>> Promise which resolves to the event data value.
-Waits for event to fire and passes its value into the predicate function. Resolves when the predicate returns truthy value. Will throw an error if the webSocket is closed before the event
-is fired.
+Waits for event to fire and passes its value into the predicate function. Resolves when the predicate returns truthy
+value. Will throw an error if the webSocket is closed before the event is fired.
### class: TimeoutError
-
* extends: [Error]
-TimeoutError is emitted whenever certain operations are terminated due to timeout, e.g. [page.waitForSelector(selector[, options])](#pagewaitforselectorselector-options) or [browserType.launch([options])](#browsertypelaunchoptions).
+TimeoutError is emitted whenever certain operations are terminated due to timeout, e.g. [page.waitForSelector(selector[,
+options])](#pagewaitforselectorselector-options) or [browserType.launch([options])](#browsertypelaunchoptions).
### class: Accessibility
-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).
+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.
+Accessibility is a very platform-specific thing. On different platforms, there are different screen readers that might
+have wildly different output.
-Blink - Chromium's rendering engine - has a concept of "accessibility tree", which is then translated into different platform-specific APIs. Accessibility namespace gives users
-access to the Blink Accessibility Tree.
+Blink - Chromium's rendering engine - has a concept of "accessibility tree", which is then translated into different
+platform-specific APIs. Accessibility namespace gives users access to the Blink Accessibility Tree.
-Most of the accessibility tree gets filtered out when converting from Blink 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.
+Most of the accessibility tree gets filtered out when converting from Blink 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.
<!-- GEN:toc -->
- [accessibility.snapshot([options])](#accessibilitysnapshotoptions)
@@ -4010,19 +4265,21 @@ Most of the accessibility tree gets filtered out when converting from Blink AX T
- `orientation` <[string]> Whether the node is oriented horizontally or vertically, if applicable.
- `children` <[Array]<[Object]>> Child [AXNode]s of this node, if any, if applicable.
-Captures the current state of the accessibility tree. The returned object represents the root accessible node of the page.
+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`.
+> **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`.
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);
@@ -4041,9 +4298,9 @@ function findFocusedNode(node) {
### class: Worker
-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.
+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 => {
@@ -4073,23 +4330,27 @@ Emitted when this dedicated [WebWorker](https://developer.mozilla.org/en-US/docs
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
-If the function passed to the `worker.evaluate` returns a [Promise], then `worker.evaluate` would wait for the promise to resolve and return its value.
+If the function passed to the `worker.evaluate` returns a [Promise], then `worker.evaluate` would wait for the promise
+to resolve and return its value.
-If the function passed to the `worker.evaluate` returns a non-[Serializable] value, then `worker.evaluate` resolves to `undefined`. DevTools Protocol also supports transferring some additional values that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.
+If the function passed to the `worker.evaluate` returns a non-[Serializable] value, then `worker.evaluate` resolves to
+`undefined`. DevTools Protocol also supports transferring some additional values that are not serializable by `JSON`:
+`-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.
#### worker.evaluateHandle(pageFunction[, arg])
- `pageFunction` <[function]|[string]> Function to be evaluated in the page context
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[JSHandle]>> Promise which resolves to the return value of `pageFunction` as in-page object (JSHandle)
-The only difference between `worker.evaluate` and `worker.evaluateHandle` is that `worker.evaluateHandle` returns in-page object (JSHandle).
+The only difference between `worker.evaluate` and `worker.evaluateHandle` is that `worker.evaluateHandle` returns
+in-page object (JSHandle).
-If the function passed to the `worker.evaluateHandle` returns a [Promise], then `worker.evaluateHandle` would wait for the promise to resolve and return its value.
+If the function passed to the `worker.evaluateHandle` returns a [Promise], then `worker.evaluateHandle` would wait for
+the promise to resolve and return its value.
#### worker.url()
- returns: <[string]>
-
### class: BrowserServer
<!-- GEN:toc -->
@@ -4120,12 +4381,14 @@ Kills the browser process and waits for the process to exit.
#### browserServer.wsEndpoint()
- returns: <[string]> Browser websocket url.
-Browser websocket endpoint which can be used as an argument to [browserType.connect(options)](#browsertypeconnectoptions) to establish connection to the browser.
+Browser websocket endpoint which can be used as an argument to
+[browserType.connect(options)](#browsertypeconnectoptions) to establish connection to the browser.
### class: BrowserType
-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:
+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'.
@@ -4161,7 +4424,7 @@ This methods attaches Playwright to an existing browser instance.
- returns: <[string]> A path where Playwright expects to find a bundled browser executable.
#### browserType.launch([options])
-- `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields:
+- `options` <[Object]>
- `headless` <[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`.
- `executablePath` <[string]> Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). Note that Playwright only works with the bundled Chromium, Firefox or WebKit, use at your own risk.
- `args` <[Array]<[string]>> Additional arguments to pass to the browser instance. The list of Chromium flags can be found [here](http://peter.sh/experiments/chromium-command-line-switches/).
@@ -4184,25 +4447,32 @@ This methods attaches Playwright to an existing browser instance.
- `slowMo` <[number]> Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on.
- returns: <[Promise]<[Browser]>> Promise which resolves to browser instance.
-
You can use `ignoreDefaultArgs` to filter out `--mute-audio` from default arguments:
+
```js
const browser = await chromium.launch({ // Or 'firefox' or 'webkit'.
ignoreDefaultArgs: ['--mute-audio']
});
```
-> **Chromium-only** Playwright can also be used to control the Chrome browser, 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.
+> **Chromium-only** Playwright can also be used to control the Chrome browser, 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.
+> 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.
>
> In [browserType.launch([options])](#browsertypelaunchoptions) above, any mention of Chromium also applies to Chrome.
>
-> See [`this article`](https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/) for a description of the 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.
+> See [`this article`](https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/) for
+a description of the 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.
#### browserType.launchPersistentContext(userDataDir, [options])
- `userDataDir` <[string]> 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) and [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options#User_Profile).
-- `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields:
+- `options` <[Object]>
- `headless` <[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`.
- `executablePath` <[string]> Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). **BEWARE**: Playwright is only guaranteed to work with the bundled Chromium, Firefox or WebKit, use at your own risk.
- `args` <[Array]<[string]>> Additional arguments to pass to the browser instance. The list of Chromium flags can be found [here](http://peter.sh/experiments/chromium-command-line-switches/).
@@ -4224,10 +4494,11 @@ const browser = await chromium.launch({ // Or 'firefox' or 'webkit'.
- %%-shared-context-params-%%-as-is
- returns: <[Promise]<[BrowserContext]>> Promise that resolves to 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.
+Launches browser that uses persistent storage located at `userDataDir` and returns the only context. Closing this
+context will automatically close the browser.
#### browserType.launchServer([options])
-- `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields:
+- `options` <[Object]>
- `headless` <[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`.
- `port` <[number]> Port to use for the web socket. Defaults to 0 that picks any available port.
- `executablePath` <[string]> Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). **BEWARE**: Playwright is only guaranteed to work with the bundled Chromium, Firefox or WebKit, use at your own risk.
@@ -4250,7 +4521,8 @@ Launches browser that uses persistent storage located at `userDataDir` and retur
- `devtools` <[boolean]> **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`.
- returns: <[Promise]<[BrowserServer]>> Promise which resolves to the browser app instance.
-Launches browser server that client can connect to. An example of launching a browser executable and connecting to it later:
+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'.
@@ -4265,7 +4537,6 @@ const { chromium } = require('playwright'); // Or 'webkit' or 'firefox'.
})();
```
-
#### browserType.name()
- returns: <[string]>
@@ -4310,11 +4581,12 @@ Determines whether sink is interested in the logger with the given name and seve
- `color` <[string]> preferred logger color
### class: ChromiumBrowser
-
* extends: [Browser]
-Chromium-specific features including Tracing, service worker support, etc.
-You can use [`chromiumBrowser.startTracing`](#chromiumbrowserstarttracingpage-options) and [`chromiumBrowser.stopTracing`](#chromiumbrowserstoptracing) to create a trace file which can be opened in Chrome DevTools or [timeline viewer](https://chromedevtools.github.io/timeline-viewer/).
+Chromium-specific features including Tracing, service worker support, etc. You can use
+[`chromiumBrowser.startTracing`](#chromiumbrowserstarttracingpage-options) and
+[`chromiumBrowser.stopTracing`](#chromiumbrowserstoptracing) to create a trace file which can be opened in Chrome
+DevTools or [timeline viewer](https://chromedevtools.github.io/timeline-viewer/).
```js
await browser.startTracing(page, {path: 'trace.json'});
@@ -4327,6 +4599,7 @@ await browser.stopTracing();
- [chromiumBrowser.startTracing([page, options])](#chromiumbrowserstarttracingpage-options)
- [chromiumBrowser.stopTracing()](#chromiumbrowserstoptracing)
<!-- GEN:stop -->
+
<!-- GEN:toc-extends-Browser -->
- [event: 'disconnected'](#event-disconnected)
- [browser.close()](#browserclose)
@@ -4338,8 +4611,7 @@ await browser.stopTracing();
<!-- GEN:stop -->
#### chromiumBrowser.newBrowserCDPSession()
-- returns: <[Promise]<[CDPSession]>> Promise that resolves to the newly created browser
-session.
+- returns: <[Promise]<[CDPSession]>> Promise that resolves to the newly created browser session.
#### chromiumBrowser.startTracing([page, options])
- `page` <[Page]> Optional, if specified, tracing includes screenshots of the given page.
@@ -4355,7 +4627,6 @@ Only one trace can be active at a time per browser.
- returns: <[Promise]<[Buffer]>> Promise which resolves to buffer with trace data.
### class: ChromiumBrowserContext
-
* extends: [BrowserContext]
Chromium-specific features including background pages, service worker support, etc.
@@ -4371,6 +4642,7 @@ const backgroundPage = await context.waitForEvent('backgroundpage');
- [chromiumBrowserContext.newCDPSession(page)](#chromiumbrowsercontextnewcdpsessionpage)
- [chromiumBrowserContext.serviceWorkers()](#chromiumbrowsercontextserviceworkers)
<!-- GEN:stop -->
+
<!-- GEN:toc-extends-BrowserContext -->
- [event: 'close'](#event-close)
- [event: 'page'](#event-page)
@@ -4454,17 +4726,19 @@ const v8toIstanbul = require('v8-to-istanbul');
<!-- GEN:stop -->
#### chromiumCoverage.startCSSCoverage([options])
-- `options` <[Object]> Set of configurable options for coverage
+- `options` <[Object]>
- `resetOnNavigation` <[boolean]> Whether to reset coverage on every navigation. Defaults to `true`.
- returns: <[Promise]> Promise that resolves when coverage is started
#### chromiumCoverage.startJSCoverage([options])
-- `options` <[Object]> Set of configurable options for coverage
+- `options` <[Object]>
- `resetOnNavigation` <[boolean]> Whether to reset coverage on every navigation. Defaults to `true`.
- `reportAnonymousScripts` <[boolean]> Whether anonymous scripts generated by the page should be reported. Defaults to `false`.
- returns: <[Promise]> Promise that resolves when coverage is started
-> **NOTE** Anonymous scripts are ones that don't have an associated url. These are scripts that are dynamically created on the page using `eval` or `new Function`. If `reportAnonymousScripts` is set to `true`, anonymous scripts will have `__playwright_evaluation_script__` as their URL.
+> **NOTE** Anonymous scripts are ones that don't have an associated url. These are scripts that are dynamically created
+on the page using `eval` or `new Function`. If `reportAnonymousScripts` is set to `true`, anonymous scripts will have
+`__playwright_evaluation_script__` as their URL.
#### chromiumCoverage.stopCSSCoverage()
- returns: <[Promise]<[Array]<[Object]>>> Promise that resolves to the array of coverage reports for all stylesheets
@@ -4493,7 +4767,6 @@ const v8toIstanbul = require('v8-to-istanbul');
reported.
### class: CDPSession
-
* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
The `CDPSession` instances are used to talk raw Chrome Devtools Protocol:
@@ -4523,8 +4796,8 @@ await client.send('Animation.setPlaybackRate', {
#### cdpSession.detach()
- returns: <[Promise]>
-Detaches the CDPSession from the target. Once detached, the CDPSession object won't emit any events and can't be used
-to send messages.
+Detaches the CDPSession from the target. Once detached, the CDPSession object won't emit any events and can't be used to
+send messages.
#### cdpSession.send(method[, params])
- `method` <[string]> protocol method name
@@ -4532,7 +4805,6 @@ to send messages.
- returns: <[Promise]<[Object]>>
### class: FirefoxBrowser
-
* extends: [Browser]
Firefox browser instance does not expose Firefox-specific features.
@@ -4548,7 +4820,6 @@ Firefox browser instance does not expose Firefox-specific features.
<!-- GEN:stop -->
### class: WebKitBrowser
-
* extends: [Browser]
WebKit browser instance does not expose WebKit-specific features.
@@ -4562,3 +4833,4 @@ WebKit browser instance does not expose WebKit-specific features.
- [browser.newPage([options])](#browsernewpageoptions)
- [browser.version()](#browserversion)
<!-- GEN:stop -->
+
diff --git a/docs/api.md b/docs/api.md
index 58e96127f3..21aba96145 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -134,12 +134,13 @@ This object can be used to launch or connect to WebKit, returning instances of [
### class: Browser
-
* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
-A Browser is created when Playwright connects to a browser instance, either through [`browserType.launch`](#browsertypelaunchoptions) or [`browserType.connect`](#browsertypeconnectoptions).
+A Browser is created when Playwright connects to a browser instance, either through
+[`browserType.launch`](#browsertypelaunchoptions) or [`browserType.connect`](#browsertypeconnectoptions).
An example of using a [Browser] to create a [Page]:
+
```js
const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
@@ -151,7 +152,10 @@ const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
})();
```
-See [ChromiumBrowser], [FirefoxBrowser] and [WebKitBrowser] for browser-specific features. Note that [browserType.connect(options)](#browsertypeconnectoptions) and [browserType.launch([options])](#browsertypelaunchoptions) always return a specific browser instance, based on the browser being connected to or launched.
+See [ChromiumBrowser], [FirefoxBrowser] and [WebKitBrowser] for browser-specific features. Note that
+[browserType.connect(options)](#browsertypeconnectoptions) and
+[browserType.launch([options])](#browsertypelaunchoptions) always return a specific browser instance, based on the
+browser being connected to or launched.
<!-- GEN:toc -->
- [event: 'disconnected'](#event-disconnected)
@@ -164,6 +168,7 @@ See [ChromiumBrowser], [FirefoxBrowser] and [WebKitBrowser] for browser-specific
<!-- GEN:stop -->
#### event: 'disconnected'
+
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`](#browserclose) method was called.
@@ -171,17 +176,18 @@ Emitted when Browser gets disconnected from the browser application. This might
#### browser.close()
- returns: <[Promise]>
-In case this browser is obtained using [browserType.launch](#browsertypelaunchoptions), closes the browser and all of its pages (if any were opened).
+In case this browser is obtained using [browserType.launch](#browsertypelaunchoptions), closes the browser and all of
+its pages (if any were opened).
-In case this browser is obtained using [browserType.connect](#browsertypeconnectoptions), clears all created contexts belonging to this browser and disconnects from the browser server.
+In case this browser is obtained using [browserType.connect](#browsertypeconnectoptions), clears all created contexts
+belonging to this browser and disconnects from the browser server.
The [Browser] object itself is considered to be disposed and cannot be used anymore.
#### browser.contexts()
- returns: <[Array]<[BrowserContext]>>
-Returns an array of all open browser contexts. In a newly created browser, this will return zero
-browser contexts.
+Returns an array of all open browser contexts. In a newly created browser, this will return zero browser contexts.
```js
const browser = await pw.webkit.launch();
@@ -335,16 +341,16 @@ Creates a new browser context. It won't share cookies/cache with other browser c
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](#browsernewcontextoptions) followed by the [browserContext.newPage](#browsercontextnewpage) to control their exact life times.
+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](#browsernewcontextoptions) followed by the
+[browserContext.newPage](#browsercontextnewpage) to control their exact life times.
#### browser.version()
-
- returns: <[string]>
Returns the browser version.
### class: BrowserContext
-
* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
BrowserContexts provide a way to operate multiple independent browser sessions.
@@ -352,8 +358,8 @@ BrowserContexts provide a way to operate multiple independent browser sessions.
If a page opens another page, e.g. with a `window.open` call, the popup will belong to the parent page's browser
context.
-Playwright allows creation of "incognito" browser contexts with `browser.newContext()` method.
-"Incognito" browser contexts don't write any browsing data to disk.
+Playwright allows creation of "incognito" browser contexts with `browser.newContext()` method. "Incognito" browser
+contexts don't write any browsing data to disk.
```js
// Create a new incognito browser context
@@ -402,9 +408,13 @@ Emitted when Browser context gets closed. This might happen because of one of th
#### event: 'page'
- <[Page]>
-The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event will also fire for popup pages. See also [`Page.on('popup')`](#event-popup) to receive events about popups relevant to a specific page.
+The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event will
+also fire for popup pages. See also [`Page.on('popup')`](#event-popup) to receive events about popups relevant to a
+specific page.
-The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a popup with `window.open('http://example.com')`, this event will fire when the network request to "http://example.com" is done and its response has started loading in the popup.
+The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
+popup with `window.open('http://example.com')`, this event will fire when the network request to "http://example.com" is
+done and its response has started loading in the popup.
```js
const [page] = await Promise.all([
@@ -414,7 +424,8 @@ const [page] = await Promise.all([
console.log(await page.evaluate('location.href'));
```
-> **NOTE** Use [`page.waitForLoadState([state[, options]])`](#pagewaitforloadstatestate-options) to wait until the page gets to a particular state (you should not need it in most cases).
+> **NOTE** Use [`page.waitForLoadState([state[, options]])`](#pagewaitforloadstatestate-options) to wait until the page
+gets to a particular state (you should not need it in most cases).
#### browserContext.addCookies(cookies)
- `cookies` <[Array]<[Object]>>
@@ -444,7 +455,8 @@ Adds a script which would be evaluated in one of the following scenarios:
- Whenever a page is created in the browser context or is navigated.
- Whenever a child frame is attached or navigated in any page in the browser context. In this case, the script is evaluated in the context of the newly attached frame.
-The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed `Math.random`.
+The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend
+the JavaScript environment, e.g. to seed `Math.random`.
An example of overriding `Math.random` before the page loads:
@@ -460,7 +472,9 @@ await browserContext.addInitScript({
});
```
-> **NOTE** The order of evaluation of multiple scripts installed via [browserContext.addInitScript(script[, arg])](#browsercontextaddinitscriptscript-arg) and [page.addInitScript(script[, arg])](#pageaddinitscriptscript-arg) is not defined.
+> **NOTE** The order of evaluation of multiple scripts installed via [browserContext.addInitScript(script[,
+arg])](#browsercontextaddinitscriptscript-arg) and [page.addInitScript(script[, arg])](#pageaddinitscriptscript-arg) is
+not defined.
#### browserContext.browser()
- returns: <[null]|[Browser]> Returns the browser instance of the context. If it was launched as a persistent context null gets returned.
@@ -485,8 +499,7 @@ context.clearPermissions();
#### browserContext.close()
- returns: <[Promise]>
-Closes the browser context. All the pages that belong to the browser context
-will be closed.
+Closes the browser context. All the pages that belong to the browser context will be closed.
> **NOTE** the default browser context cannot be closed.
@@ -502,8 +515,8 @@ will be closed.
- `secure` <[boolean]>
- `sameSite` <"Strict"|"Lax"|"None">
-If no URLs are specified, this method returns all cookies.
-If URLs are specified, only cookies that affect those URLs are returned.
+If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs
+are returned.
#### browserContext.exposeBinding(name, playwrightBinding[, options])
- `name` <[string]> Name of the function on the window object.
@@ -512,16 +525,18 @@ If URLs are specified, only cookies that affect those URLs are returned.
- `handle` <[boolean]> Whether to pass the argument as a handle, instead of passing by value. When passing a handle, only one argument is supported. When passing by value, multiple arguments are supported.
- returns: <[Promise]>
-The method adds a function called `name` on the `window` object of every frame in every page in the context.
-When called, the function executes `playwrightBinding` in Node.js and returns a [Promise] which resolves to the return value of `playwrightBinding`.
-If the `playwrightBinding` returns a [Promise], it will be awaited.
+The method adds a function called `name` on the `window` object of every frame in every page in the context. When
+called, the function executes `playwrightBinding` in Node.js and returns a [Promise] which resolves to the return value
+of `playwrightBinding`. If the `playwrightBinding` returns a [Promise], it will be awaited.
-The first argument of the `playwrightBinding` function contains information about the caller:
-`{ browserContext: BrowserContext, page: Page, frame: Frame }`.
+The first argument of the `playwrightBinding` function contains information about the caller: `{ browserContext:
+BrowserContext, page: Page, frame: Frame }`.
-See [page.exposeBinding(name, playwrightBinding)](#pageexposebindingname-playwrightbinding-options) for page-only version.
+See [page.exposeBinding(name, playwrightBinding)](#pageexposebindingname-playwrightbinding-options) for page-only
+version.
An example of exposing page URL to all frames in all pages in the context:
+
```js
const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
@@ -544,6 +559,7 @@ const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
```
An example of passing an element handle:
+
```js
await context.exposeBinding('clicked', async (source, element) => {
console.log(await element.textContent());
@@ -562,14 +578,16 @@ await page.setContent(`
- `playwrightFunction` <[function]> Callback function that will be called in the Playwright's context.
- returns: <[Promise]>
-The method adds a function called `name` on the `window` object of every frame in every page in the context.
-When called, the function executes `playwrightFunction` in Node.js and returns a [Promise] which resolves to the return value of `playwrightFunction`.
+The method adds a function called `name` on the `window` object of every frame in every page in the context. When
+called, the function executes `playwrightFunction` in Node.js and returns a [Promise] which resolves to the return value
+of `playwrightFunction`.
If the `playwrightFunction` returns a [Promise], it will be awaited.
See [page.exposeFunction(name, playwrightFunction)](#pageexposefunctionname-playwrightfunction) for page-only version.
An example of adding an `md5` function to all pages in the context:
+
```js
const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
const crypto = require('crypto');
@@ -594,27 +612,28 @@ const crypto = require('crypto');
#### browserContext.grantPermissions(permissions[][, options])
- `permissions` <[Array]<[string]>> A permission or an array of permissions to grant. Permissions can be one of the following values:
- - `'geolocation'`
- - `'midi'`
- - `'midi-sysex'` (system-exclusive midi)
- - `'notifications'`
- - `'push'`
- - `'camera'`
- - `'microphone'`
- - `'background-sync'`
- - `'ambient-light-sensor'`
- - `'accelerometer'`
- - `'gyroscope'`
- - `'magnetometer'`
- - `'accessibility-events'`
- - `'clipboard-read'`
- - `'clipboard-write'`
- - `'payment-handler'`
+ - `'geolocation'`
+ - `'midi'`
+ - `'midi-sysex'` (system-exclusive midi)
+ - `'notifications'`
+ - `'push'`
+ - `'camera'`
+ - `'microphone'`
+ - `'background-sync'`
+ - `'ambient-light-sensor'`
+ - `'accelerometer'`
+ - `'gyroscope'`
+ - `'magnetometer'`
+ - `'accessibility-events'`
+ - `'clipboard-read'`
+ - `'clipboard-write'`
+ - `'payment-handler'`
- `options` <[Object]>
- `origin` <[string]> The [origin] to grant permissions to, e.g. "https://example.com".
- returns: <[Promise]>
-Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if specified.
+Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if
+specified.
#### browserContext.newPage()
- returns: <[Promise]<[Page]>>
@@ -629,8 +648,8 @@ Creates a new page in the browser context.
- `handler` <[function]\([Route], [Request]\)> handler function to route the request.
- returns: <[Promise]>
-Routing provides the capability to modify network requests that are made by any page in the browser context.
-Once route is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
+Routing provides the capability to modify network requests that are made by any page in the browser context. Once route
+is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
An example of a naïve handler that aborts all image requests:
@@ -652,7 +671,8 @@ await page.goto('https://example.com');
await browser.close();
```
-Page routes (set up with [page.route(url, handler)](#pagerouteurl-handler)) take precedence over browser context routes when request matches both handlers.
+Page routes (set up with [page.route(url, handler)](#pagerouteurl-handler)) take precedence over browser context routes
+when request matches both handlers.
> **NOTE** Enabling routing disables http cache.
@@ -667,20 +687,27 @@ This setting will change the default maximum navigation time for the following m
- [page.setContent(html[, options])](#pagesetcontenthtml-options)
- [page.waitForNavigation([options])](#pagewaitfornavigationoptions)
-> **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout) and [`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout) take priority over [`browserContext.setDefaultNavigationTimeout`](#browsercontextsetdefaultnavigationtimeouttimeout).
+> **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout) and
+[`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout) take priority over
+[`browserContext.setDefaultNavigationTimeout`](#browsercontextsetdefaultnavigationtimeouttimeout).
#### browserContext.setDefaultTimeout(timeout)
- `timeout` <[number]> Maximum time in milliseconds
This setting will change the default maximum time for all the methods accepting `timeout` option.
-> **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout), [`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout) and [`browserContext.setDefaultNavigationTimeout`](#browsercontextsetdefaultnavigationtimeouttimeout) take priority over [`browserContext.setDefaultTimeout`](#browsercontextsetdefaulttimeouttimeout).
+> **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout),
+[`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout) and
+[`browserContext.setDefaultNavigationTimeout`](#browsercontextsetdefaultnavigationtimeouttimeout) take priority over
+[`browserContext.setDefaultTimeout`](#browsercontextsetdefaulttimeouttimeout).
#### browserContext.setExtraHTTPHeaders(headers)
- `headers` <[Object]<[string], [string]>> An object containing additional HTTP headers to be sent with every request. All header values must be strings.
- returns: <[Promise]>
-The extra HTTP headers will be sent with every request initiated by any page in the context. These headers are merged with page-specific extra HTTP headers set with [page.setExtraHTTPHeaders()](#pagesetextrahttpheadersheaders). If page overrides a particular header, page-specific header value will be used instead of the browser context header value.
+The extra HTTP headers will be sent with every request initiated by any page in the context. These headers are merged
+with page-specific extra HTTP headers set with [page.setExtraHTTPHeaders()](#pagesetextrahttpheadersheaders). If page
+overrides a particular header, page-specific header value will be used instead of the browser context header value.
> **NOTE** `browserContext.setExtraHTTPHeaders` does not guarantee the order of headers in the outgoing requests.
@@ -697,7 +724,8 @@ Sets the context's geolocation. Passing `null` or `undefined` emulates position
await browserContext.setGeolocation({latitude: 59.95, longitude: 30.31667});
```
-> **NOTE** Consider using [browserContext.grantPermissions](#browsercontextgrantpermissionspermissions-options) to grant permissions for the browser context pages to read its geolocation.
+> **NOTE** Consider using [browserContext.grantPermissions](#browsercontextgrantpermissionspermissions-options) to grant
+permissions for the browser context pages to read its geolocation.
#### browserContext.setHTTPCredentials(httpCredentials)
- `httpCredentials` <[null]|[Object]>
@@ -707,7 +735,9 @@ await browserContext.setGeolocation({latitude: 59.95, longitude: 30.31667});
Provide credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
-> **NOTE** Browsers may cache credentials after successful authentication. Passing different credentials or passing `null` to disable authentication will be unreliable. To remove or replace credentials, create a new browser context instead.
+> **NOTE** Browsers may cache credentials after successful authentication. Passing different credentials or passing
+`null` to disable authentication will be unreliable. To remove or replace credentials, create a new browser context
+instead.
#### browserContext.setOffline(offline)
- `offline` <[boolean]> Whether to emulate network being offline for the browser context.
@@ -737,7 +767,8 @@ Returns storage state for this browser context, contains current cookies and loc
- `handler` <[function]\([Route], [Request]\)> Handler function used to register a routing with [browserContext.route(url, handler)](#browsercontextrouteurl-handler).
- returns: <[Promise]>
-Removes a route created with [browserContext.route(url, handler)](#browsercontextrouteurl-handler). When `handler` is not specified, removes all routes for the `url`.
+Removes a route created with [browserContext.route(url, handler)](#browsercontextrouteurl-handler). When `handler` is
+not specified, removes all routes for the `url`.
#### browserContext.waitForEvent(event[, optionsOrPredicate])
- `event` <[string]> Event name, same one would pass into `browserContext.on(event)`.
@@ -746,8 +777,8 @@ Removes a route created with [browserContext.route(url, handler)](#browsercontex
- `timeout` <[number]> 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)](#browsercontextsetdefaulttimeouttimeout).
- returns: <[Promise]<[Object]>> Promise which resolves to the event data value.
-Waits for event to fire and passes its value into the predicate function. Resolves when the predicate returns truthy value. Will throw an error if the context closes before the event
-is fired.
+Waits for event to fire and passes its value into the predicate function. Resolves when the predicate returns truthy
+value. Will throw an error if the context closes before the event is fired.
```js
const context = await browser.newContext();
@@ -755,12 +786,14 @@ await context.grantPermissions(['geolocation']);
```
### class: Page
-
* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
-Page provides methods to interact with a single tab in a [Browser], or an [extension background page](https://developer.chrome.com/extensions/background_pages) in Chromium. One [Browser] instance might have multiple [Page] instances.
+Page provides methods to interact with a single tab in a [Browser], or an [extension background
+page](https://developer.chrome.com/extensions/background_pages) in Chromium. One [Browser] instance might have multiple
+[Page] instances.
This example creates a page, navigates it to a URL, and then saves a screenshot:
+
```js
const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
@@ -774,9 +807,12 @@ const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
})();
```
-The Page class emits various events (described below) which can be handled using any of Node's native [`EventEmitter`](https://nodejs.org/api/events.html#events_class_eventemitter) methods, such as `on`, `once` or `removeListener`.
+The Page class emits various events (described below) which can be handled using any of Node's native
+[`EventEmitter`](https://nodejs.org/api/events.html#events_class_eventemitter) methods, such as `on`, `once` or
+`removeListener`.
This example logs a message for a single page `load` event:
+
```js
page.once('load', () => console.log('Page loaded!'));
```
@@ -890,11 +926,13 @@ Emitted when the page closes.
#### event: 'console'
- <[ConsoleMessage]>
-Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`. Also emitted if the page throws an error or a warning.
+Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`. Also
+emitted if the page throws an error or a warning.
The arguments passed into `console.log` appear as arguments on the event handler.
An example of handling `console` event:
+
```js
page.on('console', msg => {
for (let i = 0; i < msg.args().length; ++i)
@@ -905,9 +943,11 @@ page.evaluate(() => console.log('hello', 5, {foo: 'bar'}));
#### event: 'crash'
-Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page crashes, ongoing and subsequent operations will throw.
+Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page crashes,
+ongoing and subsequent operations will throw.
The most common way to deal with crashes is to catch an exception:
+
```js
try {
// Crash might happen during a click.
@@ -919,7 +959,8 @@ try {
}
```
-However, when manually listening to events, it might be useful to avoid stalling when the page crashes. In this case, handling `crash` event helps:
+However, when manually listening to events, it might be useful to avoid stalling when the page crashes. In this case,
+handling `crash` event helps:
```js
await new Promise((resolve, reject) => {
@@ -934,23 +975,30 @@ await new Promise((resolve, reject) => {
#### event: 'dialog'
- <[Dialog]>
-Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Playwright can respond to the dialog via [Dialog]'s [accept](#dialogacceptprompttext) or [dismiss](#dialogdismiss) methods.
+Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Playwright can respond
+to the dialog via [Dialog]'s [accept](#dialogacceptprompttext) or [dismiss](#dialogdismiss) methods.
#### event: 'domcontentloaded'
-Emitted when the JavaScript [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) event is dispatched.
+Emitted when the JavaScript [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded)
+event is dispatched.
#### event: 'download'
- <[Download]>
-Emitted when attachment download started. User can access basic file operations on downloaded content via the passed [Download] instance.
+Emitted when attachment download started. User can access basic file operations on downloaded content via the passed
+[Download] instance.
-> **NOTE** Browser context **must** be created with the `acceptDownloads` set to `true` when user needs access to the downloaded content. If `acceptDownloads` is not set or set to `false`, download events are emitted, but the actual download is not performed and user has no access to the downloaded files.
+> **NOTE** Browser context **must** be created with the `acceptDownloads` set to `true` when user needs access to the
+downloaded content. If `acceptDownloads` is not set or set to `false`, download events are emitted, but the actual
+download is not performed and user has no access to the downloaded files.
#### event: 'filechooser'
- <[FileChooser]>
-Emitted when a file chooser is supposed to appear, such as after clicking the `<input type=file>`. Playwright can respond to it via setting the input files using [`fileChooser.setFiles`](#filechoosersetfilesfiles-options) that can be uploaded after that.
+Emitted when a file chooser is supposed to appear, such as after clicking the `<input type=file>`. Playwright can
+respond to it via setting the input files using [`fileChooser.setFiles`](#filechoosersetfilesfiles-options) that can be
+uploaded after that.
```js
page.on('filechooser', async (fileChooser) => {
@@ -985,9 +1033,12 @@ Emitted when an uncaught exception happens within the page.
#### event: 'popup'
- <[Page]> Page corresponding to "popup" window
-Emitted when the page opens a new tab or window. This event is emitted in addition to the [`browserContext.on('page')`](#event-page), but only for popups relevant to this page.
+Emitted when the page opens a new tab or window. This event is emitted in addition to the
+[`browserContext.on('page')`](#event-page), but only for popups relevant to this page.
-The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a popup with `window.open('http://example.com')`, this event will fire when the network request to "http://example.com" is done and its response has started loading in the popup.
+The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
+popup with `window.open('http://example.com')`, this event will fire when the network request to "http://example.com" is
+done and its response has started loading in the popup.
```js
const [popup] = await Promise.all([
@@ -997,30 +1048,35 @@ const [popup] = await Promise.all([
console.log(await popup.evaluate('location.href'));
```
-> **NOTE** Use [`page.waitForLoadState([state[, options]])`](#pagewaitforloadstatestate-options) to wait until the page gets to a particular state (you should not need it in most cases).
+> **NOTE** Use [`page.waitForLoadState([state[, options]])`](#pagewaitforloadstatestate-options) to wait until the page
+gets to a particular state (you should not need it in most cases).
#### event: 'request'
- <[Request]>
-Emitted when a page issues a request. The [request] object is read-only.
-In order to intercept and mutate requests, see [`page.route()`](#pagerouteurl-handler) or [`browserContext.route()`](#browsercontextrouteurl-handler).
+Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests, see
+[`page.route()`](#pagerouteurl-handler) or [`browserContext.route()`](#browsercontextrouteurl-handler).
#### event: 'requestfailed'
- <[Request]>
Emitted when a request fails, for example by timing out.
-> **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with [`'requestfinished'`](#event-requestfinished) event and not with [`'requestfailed'`](#event-requestfailed).
+> **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
+will complete with [`'requestfinished'`](#event-requestfinished) event and not with
+[`'requestfailed'`](#event-requestfailed).
#### event: 'requestfinished'
- <[Request]>
-Emitted when a request finishes successfully after downloading the response body. For a successful response, the sequence of events is `request`, `response` and `requestfinished`.
+Emitted when a request finishes successfully after downloading the response body. For a successful response, the
+sequence of events is `request`, `response` and `requestfinished`.
#### event: 'response'
- <[Response]>
-Emitted when [response] status and headers are received for a request. For a successful response, the sequence of events is `request`, `response` and `requestfinished`.
+Emitted when [response] status and headers are received for a request. For a successful response, the sequence of events
+is `request`, `response` and `requestfinished`.
#### event: 'websocket'
- <[WebSocket]> websocket
@@ -1030,13 +1086,15 @@ Emitted when <[WebSocket]> request is sent.
#### event: 'worker'
- <[Worker]>
-Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned by the page.
+Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned by the
+page.
#### page.$(selector)
- `selector` <[string]> A selector to query for. See [working with selectors](#working-with-selectors) for more details.
- returns: <[Promise]<[null]|[ElementHandle]>>
-The method finds an element matching the specified selector within the page. If no elements match the selector, the return value resolves to `null`.
+The method finds an element matching the specified selector within the page. If no elements match the selector, the
+return value resolves to `null`.
Shortcut for [page.mainFrame().$(selector)](#frameselector).
@@ -1044,7 +1102,8 @@ Shortcut for [page.mainFrame().$(selector)](#frameselector).
- `selector` <[string]> A selector to query for. See [working with selectors](#working-with-selectors) for more details.
- returns: <[Promise]<[Array]<[ElementHandle]>>>
-The method finds all elements matching the specified selector within the page. If no elements match the selector, the return value resolves to `[]`.
+The method finds all elements matching the specified selector within the page. If no elements match the selector, the
+return value resolves to `[]`.
Shortcut for [page.mainFrame().$$(selector)](#frameselector-1).
@@ -1054,11 +1113,13 @@ Shortcut for [page.mainFrame().$$(selector)](#frameselector-1).
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
-The method finds an element matching the specified selector within the page and passes it as a first argument to `pageFunction`. If no elements match the selector, the method throws an error.
+The method finds an element matching the specified selector within the page 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 `page.$eval` would wait for the promise to resolve and return its value.
Examples:
+
```js
const searchValue = await page.$eval('#search', el => el.value);
const preloadHref = await page.$eval('link[rel=preload]', el => el.href);
@@ -1073,11 +1134,13 @@ Shortcut for [page.mainFrame().$eval(selector, pageFunction)](#frameevalselector
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
-The method finds all elements matching the specified selector within the page and passes an array of matched elements as a first argument to `pageFunction`.
+The method finds all elements matching the specified selector within the page and passes an array of matched elements as
+a first argument to `pageFunction`.
If `pageFunction` returns a [Promise], then `page.$$eval` would wait for the promise to resolve and return its value.
Examples:
+
```js
const divsCounts = await page.$$eval('div', (divs, min) => divs.length >= min, 10);
```
@@ -1096,7 +1159,8 @@ Adds a script which would be evaluated in one of the following scenarios:
- Whenever the page is navigated.
- Whenever the child frame is attached or navigated. In this case, the script is evaluated in the context of the newly attached frame.
-The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed `Math.random`.
+The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend
+the JavaScript environment, e.g. to seed `Math.random`.
An example of overriding `Math.random` before the page loads:
@@ -1109,7 +1173,9 @@ const preloadFile = fs.readFileSync('./preload.js', 'utf8');
await page.addInitScript(preloadFile);
```
-> **NOTE** The order of evaluation of multiple scripts installed via [browserContext.addInitScript(script[, arg])](#browsercontextaddinitscriptscript-arg) and [page.addInitScript(script[, arg])](#pageaddinitscriptscript-arg) is not defined.
+> **NOTE** The order of evaluation of multiple scripts installed via [browserContext.addInitScript(script[,
+arg])](#browsercontextaddinitscriptscript-arg) and [page.addInitScript(script[, arg])](#pageaddinitscriptscript-arg) is
+not defined.
#### page.addScriptTag(options)
- `options` <[Object]>
@@ -1130,18 +1196,16 @@ Shortcut for [page.mainFrame().addScriptTag(options)](#frameaddscripttagoptions)
- `content` <[string]> Raw CSS content to be injected into frame.
- returns: <[Promise]<[ElementHandle]>> which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
-Adds a `<link rel="stylesheet">` tag into the page with the desired url or a `<style type="text/css">` tag with the content.
+Adds a `<link rel="stylesheet">` tag into the page with the desired url or a `<style type="text/css">` tag with the
+content.
Shortcut for [page.mainFrame().addStyleTag(options)](#frameaddstyletagoptions).
-
#### page.bringToFront()
-
- returns: <[Promise]>
Brings page to front (activates tab).
-
#### page.check(selector, [options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](#working-with-selectors) for more details.
- `options` <[Object]>
@@ -1159,7 +1223,8 @@ This method checks an element matching `selector` by performing the following st
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
1. Ensure that the element is now checked. If not, this method rejects.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
Shortcut for [page.mainFrame().check(selector[, options])](#framecheckselector-options).
@@ -1185,20 +1250,19 @@ This method clicks an element matching `selector` by performing the following st
1. Use [page.mouse](#pagemouse) 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.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
Shortcut for [page.mainFrame().click(selector[, options])](#frameclickselector-options).
#### page.close([options])
- `options` <[Object]>
- - `runBeforeUnload` <[boolean]> Defaults to `false`. Whether to run the
- [before unload](https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload)
- page handlers.
+ - `runBeforeUnload` <[boolean]> Defaults to `false`. Whether to run the [before unload](https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload) page handlers.
- returns: <[Promise]>
-If `runBeforeUnload` is `false` the result will resolve only after the page has been closed.
-If `runBeforeUnload` is `true` the method will **not** wait for the page to close.
-By default, `page.close()` **does not** run beforeunload handlers.
+If `runBeforeUnload` is `false` the result will resolve only after the page has been closed. If `runBeforeUnload` is
+`true` the method will **not** wait for the page to close. By default, `page.close()` **does not** run beforeunload
+handlers.
> **NOTE** if `runBeforeUnload` is passed as true, a `beforeunload` dialog might be summoned
> and should be handled manually via page's ['dialog'](#event-dialog) event.
@@ -1209,16 +1273,15 @@ By default, `page.close()` **does not** run beforeunload handlers.
Gets the full HTML contents of the page, including the doctype.
#### page.context()
-
- returns: <[BrowserContext]>
Get the browser context that the page belongs to.
#### page.coverage
-
- returns: <[null]|[ChromiumCoverage]>
-Browser-specific Coverage implementation, only available for Chromium atm. See [ChromiumCoverage](#class-chromiumcoverage) for more details.
+Browser-specific Coverage implementation, only available for Chromium atm. See
+[ChromiumCoverage](#class-chromiumcoverage) for more details.
#### page.dblclick(selector[, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](#working-with-selectors) for more details.
@@ -1241,13 +1304,13 @@ This method double clicks an element matching `selector` by performing the follo
1. Use [page.mouse](#pagemouse) 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. Note that if the first click of the `dblclick()` triggers a navigation event, this method will reject.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
> **NOTE** `page.dblclick()` dispatches two `click` events and a single `dblclick` event.
Shortcut for [page.mainFrame().dblclick(selector[, options])](#framedblclickselector-options).
-
#### page.dispatchEvent(selector, type[, eventInit, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](#working-with-selectors) for more details.
- `type` <[string]> DOM event type: `"click"`, `"dragstart"`, etc.
@@ -1256,13 +1319,16 @@ Shortcut for [page.mainFrame().dblclick(selector[, options])](#framedblclicksele
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
-The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the elment, `click` is dispatched. This is equivalend to calling [`element.click()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
+The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the elment, `click`
+is dispatched. This is equivalend to calling
+[`element.click()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
```js
await page.dispatchEvent('button#submit', '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.
+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:
- [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
@@ -1273,7 +1339,7 @@ Since `eventInit` is event-specific, please refer to the events documentation fo
- [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
- [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
- You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
+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
@@ -1321,11 +1387,15 @@ await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').ma
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
-If the function passed to the `page.evaluate` returns a [Promise], then `page.evaluate` would wait for the promise to resolve and return its value.
+If the function passed to the `page.evaluate` returns a [Promise], then `page.evaluate` would wait for the promise to
+resolve and return its value.
-If the function passed to the `page.evaluate` returns a non-[Serializable] value, then `page.evaluate` resolves to `undefined`. DevTools Protocol also supports transferring some additional values that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.
+If the function passed to the `page.evaluate` returns a non-[Serializable] value, then `page.evaluate` resolves to
+`undefined`. DevTools Protocol also supports transferring some additional values that are not serializable by `JSON`:
+`-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.
Passing argument to `pageFunction`:
+
```js
const result = await page.evaluate(([x, y]) => {
return Promise.resolve(x * y);
@@ -1334,6 +1404,7 @@ console.log(result); // prints "56"
```
A string can also be passed in instead of a function:
+
```js
console.log(await page.evaluate('1 + 2')); // prints "3"
const x = 10;
@@ -1341,6 +1412,7 @@ console.log(await page.evaluate(`1 + ${x}`)); // prints "11"
```
[ElementHandle] instances can be passed as an argument to the `page.evaluate`:
+
```js
const bodyHandle = await page.$('body');
const html = await page.evaluate(([body, suffix]) => body.innerHTML + suffix, [bodyHandle, 'hello']);
@@ -1354,16 +1426,20 @@ Shortcut for [page.mainFrame().evaluate(pageFunction[, arg])](#frameevaluatepage
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[JSHandle]>> Promise which resolves to the return value of `pageFunction` as in-page object (JSHandle)
-The only difference between `page.evaluate` and `page.evaluateHandle` is that `page.evaluateHandle` returns in-page object (JSHandle).
+The only difference between `page.evaluate` and `page.evaluateHandle` is that `page.evaluateHandle` returns in-page
+object (JSHandle).
-If the function passed to the `page.evaluateHandle` returns a [Promise], then `page.evaluateHandle` would wait for the promise to resolve and return its value.
+If the function passed to the `page.evaluateHandle` returns a [Promise], then `page.evaluateHandle` would wait for the
+promise to resolve and return its value.
A string can also be passed in instead of a function:
+
```js
const aHandle = await page.evaluateHandle('document'); // Handle for the 'document'
```
[JSHandle] instances can be passed as an argument to the `page.evaluateHandle`:
+
```js
const aHandle = await page.evaluateHandle(() => document.body);
const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle);
@@ -1378,18 +1454,20 @@ await resultHandle.dispose();
- `handle` <[boolean]> Whether to pass the argument as a handle, instead of passing by value. When passing a handle, only one argument is supported. When passing by value, multiple arguments are supported.
- returns: <[Promise]>
-The method adds a function called `name` on the `window` object of every frame in this page.
-When called, the function executes `playwrightBinding` in Node.js and returns a [Promise] which resolves to the return value of `playwrightBinding`.
-If the `playwrightBinding` returns a [Promise], it will be awaited.
+The method adds a function called `name` on the `window` object of every frame in this page. When called, the function
+executes `playwrightBinding` in Node.js and returns a [Promise] which resolves to the return value of
+`playwrightBinding`. If the `playwrightBinding` returns a [Promise], it will be awaited.
-The first argument of the `playwrightBinding` function contains information about the caller:
-`{ browserContext: BrowserContext, page: Page, frame: Frame }`.
+The first argument of the `playwrightBinding` function contains information about the caller: `{ browserContext:
+BrowserContext, page: Page, frame: Frame }`.
-See [browserContext.exposeBinding(name, playwrightBinding)](#browsercontextexposebindingname-playwrightbinding-options) for the context-wide version.
+See [browserContext.exposeBinding(name, playwrightBinding)](#browsercontextexposebindingname-playwrightbinding-options)
+for the context-wide version.
> **NOTE** Functions installed via `page.exposeBinding` survive navigations.
An example of exposing page URL to all frames in a page:
+
```js
const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
@@ -1412,6 +1490,7 @@ const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
```
An example of passing an element handle:
+
```js
await page.exposeBinding('clicked', async (source, element) => {
console.log(await element.textContent());
@@ -1430,16 +1509,19 @@ await page.setContent(`
- `playwrightFunction` <[function]> Callback function which will be called in Playwright's context.
- returns: <[Promise]>
-The method adds a function called `name` on the `window` object of every frame in the page.
-When called, the function executes `playwrightFunction` in Node.js and returns a [Promise] which resolves to the return value of `playwrightFunction`.
+The method adds a function called `name` on the `window` object of every frame in the page. When called, the function
+executes `playwrightFunction` in Node.js and returns a [Promise] which resolves to the return value of
+`playwrightFunction`.
If the `playwrightFunction` returns a [Promise], it will be awaited.
-See [browserContext.exposeFunction(name, playwrightFunction)](#browsercontextexposefunctionname-playwrightfunction) for context-wide exposed function.
+See [browserContext.exposeFunction(name, playwrightFunction)](#browsercontextexposefunctionname-playwrightfunction) for
+context-wide exposed function.
> **NOTE** Functions installed via `page.exposeFunction` survive navigations.
An example of adding an `md5` function to the page:
+
```js
const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
const crypto = require('crypto');
@@ -1498,9 +1580,10 @@ const fs = require('fs');
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
-This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks, focuses the element, fills it and triggers an `input` event after filling.
-If the element matching `selector` is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an error.
-Note that you can pass an empty string to clear the input field.
+This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks, focuses the
+element, fills it and triggers an `input` event after filling. If the element matching `selector` is not an `<input>`,
+`<textarea>` or `[contenteditable]` element, this method throws an error. Note that you can pass an empty string to
+clear the input field.
To send fine-grained keyboard events, use [`page.type`](#pagetypeselector-text-options).
@@ -1512,8 +1595,8 @@ Shortcut for [page.mainFrame().fill()](#framefillselector-value-options)
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully focused. The promise will be rejected if there is no element matching `selector`.
-This method fetches an element with `selector` and focuses it.
-If there's no element matching `selector`, the method waits until a matching element appears in the DOM.
+This method fetches an element with `selector` and focuses it. If there's no element matching `selector`, the method
+waits until a matching element appears in the DOM.
Shortcut for [page.mainFrame().focus(selector)](#framefocusselector-options).
@@ -1546,32 +1629,30 @@ Returns frame matching the specified criteria. Either `name` or `url` must be sp
Returns element attribute value.
#### page.goBack([options])
-- `options` <[Object]> Navigation parameters which might have the following properties:
+- `options` <[Object]>
- `timeout` <[number]> Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- `waitUntil` <"load"|"domcontentloaded"|"networkidle"> When to consider operation succeeded, defaults to `load`. Events can be either:
- `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
- `'load'` - consider operation to be finished when the `load` event is fired.
- `'networkidle'` - consider operation to be finished when there are no network connections for at least `500` ms.
-- returns: <[Promise]<[null]|[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If
-can not go back, resolves to `null`.
+- returns: <[Promise]<[null]|[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go back, resolves to `null`.
Navigate to the previous page in history.
#### page.goForward([options])
-- `options` <[Object]> Navigation parameters which might have the following properties:
+- `options` <[Object]>
- `timeout` <[number]> Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- `waitUntil` <"load"|"domcontentloaded"|"networkidle"> When to consider operation succeeded, defaults to `load`. Events can be either:
- `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
- `'load'` - consider operation to be finished when the `load` event is fired.
- `'networkidle'` - consider operation to be finished when there are no network connections for at least `500` ms.
-- returns: <[Promise]<[null]|[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If
-can not go forward, resolves to `null`.
+- returns: <[Promise]<[null]|[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go forward, resolves to `null`.
Navigate to the next page in history.
#### page.goto(url[, options])
- `url` <[string]> URL to navigate page to. The url should include scheme, e.g. `https://`.
-- `options` <[Object]> Navigation parameters which might have the following properties:
+- `options` <[Object]>
- `timeout` <[number]> Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- `waitUntil` <"load"|"domcontentloaded"|"networkidle"> When to consider operation succeeded, defaults to `load`. Events can be either:
- `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
@@ -1587,11 +1668,14 @@ Navigate to the next page in history.
* the remote server does not respond or is unreachable.
* the main resource failed to load.
-`page.goto` will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling [response.status()](#responsestatus).
-
-> **NOTE** `page.goto` either throws an error or returns a main resource response. The only exceptions are navigation to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
+`page.goto` will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not
+Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling
+[response.status()](#responsestatus).
-> **NOTE** Headless mode doesn't support navigation to a PDF document. See the [upstream issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).
+> **NOTE** `page.goto` either throws an error or returns a main resource response. The only exceptions are navigation to
+`about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
+> **NOTE** Headless mode doesn't support navigation to a PDF document. See the [upstream
+issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).
Shortcut for [page.mainFrame().goto(url[, options])](#framegotourl-options)
@@ -1613,7 +1697,8 @@ This method hovers over an element matching `selector` by performing the followi
1. Use [page.mouse](#pagemouse) to hover over the center of the element, or the specified `position`.
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
Shortcut for [page.mainFrame().hover(selector[, options])](#framehoverselector-options).
@@ -1634,13 +1719,11 @@ Resolves to the `element.innerHTML`.
Resolves to the `element.innerText`.
#### page.isClosed()
-
- returns: <[boolean]>
Indicates that the page has been closed.
#### page.keyboard
-
- returns: <[Keyboard]>
#### page.mainFrame()
@@ -1649,15 +1732,13 @@ Indicates that the page has been closed.
Page is guaranteed to have a main frame which persists during navigations.
#### page.mouse
-
- returns: <[Mouse]>
#### page.opener()
-
- returns: <[Promise]<[null]|[Page]>> Promise which resolves to the opener for popup pages and `null` for others. If the opener has been closed already the promise may resolve to `null`.
#### page.pdf([options])
-- `options` <[Object]> Options object which might have the following properties:
+- `options` <[Object]>
- `path` <[string]> The file path to save the PDF to. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). If no path is provided, the PDF won't be saved to the disk.
- `scale` <[number]> Scale of the webpage rendering. Defaults to `1`. Scale amount must be between 0.1 and 2.
- `displayHeaderFooter` <[boolean]> Display header and footer. Defaults to `false`.
@@ -1684,9 +1765,12 @@ Page is guaranteed to have a main frame which persists during navigations.
> **NOTE** Generating a pdf is currently only supported in Chromium headless.
-`page.pdf()` generates a pdf of the page with `print` css media. To generate a pdf with `screen` media, call [page.emulateMedia({ media: 'screen' })](#pageemulatemediaoptions) before calling `page.pdf()`:
+`page.pdf()` generates a pdf of the page with `print` css media. To generate a pdf with `screen` media, call
+[page.emulateMedia({ media: 'screen' })](#pageemulatemediaoptions) before calling `page.pdf()`:
-> **NOTE** By default, `page.pdf()` generates a pdf with modified colors for printing. Use the [`-webkit-print-color-adjust`](https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-print-color-adjust) property to force rendering of exact colors.
+> **NOTE** By default, `page.pdf()` generates a pdf with modified colors for printing. Use the
+[`-webkit-print-color-adjust`](https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-print-color-adjust) property to
+force rendering of exact colors.
```js
// Generates a PDF with 'screen' media type.
@@ -1735,17 +1819,22 @@ The `format` options are:
Focuses the element, and then uses [`keyboard.down`](#keyboarddownkey) and [`keyboard.up`](#keyboardupkey).
-`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:
+`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.
+`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 suported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
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.
+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"` or `key: "Control+Shift+T"` are supported as well. When speficied with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
+Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When speficied with the
+modifier, modifier is pressed and being held while the subsequent key is being pressed.
```js
const page = await browser.newPage();
@@ -1760,7 +1849,7 @@ await browser.close();
```
#### page.reload([options])
-- `options` <[Object]> Navigation parameters which might have the following properties:
+- `options` <[Object]>
- `timeout` <[number]> Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- `waitUntil` <"load"|"domcontentloaded"|"networkidle"> When to consider operation succeeded, defaults to `load`. Events can be either:
- `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
@@ -1797,12 +1886,13 @@ await page.goto('https://example.com');
await browser.close();
```
-Page routes take precedence over browser context routes (set up with [browserContext.route(url, handler)](#browsercontextrouteurl-handler)) when request matches both handlers.
+Page routes take precedence over browser context routes (set up with [browserContext.route(url,
+handler)](#browsercontextrouteurl-handler)) when request matches both handlers.
> **NOTE** Enabling routing disables http cache.
#### page.screenshot([options])
-- `options` <[Object]> Options object which might have the following properties:
+- `options` <[Object]>
- `path` <[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 [current working directory](https://nodejs.org/api/process.html#process_process_cwd). If no path is provided, the image won't be saved to the disk.
- `type` <"png"|"jpeg"> Specify screenshot type, defaults to `png`.
- `quality` <[number]> The quality of the image, between 0-100. Not applicable to `png` images.
@@ -1816,7 +1906,8 @@ Page routes take precedence over browser context routes (set up with [browserCon
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]<[Buffer]>> Promise which resolves to buffer with the captured screenshot.
-> **NOTE** Screenshots take at least 1/6 second on Chromium OS X and Chromium Windows. See https://crbug.com/741689 for discussion.
+> **NOTE** Screenshots take at least 1/6 second on Chromium OS X and Chromium Windows. See https://crbug.com/741689 for
+discussion.
#### page.selectOption(selector, values[, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](#working-with-selectors) for more details.
@@ -1829,8 +1920,8 @@ Page routes take precedence over browser context routes (set up with [browserCon
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]<[Array]<[string]>>> An array of option values that have been successfully selected.
-Triggers a `change` and `input` event once all the provided options have been selected.
-If there's no `<select>` element matching `selector`, the method throws an error.
+Triggers a `change` and `input` event once all the provided options have been selected. If there's no `<select>` element
+matching `selector`, the method throws an error.
```js
// single selection matching the value
@@ -1848,7 +1939,7 @@ Shortcut for [page.mainFrame().selectOption()](#frameselectoptionselector-values
#### page.setContent(html[, options])
- `html` <[string]> HTML markup to assign to the page.
-- `options` <[Object]> Parameters which might have the following properties:
+- `options` <[Object]>
- `timeout` <[number]> Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- `waitUntil` <"load"|"domcontentloaded"|"networkidle"> When to consider operation succeeded, defaults to `load`. Events can be either:
- `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
@@ -1867,15 +1958,18 @@ This setting will change the default maximum navigation time for the following m
- [page.setContent(html[, options])](#pagesetcontenthtml-options)
- [page.waitForNavigation([options])](#pagewaitfornavigationoptions)
-> **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout) takes priority over [`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout), [`browserContext.setDefaultTimeout`](#browsercontextsetdefaulttimeouttimeout) and [`browserContext.setDefaultNavigationTimeout`](#browsercontextsetdefaultnavigationtimeouttimeout).
-
+> **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout) takes priority over
+[`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout),
+[`browserContext.setDefaultTimeout`](#browsercontextsetdefaulttimeouttimeout) and
+[`browserContext.setDefaultNavigationTimeout`](#browsercontextsetdefaultnavigationtimeouttimeout).
#### page.setDefaultTimeout(timeout)
- `timeout` <[number]> Maximum time in milliseconds
This setting will change the default maximum time for all the methods accepting `timeout` option.
-> **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout) takes priority over [`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout).
+> **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout) takes priority over
+[`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout).
#### page.setExtraHTTPHeaders(headers)
- `headers` <[Object]<[string], [string]>> An object containing additional HTTP headers to be sent with every request. All header values must be strings.
@@ -1896,10 +1990,12 @@ The extra HTTP headers will be sent with every request the page initiates.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
-This method expects `selector` to point to an [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
-
-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](https://nodejs.org/api/process.html#process_process_cwd). For empty array, clears the selected files.
+This method expects `selector` to point to an [input
+element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
+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](https://nodejs.org/api/process.html#process_process_cwd). For
+empty array, clears the selected files.
#### page.setViewportSize(viewportSize)
- `viewportSize` <[Object]>
@@ -1907,9 +2003,12 @@ Sets the value of the file input to these file paths or files. If some of the `f
- `height` <[number]> page height in pixels. **required**
- returns: <[Promise]>
-In the case of multiple pages in a single browser, each page can have its own viewport size. However, [browser.newContext([options])](#browsernewcontextoptions) allows to set viewport size (and more) for all pages in the context at once.
+In the case of multiple pages in a single browser, each page can have its own viewport size. However,
+[browser.newContext([options])](#browsernewcontextoptions) allows to set viewport size (and more) for all pages in the
+context at once.
-`page.setViewportSize` will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport size before navigating to the page.
+`page.setViewportSize` will resize the page. A lot of websites don't expect phones to change size, so you should set the
+viewport size before navigating to the page.
```js
const page = await browser.newPage();
@@ -1939,7 +2038,8 @@ This method taps an element matching `selector` by performing the following step
1. Use [page.touchscreen](#pagemouse) to tap the center of the element, or the specified `position`.
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
> **NOTE** `page.tap()` requires that the `hasTouch` option of the browser context be set to true.
@@ -1959,7 +2059,6 @@ Resolves to the `element.textContent`.
Shortcut for [page.mainFrame().title()](#frametitle).
#### page.touchscreen
-
- returns: <[Touchscreen]>
#### page.type(selector, text[, options])
@@ -1971,7 +2070,8 @@ Shortcut for [page.mainFrame().title()](#frametitle).
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
-Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `page.type` can be used to send fine-grained keyboard events. To fill values in form fields, use [`page.fill`](#pagefillselector-value-options).
+Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `page.type` can be used to send
+fine-grained keyboard events. To fill values in form fields, use [`page.fill`](#pagefillselector-value-options).
To press a special key, like `Control` or `ArrowDown`, use [`keyboard.press`](#keyboardpresskey-options).
@@ -1999,7 +2099,8 @@ This method unchecks an element matching `selector` by performing the following
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
1. Ensure that the element is now unchecked. If not, this method rejects.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
Shortcut for [page.mainFrame().uncheck(selector[, options])](#frameuncheckselector-options).
@@ -2008,7 +2109,8 @@ Shortcut for [page.mainFrame().uncheck(selector[, options])](#frameuncheckselect
- `handler` <[function]\([Route], [Request]\)> Handler function to route the request.
- returns: <[Promise]>
-Removes a route created with [page.route(url, handler)](#pagerouteurl-handler). When `handler` is not specified, removes all routes for the `url`.
+Removes a route created with [page.route(url, handler)](#pagerouteurl-handler). When `handler` is not specified, removes
+all routes for the `url`.
#### page.url()
- returns: <[string]>
@@ -2032,18 +2134,19 @@ Video object associated with this page.
- `timeout` <[number]> 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)](#browsercontextsetdefaulttimeouttimeout).
- returns: <[Promise]<[Object]>> Promise which resolves to the event data value.
-Waits for event to fire and passes its value into the predicate function. Resolves when the predicate returns truthy value. Will throw an error if the page is closed before the event
-is fired.
+Waits for event to fire and passes its value into the predicate function. Resolves when the predicate returns truthy
+value. Will throw an error if the page is closed before the event is fired.
#### page.waitForFunction(pageFunction[, arg, options])
- `pageFunction` <[function]|[string]> Function to be evaluated in browser context
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
-- `options` <[Object]> Optional waiting parameters
+- `options` <[Object]>
- `polling` <[number]|"raf"> If `polling` is `'raf'`, then `pageFunction` is constantly executed in `requestAnimationFrame` callback. If `polling` is a number, then it is treated as an interval in milliseconds at which the function would be executed. Defaults to `raf`.
- `timeout` <[number]> 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)](#browsercontextsetdefaulttimeouttimeout).
- returns: <[Promise]<[JSHandle]>> Promise which resolves when the `pageFunction` returns a truthy value. It resolves to a JSHandle of the truthy value.
The `waitForFunction` can be used to observe viewport size change:
+
```js
const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
@@ -2064,7 +2167,8 @@ const selector = '.foo';
await page.waitForFunction(selector => !!document.querySelector(selector), selector);
```
-Shortcut for [page.mainFrame().waitForFunction(pageFunction[, arg, options])](#framewaitforfunctionpagefunction-arg-options).
+Shortcut for [page.mainFrame().waitForFunction(pageFunction[, arg,
+options])](#framewaitforfunctionpagefunction-arg-options).
#### page.waitForLoadState([state[, options]])
- `state` <"load"|"domcontentloaded"|"networkidle"> Load state to wait for, defaults to `load`. If the state has been already reached while loading current document, the method resolves immediately.
@@ -2075,7 +2179,8 @@ Shortcut for [page.mainFrame().waitForFunction(pageFunction[, arg, options])](#f
- `timeout` <[number]> Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]> Promise which resolves when the required load state has been reached.
-This resolves when the page reaches a required load state, `load` by default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.
+This resolves when the page reaches a required load state, `load` by default. The navigation must have been committed
+when this method is called. If current document has already reached the required state, resolves immediately.
```js
await page.click('button'); // Click triggers navigation.
@@ -2094,7 +2199,7 @@ console.log(await popup.title()); // Popup is ready to use.
Shortcut for [page.mainFrame().waitForLoadState([options])](#framewaitforloadstatestate-options).
#### page.waitForNavigation([options])
-- `options` <[Object]> Navigation parameters which might have the following properties:
+- `options` <[Object]>
- `timeout` <[number]> Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- `url` <[string]|[RegExp]|[Function]> A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation.
- `waitUntil` <"load"|"domcontentloaded"|"networkidle"> When to consider operation succeeded, defaults to `load`. Events can be either:
@@ -2103,8 +2208,9 @@ Shortcut for [page.mainFrame().waitForLoadState([options])](#framewaitforloadsta
- `'networkidle'` - consider operation to be finished when there are no network connections for at least `500` ms.
- returns: <[Promise]<[null]|[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with `null`.
-This resolves when the page navigates to a new URL or reloads. It is useful for when you run code
-which will indirectly cause the page to navigate. e.g. The click target has an `onclick` handler that triggers navigation from a `setTimeout`. Consider this example:
+This resolves when the page navigates to a new URL or reloads. It is useful for when you run code which will indirectly
+cause the page to navigate. e.g. The click target has an `onclick` handler that triggers navigation from a `setTimeout`.
+Consider this example:
```js
const [response] = await Promise.all([
@@ -2113,13 +2219,14 @@ const [response] = await Promise.all([
]);
```
-**NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL is considered a navigation.
+**NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL is
+considered a navigation.
Shortcut for [page.mainFrame().waitForNavigation(options)](#framewaitfornavigationoptions).
#### page.waitForRequest(urlOrPredicate[, options])
- `urlOrPredicate` <[string]|[RegExp]|[Function]> Request URL string, regex or predicate receiving [Request] object.
-- `options` <[Object]> Optional waiting parameters
+- `options` <[Object]>
- `timeout` <[number]> Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to disable the timeout. The default value can be changed by using the [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) method.
- returns: <[Promise]<[Request]>> Promise which resolves to the matched request.
@@ -2135,7 +2242,7 @@ await page.waitForRequest(request => request.url().searchParams.get('foo') === '
#### page.waitForResponse(urlOrPredicate[, options])
- `urlOrPredicate` <[string]|[RegExp]|[function]\([Response]\):[boolean]> Request URL string, regex or predicate receiving [Response] object.
-- `options` <[Object]> Optional waiting parameters
+- `options` <[Object]>
- `timeout` <[number]> Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to disable the timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]<[Response]>> Promise which resolves to the matched response.
@@ -2156,9 +2263,12 @@ return finalResponse.ok();
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]<[null]|[ElementHandle]>> Promise which resolves when element specified by selector satisfies `state` option. Resolves to `null` if waiting for `hidden` or `detached`.
-Wait for the `selector` 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.
+Wait for the `selector` 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.
This method works across navigations:
+
```js
const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
@@ -2175,7 +2285,6 @@ const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
await browser.close();
})();
```
-Shortcut for [page.mainFrame().waitForSelector(selector[, options])](#framewaitforselectorselector-options).
#### page.waitForTimeout(timeout)
- `timeout` <[number]> A timeout to wait for
@@ -2183,7 +2292,8 @@ Shortcut for [page.mainFrame().waitForSelector(selector[, options])](#framewaitf
Returns a promise that resolves after the timeout.
-Note that `page.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going to be flaky. Use signals such as network events, selectors becoming visible and others instead.
+Note that `page.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going to be
+flaky. Use signals such as network events, selectors becoming visible and others instead.
```js
// wait for 1 second
@@ -2193,14 +2303,14 @@ await page.waitForTimeout(1000);
Shortcut for [page.mainFrame().waitForTimeout(timeout)](#pagewaitfortimeouttimeout).
#### page.workers()
-- returns: <[Array]<[Worker]>>
-This method returns all of the dedicated [WebWorkers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) associated with the page.
+- returns: <[Array]<[Worker]>> This method returns all of the dedicated [WebWorkers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) associated with the page.
> **NOTE** This does not contain ServiceWorkers
### class: Frame
-At every point of time, page exposes its current frame tree via the [page.mainFrame()](#pagemainframe) and [frame.childFrames()](#framechildframes) methods.
+At every point of time, page exposes its current frame tree via the [page.mainFrame()](#pagemainframe) and
+[frame.childFrames()](#framechildframes) methods.
[Frame] object's lifecycle is controlled by three events, dispatched on the page object:
- ['frameattached'](#event-frameattached) - fired when the frame gets attached to the page. A Frame can be attached to the page only once.
@@ -2284,13 +2394,17 @@ console.log(text);
- `selector` <[string]> A selector to query for. See [working with selectors](#working-with-selectors) for more details.
- returns: <[Promise]<[null]|[ElementHandle]>> Promise which resolves to ElementHandle pointing to the frame element.
-The method finds an element matching the specified selector within the frame. See [Working with selectors](#working-with-selectors) for more details. If no elements match the selector, the return value resolves to `null`.
+The method finds an element matching the specified selector within the frame. See [Working with
+selectors](#working-with-selectors) for more details. If no elements match the selector, the return value resolves to
+`null`.
#### frame.$$(selector)
- `selector` <[string]> A selector to query for. See [working with selectors](#working-with-selectors) for more details.
- returns: <[Promise]<[Array]<[ElementHandle]>>> Promise which resolves to ElementHandles pointing to the frame elements.
-The method finds all elements matching the specified selector within the frame. See [Working with selectors](#working-with-selectors) for more details. If no elements match the selector, the return value resolves to `[]`.
+The method finds all elements matching the specified selector within the frame. See [Working with
+selectors](#working-with-selectors) for more details. If no elements match the selector, the return value resolves to
+`[]`.
#### frame.$eval(selector, pageFunction[, arg])
- `selector` <[string]> A selector to query for. See [working with selectors](#working-with-selectors) for more details.
@@ -2298,11 +2412,14 @@ The method finds all elements matching the specified selector within the frame.
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
-The method finds an element matching the specified selector within the frame and passes it as a first argument to `pageFunction`. See [Working with selectors](#working-with-selectors) for more details. If no elements match the selector, the method throws an error.
+The method finds an element matching the specified selector within the frame and passes it as a first argument to
+`pageFunction`. See [Working with selectors](#working-with-selectors) for more details. If no elements match the
+selector, the method throws an error.
If `pageFunction` returns a [Promise], then `frame.$eval` would wait for the promise to resolve and return its value.
Examples:
+
```js
const searchValue = await frame.$eval('#search', el => el.value);
const preloadHref = await frame.$eval('link[rel=preload]', el => el.href);
@@ -2315,11 +2432,13 @@ const html = await frame.$eval('.main-container', (e, suffix) => e.outerHTML + s
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
-The method finds all elements matching the specified selector within the frame and passes an array of matched elements as a first argument to `pageFunction`. See [Working with selectors](#working-with-selectors) for more details.
+The method finds all elements matching the specified selector within the frame and passes an array of matched elements
+as a first argument to `pageFunction`. See [Working with selectors](#working-with-selectors) for more details.
If `pageFunction` returns a [Promise], then `frame.$$eval` would wait for the promise to resolve and return its value.
Examples:
+
```js
const divsCounts = await frame.$$eval('div', (divs, min) => divs.length >= min, 10);
```
@@ -2341,7 +2460,8 @@ Adds a `<script>` tag into the page with the desired url or content.
- `content` <[string]> Raw CSS content to be injected into frame.
- returns: <[Promise]<[ElementHandle]>> which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
-Adds a `<link rel="stylesheet">` tag into the page with the desired url or a `<style type="text/css">` tag with the content.
+Adds a `<link rel="stylesheet">` tag into the page with the desired url or a `<style type="text/css">` tag with the
+content.
#### frame.check(selector, [options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](#working-with-selectors) for more details.
@@ -2360,7 +2480,8 @@ This method checks an element matching `selector` by performing the following st
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
1. Ensure that the element is now checked. If not, this method rejects.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
#### frame.childFrames()
- returns: <[Array]<[Frame]>>
@@ -2387,7 +2508,8 @@ This method clicks an element matching `selector` by performing the following st
1. Use [page.mouse](#pagemouse) 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.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
#### frame.content()
- returns: <[Promise]<[string]>>
@@ -2415,7 +2537,8 @@ This method double clicks an element matching `selector` by performing the follo
1. Use [page.mouse](#pagemouse) 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. Note that if the first click of the `dblclick()` triggers a navigation event, this method will reject.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
> **NOTE** `frame.dblclick()` dispatches two `click` events and a single `dblclick` event.
@@ -2427,13 +2550,16 @@ When all steps combined have not finished during the specified `timeout`, this m
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
-The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the elment, `click` is dispatched. This is equivalend to calling [`element.click()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
+The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the elment, `click`
+is dispatched. This is equivalend to calling
+[`element.click()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
```js
await frame.dispatchEvent('button#submit', '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.
+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:
- [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
@@ -2444,7 +2570,7 @@ Since `eventInit` is event-specific, please refer to the events documentation fo
- [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
- [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
- You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
+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
@@ -2457,9 +2583,12 @@ await frame.dispatchEvent('#source', 'dragstart', { dataTransfer });
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
-If the function passed to the `frame.evaluate` returns a [Promise], then `frame.evaluate` would wait for the promise to resolve and return its value.
+If the function passed to the `frame.evaluate` returns a [Promise], then `frame.evaluate` would wait for the promise to
+resolve and return its value.
-If the function passed to the `frame.evaluate` returns a non-[Serializable] value, then `frame.evaluate` resolves to `undefined`. DevTools Protocol also supports transferring some additional values that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.
+If the function passed to the `frame.evaluate` returns a non-[Serializable] value, then `frame.evaluate` resolves to
+`undefined`. DevTools Protocol also supports transferring some additional values that are not serializable by `JSON`:
+`-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.
```js
const result = await frame.evaluate(([x, y]) => {
@@ -2475,6 +2604,7 @@ console.log(await frame.evaluate('1 + 2')); // prints "3"
```
[ElementHandle] instances can be passed as an argument to the `frame.evaluate`:
+
```js
const bodyHandle = await frame.$('body');
const html = await frame.evaluate(([body, suffix]) => body.innerHTML + suffix, [bodyHandle, 'hello']);
@@ -2486,9 +2616,11 @@ await bodyHandle.dispose();
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[JSHandle]>> Promise which resolves to the return value of `pageFunction` as in-page object (JSHandle)
-The only difference between `frame.evaluate` and `frame.evaluateHandle` is that `frame.evaluateHandle` returns in-page object (JSHandle).
+The only difference between `frame.evaluate` and `frame.evaluateHandle` is that `frame.evaluateHandle` returns in-page
+object (JSHandle).
-If the function, passed to the `frame.evaluateHandle`, returns a [Promise], then `frame.evaluateHandle` would wait for the promise to resolve and return its value.
+If the function, passed to the `frame.evaluateHandle`, returns a [Promise], then `frame.evaluateHandle` would wait for
+the promise to resolve and return its value.
```js
const aWindowHandle = await frame.evaluateHandle(() => Promise.resolve(window));
@@ -2502,6 +2634,7 @@ const aHandle = await frame.evaluateHandle('document'); // Handle for the 'docum
```
[JSHandle] instances can be passed as an argument to the `frame.evaluateHandle`:
+
```js
const aHandle = await frame.evaluateHandle(() => document.body);
const resultHandle = await frame.evaluateHandle(([body, suffix]) => body.innerHTML + suffix, [aHandle, 'hello']);
@@ -2517,9 +2650,10 @@ await resultHandle.dispose();
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
-This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks, focuses the element, fills it and triggers an `input` event after filling.
-If the element matching `selector` is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an error.
-Note that you can pass an empty string to clear the input field.
+This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks, focuses the
+element, fills it and triggers an `input` event after filling. If the element matching `selector` is not an `<input>`,
+`<textarea>` or `[contenteditable]` element, this method throws an error. Note that you can pass an empty string to
+clear the input field.
To send fine-grained keyboard events, use [`frame.type`](#frametypeselector-text-options).
@@ -2529,13 +2663,14 @@ To send fine-grained keyboard events, use [`frame.type`](#frametypeselector-text
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully focused. The promise will be rejected if there is no element matching `selector`.
-This method fetches an element with `selector` and focuses it.
-If there's no element matching `selector`, the method waits until a matching element appears in the DOM.
+This method fetches an element with `selector` and focuses it. If there's no element matching `selector`, the method
+waits until a matching element appears in the DOM.
#### frame.frameElement()
- returns: <[Promise]<[ElementHandle]>> Promise that resolves with a `frame` or `iframe` element handle which corresponds to this frame.
-This is an inverse of [elementHandle.contentFrame()](#elementhandlecontentframe). Note that returned handle actually belongs to the parent frame.
+This is an inverse of [elementHandle.contentFrame()](#elementhandlecontentframe). Note that returned handle actually
+belongs to the parent frame.
This method throws an error if the frame has been detached before `frameElement()` returns.
@@ -2556,7 +2691,7 @@ Returns element attribute value.
#### frame.goto(url[, options])
- `url` <[string]> URL to navigate frame to. The url should include scheme, e.g. `https://`.
-- `options` <[Object]> Navigation parameters which might have the following properties:
+- `options` <[Object]>
- `timeout` <[number]> Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- `waitUntil` <"load"|"domcontentloaded"|"networkidle"> When to consider operation succeeded, defaults to `load`. Events can be either:
- `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
@@ -2572,12 +2707,14 @@ Returns element attribute value.
* the remote server does not respond or is unreachable.
* the main resource failed to load.
-`frame.goto` will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling [response.status()](#responsestatus).
-
-> **NOTE** `frame.goto` either throws an error or returns a main resource response. The only exceptions are navigation to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
-
-> **NOTE** Headless mode doesn't support navigation to a PDF document. See the [upstream issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).
+`frame.goto` will not throw an error when any valid HTTP status code is returned by the remote server, including 404
+"Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling
+[response.status()](#responsestatus).
+> **NOTE** `frame.goto` either throws an error or returns a main resource response. The only exceptions are navigation
+to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
+> **NOTE** Headless mode doesn't support navigation to a PDF document. See the [upstream
+issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).
#### frame.hover(selector[, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](#working-with-selectors) for more details.
@@ -2597,7 +2734,8 @@ This method hovers over an element matching `selector` by performing the followi
1. Use [page.mouse](#pagemouse) to hover over the center of the element, or the specified `position`.
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
#### frame.innerHTML(selector[, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](#working-with-selectors) for more details.
@@ -2627,7 +2765,8 @@ Returns frame's name attribute as specified in the tag.
If the name is empty, returns the id attribute instead.
-> **NOTE** This value is calculated once when the frame is created, and will not update if the attribute is changed later.
+> **NOTE** This value is calculated once when the frame is created, and will not update if the attribute is changed
+later.
#### frame.page()
- returns: <[Page]>
@@ -2646,17 +2785,22 @@ Returns the page containing this frame.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
-`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:
+`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.
+`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 suported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
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.
+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"` or `key: "Control+Shift+T"` are supported as well. When speficied with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
+Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When speficied with the
+modifier, modifier is pressed and being held while the subsequent key is being pressed.
#### frame.selectOption(selector, values[, options])
- `selector` <[string]> A selector to query for. See [working with selectors](#working-with-selectors) for more details.
@@ -2669,8 +2813,8 @@ Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported a
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]<[Array]<[string]>>> An array of option values that have been successfully selected.
-Triggers a `change` and `input` event once all the provided options have been selected.
-If there's no `<select>` element matching `selector`, the method throws an error.
+Triggers a `change` and `input` event once all the provided options have been selected. If there's no `<select>` element
+matching `selector`, the method throws an error.
```js
// single selection matching the value
@@ -2685,7 +2829,7 @@ frame.selectOption('select#colors', 'red', 'green', 'blue');
#### frame.setContent(html[, options])
- `html` <[string]> HTML markup to assign to the page.
-- `options` <[Object]> Parameters which might have the following properties:
+- `options` <[Object]>
- `timeout` <[number]> Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- `waitUntil` <"load"|"domcontentloaded"|"networkidle"> When to consider operation succeeded, defaults to `load`. Events can be either:
- `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
@@ -2704,9 +2848,12 @@ frame.selectOption('select#colors', 'red', 'green', 'blue');
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
-This method expects `selector` to point to an [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
+This method expects `selector` to point to an [input
+element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
-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](https://nodejs.org/api/process.html#process_process_cwd). For empty array, clears the selected files.
+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](https://nodejs.org/api/process.html#process_process_cwd). For
+empty array, clears the selected files.
#### frame.tap(selector[, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](#working-with-selectors) for more details.
@@ -2727,7 +2874,8 @@ This method taps an element matching `selector` by performing the following step
1. Use [page.touchscreen](#pagemouse) to tap the center of the element, or the specified `position`.
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
> **NOTE** `frame.tap()` requires that the `hasTouch` option of the browser context be set to true.
@@ -2751,7 +2899,8 @@ Resolves to the `element.textContent`.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
-Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `frame.type` can be used to send fine-grained keyboard events. To fill values in form fields, use [`frame.fill`](#framefillselector-value-options).
+Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `frame.type` can be used to
+send fine-grained keyboard events. To fill values in form fields, use [`frame.fill`](#framefillselector-value-options).
To press a special key, like `Control` or `ArrowDown`, use [`keyboard.press`](#keyboardpresskey-options).
@@ -2777,7 +2926,8 @@ This method checks an element matching `selector` by performing the following st
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
1. Ensure that the element is now unchecked. If not, this method rejects.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
#### frame.url()
- returns: <[string]>
@@ -2787,12 +2937,13 @@ Returns frame's url.
#### frame.waitForFunction(pageFunction[, arg, options])
- `pageFunction` <[function]|[string]> Function to be evaluated in browser context
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
-- `options` <[Object]> Optional waiting parameters
+- `options` <[Object]>
- `polling` <[number]|"raf"> If `polling` is `'raf'`, then `pageFunction` is constantly executed in `requestAnimationFrame` callback. If `polling` is a number, then it is treated as an interval in milliseconds at which the function would be executed. Defaults to `raf`.
- `timeout` <[number]> 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)](#browsercontextsetdefaulttimeouttimeout).
- returns: <[Promise]<[JSHandle]>> Promise which resolves when the `pageFunction` returns a truthy value. It resolves to a JSHandle of the truthy value.
The `waitForFunction` can be used to observe viewport size change:
+
```js
const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
@@ -2822,7 +2973,8 @@ await frame.waitForFunction(selector => !!document.querySelector(selector), sele
- `timeout` <[number]> Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]> Promise which resolves when the required load state has been reached.
-This resolves when the frame reaches a required load state, `load` by default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.
+This resolves when the frame reaches a required load state, `load` by default. The navigation must have been committed
+when this method is called. If current document has already reached the required state, resolves immediately.
```js
await frame.click('button'); // Click triggers navigation.
@@ -2830,7 +2982,7 @@ await frame.waitForLoadState(); // The promise resolves after 'load' event.
```
#### frame.waitForNavigation([options])
-- `options` <[Object]> Navigation parameters which might have the following properties:
+- `options` <[Object]>
- `timeout` <[number]> Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- `url` <[string]|[RegExp]|[Function]> URL string, URL regex pattern or predicate receiving [URL] to match while waiting for the navigation.
- `waitUntil` <"load"|"domcontentloaded"|"networkidle"> When to consider operation succeeded, defaults to `load`. Events can be either:
@@ -2839,8 +2991,8 @@ await frame.waitForLoadState(); // The promise resolves after 'load' event.
- `'networkidle'` - consider operation to be finished when there are no network connections for at least `500` ms.
- returns: <[Promise]<[null]|[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with `null`.
-This resolves when the frame navigates to a new URL. It is useful for when you run code
-which will indirectly cause the frame to navigate. Consider this example:
+This resolves when the frame navigates to a new URL. It is useful for when you run code which will indirectly cause the
+frame to navigate. Consider this example:
```js
const [response] = await Promise.all([
@@ -2849,7 +3001,8 @@ const [response] = await Promise.all([
]);
```
-**NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL is considered a navigation.
+**NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL is
+considered a navigation.
#### frame.waitForSelector(selector[, options])
- `selector` <[string]> A selector to query for. See [working with selectors](#working-with-selectors) for more details.
@@ -2862,9 +3015,12 @@ const [response] = await Promise.all([
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]<[null]|[ElementHandle]>> Promise which resolves when element specified by selector satisfies `state` option. Resolves to `null` if waiting for `hidden` or `detached`.
-Wait for the `selector` 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.
+Wait for the `selector` 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.
This method works across navigations:
+
```js
const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
@@ -2888,7 +3044,8 @@ const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
Returns a promise that resolves after the timeout.
-Note that `frame.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going to be flaky. Use signals such as network events, selectors becoming visible and others instead.
+Note that `frame.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going to
+be flaky. Use signals such as network events, selectors becoming visible and others instead.
### class: ElementHandle
* extends: [JSHandle]
@@ -2908,9 +3065,11 @@ const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
})();
```
-ElementHandle prevents DOM element from garbage collection unless the handle is [disposed](#jshandledispose). ElementHandles are auto-disposed when their origin frame gets navigated.
+ElementHandle prevents DOM element from garbage collection unless the handle is [disposed](#jshandledispose).
+ElementHandles are auto-disposed when their origin frame gets navigated.
-ElementHandle instances can be used as an argument in [`page.$eval()`](#pageevalselector-pagefunction-arg) and [`page.evaluate()`](#pageevaluatepagefunction-arg) methods.
+ElementHandle instances can be used as an argument in [`page.$eval()`](#pageevalselector-pagefunction-arg) and
+[`page.evaluate()`](#pageevaluatepagefunction-arg) methods.
<!-- GEN:toc -->
- [elementHandle.$(selector)](#elementhandleselector)
@@ -2944,6 +3103,7 @@ ElementHandle instances can be used as an argument in [`page.$eval()`](#pageeval
- [elementHandle.waitForElementState(state[, options])](#elementhandlewaitforelementstatestate-options)
- [elementHandle.waitForSelector(selector[, options])](#elementhandlewaitforselectorselector-options)
<!-- GEN:stop -->
+
<!-- GEN:toc-extends-JSHandle -->
- [jsHandle.asElement()](#jshandleaselement)
- [jsHandle.dispose()](#jshandledispose)
@@ -2958,13 +3118,17 @@ ElementHandle instances can be used as an argument in [`page.$eval()`](#pageeval
- `selector` <[string]> A selector to query for. See [working with selectors](#working-with-selectors) for more details.
- returns: <[Promise]<[null]|[ElementHandle]>>
-The method finds an element matching the specified selector in the `ElementHandle`'s subtree. See [Working with selectors](#working-with-selectors) for more details. If no elements match the selector, the return value resolves to `null`.
+The method finds an element matching the specified selector in the `ElementHandle`'s subtree. See [Working with
+selectors](#working-with-selectors) for more details. If no elements match the selector, the return value resolves to
+`null`.
#### elementHandle.$$(selector)
- `selector` <[string]> A selector to query for. See [working with selectors](#working-with-selectors) for more details.
- returns: <[Promise]<[Array]<[ElementHandle]>>>
-The method finds all elements matching the specified selector in the `ElementHandle`s subtree. See [Working with selectors](#working-with-selectors) for more details. If no elements match the selector, the return value resolves to `[]`.
+The method finds all elements matching the specified selector in the `ElementHandle`s subtree. See [Working with
+selectors](#working-with-selectors) for more details. If no elements match the selector, the return value resolves to
+`[]`.
#### elementHandle.$eval(selector, pageFunction[, arg])
- `selector` <[string]> A selector to query for. See [working with selectors](#working-with-selectors) for more details.
@@ -2972,11 +3136,14 @@ The method finds all elements matching the specified selector in the `ElementHan
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>> Promise which resolves to 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`. See [Working with selectors](#working-with-selectors) for more details. If no elements match the selector, the method throws an error.
+The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a first
+argument to `pageFunction`. See [Working with selectors](#working-with-selectors) for more details. If no elements match
+the selector, the method throws an error.
If `pageFunction` returns a [Promise], then `frame.$eval` would wait for the promise to resolve and return its value.
Examples:
+
```js
const tweetHandle = await page.$('.tweet');
expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');
@@ -2989,17 +3156,21 @@ expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>> Promise which resolves to 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`. See [Working with selectors](#working-with-selectors) for more details.
+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`. See [Working with selectors](#working-with-selectors) for more
+details.
If `pageFunction` returns a [Promise], then `frame.$$eval` would wait for the promise to resolve and return its value.
Examples:
+
```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!']);
@@ -3012,13 +3183,18 @@ expect(await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText))).
- width <[number]> the width of the element in pixels.
- height <[number]> the height of the element in pixels.
-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.
+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 bonding 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.
+Scrolling affects the returned bonding 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).
+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.
+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.
```js
const box = await elementHandle.boundingBox();
@@ -3042,7 +3218,8 @@ This method checks the element by performing the following steps:
If the element is detached from the DOM at any moment during the action, this method rejects.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
#### elementHandle.click([options])
- `options` <[Object]>
@@ -3066,7 +3243,8 @@ This method clicks the element by performing the following steps:
If the element is detached from the DOM at any moment during the action, this method rejects.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
#### elementHandle.contentFrame()
- returns: <[Promise]<[null]|[Frame]>> Resolves to the content frame for element handles referencing iframe nodes, or `null` otherwise
@@ -3092,7 +3270,8 @@ This method double clicks the element by performing the following steps:
If the element is detached from the DOM at any moment during the action, this method rejects.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
> **NOTE** `elementHandle.dblclick()` dispatches two `click` events and a single `dblclick` event.
@@ -3101,13 +3280,16 @@ When all steps combined have not finished during the specified `timeout`, this m
- `eventInit` <[EvaluationArgument]> event-specific initialization properties.
- returns: <[Promise]>
-The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the elment, `click` is dispatched. This is equivalend to calling [`element.click()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
+The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the elment, `click`
+is dispatched. This is equivalend to calling
+[`element.click()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
```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.
+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:
- [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
@@ -3118,7 +3300,7 @@ Since `eventInit` is event-specific, please refer to the events documentation fo
- [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
- [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
- You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
+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
@@ -3133,9 +3315,9 @@ await elementHandle.dispatchEvent('dragstart', { dataTransfer });
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
-This method waits for [actionability](./actionability.md) checks, focuses the element, fills it and triggers an `input` event after filling.
-If the element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an error.
-Note that you can pass an empty string to clear the input field.
+This method waits for [actionability](./actionability.md) checks, focuses the element, fills it and triggers an `input`
+event after filling. If the element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws
+an error. Note that you can pass an empty string to clear the input field.
#### elementHandle.focus()
- returns: <[Promise]>
@@ -3166,7 +3348,8 @@ This method hovers over the element by performing the following steps:
If the element is detached from the DOM at any moment during the action, this method rejects.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
#### elementHandle.innerHTML()
- returns: <[Promise]<[string]>> Resolves to the `element.innerHTML`.
@@ -3187,20 +3370,25 @@ When all steps combined have not finished during the specified `timeout`, this m
Focuses the element, and then uses [`keyboard.down`](#keyboarddownkey) and [`keyboard.up`](#keyboardupkey).
-`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:
+`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.
+`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 suported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
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.
+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"` or `key: "Control+Shift+T"` are supported as well. When speficied with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
+Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When speficied with the
+modifier, modifier is pressed and being held while the subsequent key is being pressed.
#### elementHandle.screenshot([options])
-- `options` <[Object]> Screenshot options.
+- `options` <[Object]>
- `path` <[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 [current working directory](https://nodejs.org/api/process.html#process_process_cwd). If no path is provided, the image won't be saved to the disk.
- `type` <"png"|"jpeg"> Specify screenshot type, defaults to `png`.
- `quality` <[number]> The quality of the image, between 0-100. Not applicable to `png` images.
@@ -3208,16 +3396,20 @@ Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported a
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]<[Buffer]>> Promise which resolves to buffer with the captured screenshot.
-This method waits for the [actionability](./actionability.md) checks, then scrolls element into view before taking a screenshot. If the element is detached from DOM, the method throws an error.
+This method waits for the [actionability](./actionability.md) checks, then scrolls element into view before taking a
+screenshot. If the element is detached from DOM, the method throws an error.
#### elementHandle.scrollIntoViewIfNeeded([options])
- `options` <[Object]>
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
-This method waits for [actionability](./actionability.md) 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 waits for [actionability](./actionability.md) 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```.
-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.
+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.
#### elementHandle.selectOption(values[, options])
- `values` <[null]|[string]|[ElementHandle]|[Array]<[string]>|[Object]|[Array]<[ElementHandle]>|[Array]<[Object]>> 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 equivalent to `{value:'string'}`. Option is considered matching if all specified properties match.
@@ -3229,8 +3421,8 @@ Throws when ```elementHandle``` does not point to an element [connected](https:/
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]<[Array]<[string]>>> An array of option values that have been successfully selected.
-Triggers a `change` and `input` event once all the provided options have been selected.
-If element is not a `<select>` element, the method throws an error.
+Triggers a `change` and `input` event once all the provided options have been selected. If element is not a `<select>`
+element, the method throws an error.
```js
// single selection matching the value
@@ -3251,7 +3443,8 @@ handle.selectOption({ value: 'blue' }, { index: 2 }, 'red');
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
-This method waits for [actionability](./actionability.md) checks, then focuses the element and selects all its text content.
+This method waits for [actionability](./actionability.md) checks, then focuses the element and selects all its text
+content.
#### elementHandle.setInputFiles(files[, options])
- `files` <[string]|[Array]<[string]>|[Object]|[Array]<[Object]>>
@@ -3263,9 +3456,12 @@ This method waits for [actionability](./actionability.md) checks, then focuses t
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
-This method expects `elementHandle` to point to an [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
+This method expects `elementHandle` to point to an [input
+element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
-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](https://nodejs.org/api/process.html#process_process_cwd). For empty array, clears the selected files.
+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](https://nodejs.org/api/process.html#process_process_cwd). For
+empty array, clears the selected files.
#### elementHandle.tap([options])
- `options` <[Object]>
@@ -3286,7 +3482,8 @@ This method taps the element by performing the following steps:
If the element is detached from the DOM at any moment during the action, this method rejects.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
> **NOTE** `elementHandle.tap()` requires that the `hasTouch` option of the browser context be set to true.
@@ -3314,6 +3511,7 @@ await elementHandle.type('World', {delay: 100}); // Types slower, like a user
```
An example of typing into a text field and then submitting the form:
+
```js
const elementHandle = await page.$('input');
await elementHandle.type('some text');
@@ -3337,7 +3535,8 @@ This method checks the element by performing the following steps:
If the element is detached from the DOM at any moment during the action, this method rejects.
-When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
+When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
+Passing zero timeout disables this.
#### elementHandle.waitForElementState(state[, options])
- `state` <"visible"|"hidden"|"stable"|"enabled"|"disabled"> A state to wait for, see below for more details.
@@ -3345,7 +3544,8 @@ When all steps combined have not finished during the specified `timeout`, this m
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]> Promise that resolves when the element satisfies the `state`.
-Depending on the `state` parameter, this method waits for one of the [actionability](./actionability.md) checks to pass. This method throws when the element is detached while waiting, unless waiting for the `"hidden"` state.
+Depending on the `state` parameter, this method waits for one of the [actionability](./actionability.md) 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](./actionability.md#visible).
* `"hidden"` Wait until the element is [not visible](./actionability.md#visible) or [not attached](./actionability.md#attached). Note that waiting for hidden does not throw when the element detaches.
* `"stable"` Wait until the element is both [visible](./actionability.md#visible) and [stable](./actionability.md#stable).
@@ -3354,7 +3554,6 @@ Depending on the `state` parameter, this method waits for one of the [actionabil
If the element does not satisfy the condition for the `timeout` milliseconds, this method will throw.
-
#### elementHandle.waitForSelector(selector[, options])
- `selector` <[string]> A selector to query for. See [working with selectors](#working-with-selectors) for more details.
- `options` <[Object]>
@@ -3366,7 +3565,10 @@ If the element does not satisfy the condition for the `timeout` milliseconds, th
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]<[null]|[ElementHandle]>> Promise that resolves when element specified by selector satisfies `state` option. Resolves to `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.
+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.
```js
await page.setContent(`<div><span></span></div>`);
@@ -3375,20 +3577,26 @@ const div = await page.$('div');
const span = await div.waitForSelector('span', { state: 'attached' });
```
-> **NOTE** This method does not work across navigations, use [page.waitForSelector(selector[, options])](#pagewaitforselectorselector-options) instead.
+> **NOTE** This method does not work across navigations, use [page.waitForSelector(selector[,
+options])](#pagewaitforselectorselector-options) instead.
### class: JSHandle
-JSHandle represents an in-page JavaScript object. JSHandles can be created with the [page.evaluateHandle](#pageevaluatehandlepagefunction-arg) method.
+JSHandle represents an in-page JavaScript object. JSHandles can be created with the
+[page.evaluateHandle](#pageevaluatehandlepagefunction-arg) method.
```js
const windowHandle = await page.evaluateHandle(() => window);
// ...
```
-JSHandle prevents the referenced JavaScript object being garbage collected unless the handle is [disposed](#jshandledispose). JSHandles are auto-disposed when their origin frame gets navigated or the parent context gets destroyed.
+JSHandle prevents the referenced JavaScript object being garbage collected unless the handle is
+[disposed](#jshandledispose). 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()`](#pageevalselector-pagefunction-arg), [`page.evaluate()`](#pageevaluatepagefunction-arg) and [`page.evaluateHandle()`](#pageevaluatehandlepagefunction-arg) methods.
+JSHandle instances can be used as an argument in [`page.$eval()`](#pageevalselector-pagefunction-arg),
+[`page.evaluate()`](#pageevaluatepagefunction-arg) and [`page.evaluateHandle()`](#pageevaluatehandlepagefunction-arg)
+methods.
<!-- GEN:toc -->
- [jsHandle.asElement()](#jshandleaselement)
@@ -3417,9 +3625,11 @@ The `jsHandle.dispose` method stops referencing the element handle.
This method passes this handle as the first argument to `pageFunction`.
-If `pageFunction` returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return its value.
+If `pageFunction` returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return its
+value.
Examples:
+
```js
const tweetHandle = await page.$('.tweet .retweets');
expect(await tweetHandle.evaluate((node, suffix) => node.innerText, ' retweets')).toBe('10 retweets');
@@ -3432,9 +3642,11 @@ expect(await tweetHandle.evaluate((node, suffix) => node.innerText, ' retweets')
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 in-page object (JSHandle).
+The only difference between `jsHandle.evaluate` and `jsHandle.evaluateHandle` is that `jsHandle.evaluateHandle` returns
+in-page object (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.
+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()](#pageevaluatehandlepagefunction-arg) for more details.
@@ -3464,7 +3676,8 @@ Returns a JSON representation of the object. If the object has a
[`toJSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON()_behavior)
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.
+> **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.
### class: ConsoleMessage
@@ -3492,13 +3705,16 @@ function, it **will not be called**.
#### consoleMessage.type()
- returns: <[string]>
-One of the following values: `'log'`, `'debug'`, `'info'`, `'error'`, `'warning'`, `'dir'`, `'dirxml'`, `'table'`, `'trace'`, `'clear'`, `'startGroup'`, `'startGroupCollapsed'`, `'endGroup'`, `'assert'`, `'profile'`, `'profileEnd'`, `'count'`, `'timeEnd'`.
+One of the following values: `'log'`, `'debug'`, `'info'`, `'error'`, `'warning'`, `'dir'`, `'dirxml'`, `'table'`,
+`'trace'`, `'clear'`, `'startGroup'`, `'startGroupCollapsed'`, `'endGroup'`, `'assert'`, `'profile'`, `'profileEnd'`,
+`'count'`, `'timeEnd'`.
### class: Dialog
[Dialog] objects are dispatched by page via the ['dialog'](#event-dialog) event.
An example of using `Dialog` class:
+
```js
const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
@@ -3538,15 +3754,14 @@ const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
#### dialog.type()
- returns: <[string]> Dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`.
-
### class: Download
[Download] objects are dispatched by page via the ['download'](#event-download) event.
-All the downloaded files belonging to the browser context are deleted when the browser context is closed. All downloaded files are deleted when the browser closes.
+All the downloaded files belonging to the browser context are deleted when the browser context is closed. All downloaded
+files are deleted when the browser closes.
-Download event is emitted once the download starts. Download path becomes available
-once download completes:
+Download event is emitted once the download starts. Download path becomes available once download completes:
```js
const [ download ] = await Promise.all([
@@ -3558,7 +3773,9 @@ const path = await download.path();
...
```
-> **NOTE** Browser context **must** be created with the `acceptDownloads` set to `true` when user needs access to the downloaded content. If `acceptDownloads` is not set or set to `false`, download events are emitted, but the actual download is not performed and user has no access to the downloaded files.
+> **NOTE** Browser context **must** be created with the `acceptDownloads` set to `true` when user needs access to the
+downloaded content. If `acceptDownloads` is not set or set to `false`, download events are emitted, but the actual
+download is not performed and user has no access to the downloaded files.
<!-- GEN:toc -->
- [download.createReadStream()](#downloadcreatereadstream)
@@ -3599,14 +3816,16 @@ Saves the download to a user-specified path.
#### download.suggestedFilename()
- returns: <[string]>
-Returns suggested filename for this download. It is typically computed by the browser from the [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) response header or the `download` attribute. See the spec on [whatwg](https://html.spec.whatwg.org/#downloading-resources). Different browsers can use different logic for computing it.
+Returns suggested filename for this download. It is typically computed by the browser from the
+[`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) response header
+or the `download` attribute. See the spec on [whatwg](https://html.spec.whatwg.org/#downloading-resources). Different
+browsers can use different logic for computing it.
#### download.url()
- returns: <[string]>
Returns downloaded url.
-
### class: Video
When browser context is created with the `videosPath` option, each page has a video object associated with it.
@@ -3622,8 +3841,8 @@ console.log(await page.video().path());
#### video.path()
- returns: <[Promise]<[string]>>
-Returns the file system path this video will be recorded to. The video is guaranteed to be written to the filesystem upon closing the browser context.
-
+Returns the file system path this video will be recorded to. The video is guaranteed to be written to the filesystem
+upon closing the browser context.
### class: FileChooser
@@ -3667,15 +3886,21 @@ Returns page this file chooser belongs to.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
-Sets the value of the file input this chooser is associated with. If some of the `filePaths` are relative paths, then they are resolved relative to the [current working directory](https://nodejs.org/api/process.html#process_process_cwd). For empty array, clears the selected files.
+Sets the value of the file input this chooser is associated with. If some of the `filePaths` are relative paths, then
+they are resolved relative to the [current working directory](https://nodejs.org/api/process.html#process_process_cwd).
+For empty array, clears the selected files.
### class: Keyboard
-Keyboard provides an api for managing a virtual keyboard. The high level api is [`keyboard.type`](#keyboardtypetext-options), which takes raw characters and generates proper keydown, keypress/input, and keyup events on your page.
+Keyboard provides an api for managing a virtual keyboard. The high level api is
+[`keyboard.type`](#keyboardtypetext-options), which takes raw characters and generates proper keydown, keypress/input,
+and keyup events on your page.
-For finer control, you can use [`keyboard.down`](#keyboarddownkey), [`keyboard.up`](#keyboardupkey), and [`keyboard.insertText`](#keyboardinserttexttext) to manually fire events as if they were generated from a real keyboard.
+For finer control, you can use [`keyboard.down`](#keyboarddownkey), [`keyboard.up`](#keyboardupkey), and
+[`keyboard.insertText`](#keyboardinserttexttext) to manually fire events as if they were generated from a real keyboard.
An example of holding down `Shift` in order to select and delete some text:
+
```js
await page.keyboard.type('Hello World!');
await page.keyboard.press('ArrowLeft');
@@ -3690,6 +3915,7 @@ await page.keyboard.press('Backspace');
```
An example of pressing uppercase `A`
+
```js
await page.keyboard.press('Shift+KeyA');
// or
@@ -3697,6 +3923,7 @@ await page.keyboard.press('Shift+A');
```
An example to trigger select-all with the keyboard
+
```js
// on Windows and Linux
await page.keyboard.press('Control+A');
@@ -3718,19 +3945,26 @@ await page.keyboard.press('Meta+A');
Dispatches a `keydown` event.
-`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:
+`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.
+`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 suported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
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.
+If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
+texts.
-If `key` is a modifier key, `Shift`, `Meta`, `Control`, or `Alt`, subsequent key presses will be sent with that modifier active. To release the modifier key, use [`keyboard.up`](#keyboardupkey).
+If `key` is a modifier key, `Shift`, `Meta`, `Control`, or `Alt`, subsequent key presses will be sent with that modifier
+active. To release the modifier key, use [`keyboard.up`](#keyboardupkey).
-After the key is pressed once, subsequent calls to [`keyboard.down`](#keyboarddownkey) will have [repeat](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat) set to true. To release the key, use [`keyboard.up`](#keyboardupkey).
+After the key is pressed once, subsequent calls to [`keyboard.down`](#keyboarddownkey) will have
+[repeat](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat) set to true. To release the key, use
+[`keyboard.up`](#keyboardupkey).
> **NOTE** Modifier keys DO influence `keyboard.down`. Holding down `Shift` will type the text in upper case.
@@ -3752,17 +3986,22 @@ page.keyboard.insertText('嗨');
- `delay` <[number]> Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
- returns: <[Promise]>
-`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:
+`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.
+`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 suported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
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.
+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"` or `key: "Control+Shift+T"` are supported as well. When speficied with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
+Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When speficied with the
+modifier, modifier is pressed and being held while the subsequent key is being pressed.
```js
const page = await browser.newPage();
@@ -3845,7 +4084,8 @@ Shortcut for [`mouse.move`](#mousemovex-y-options), [`mouse.down`](#mousedownopt
- `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
- returns: <[Promise]>
-Shortcut for [`mouse.move`](#mousemovex-y-options), [`mouse.down`](#mousedownoptions), [`mouse.up`](#mouseupoptions), [`mouse.down`](#mousedownoptions) and [`mouse.up`](#mouseupoptions).
+Shortcut for [`mouse.move`](#mousemovex-y-options), [`mouse.down`](#mousedownoptions), [`mouse.up`](#mouseupoptions),
+[`mouse.down`](#mousedownoptions) and [`mouse.up`](#mouseupoptions).
#### mouse.down([options])
- `options` <[Object]>
@@ -3891,11 +4131,14 @@ Whenever the page sends a request for a network resource the following sequence
- [`'response'`](#event-response) emitted when/if the response status and headers are received for the request.
- [`'requestfinished'`](#event-requestfinished) emitted when the response body is downloaded and the request is complete.
-If request fails at some point, then instead of `'requestfinished'` event (and possibly instead of 'response' event), the [`'requestfailed'`](#event-requestfailed) event is emitted.
+If request fails at some point, then instead of `'requestfinished'` event (and possibly instead of 'response' event),
+the [`'requestfailed'`](#event-requestfailed) event is emitted.
-> **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with `'requestfinished'` event.
+> **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
+will complete with `'requestfinished'` event.
-If request gets a 'redirect' response, the request is successfully finished with the 'requestfinished' event, and a new request is issued to a redirected url.
+If request gets a 'redirect' response, the request is successfully finished with the 'requestfinished' event, and a new
+request is issued to a redirected url.
<!-- GEN:toc -->
- [request.failure()](#requestfailure)
@@ -3918,8 +4161,7 @@ If request gets a 'redirect' response, the request is successfully finished with
- returns: <[null]|[Object]> Object describing request failure, if any
- `errorText` <[string]> Human-readable error message, e.g. `'net::ERR_FAILED'`.
-The method returns `null` unless this request has failed, as reported by
-`requestfailed` event.
+The method returns `null` unless this request has failed, as reported by `requestfailed` event.
Example of logging of all the failed requests:
@@ -3952,20 +4194,25 @@ Whether this request is driving frame's navigation.
#### request.postDataJSON()
- returns: <[null]|[Object]> Parsed request's body for `form-urlencoded` and JSON as a fallback if any.
-When the response is `application/x-www-form-urlencoded` then a key/value object of the values will be returned. Otherwise it will be parsed as JSON.
+When the response is `application/x-www-form-urlencoded` then a key/value object of the values will be returned.
+Otherwise it will be parsed as JSON.
#### request.redirectedFrom()
- returns: <[null]|[Request]> Request that was redirected by the server to this one, if any.
-When the server responds with a redirect, Playwright creates a new [Request] object. The two requests are connected by `redirectedFrom()` and `redirectedTo()` methods. When multiple server redirects has happened, it is possible to construct the whole redirect chain by repeatedly calling `redirectedFrom()`.
+When the server responds with a redirect, Playwright creates a new [Request] object. The two requests are connected by
+`redirectedFrom()` and `redirectedTo()` methods. When multiple server redirects has happened, it is possible to
+construct the whole redirect chain by repeatedly calling `redirectedFrom()`.
For example, if the website `http://example.com` redirects to `https://example.com`:
+
```js
const response = await page.goto('http://example.com');
console.log(response.request().redirectedFrom().url()); // 'http://example.com'
```
If the website `https://google.com` has no redirects:
+
```js
const response = await page.goto('https://google.com');
console.log(response.request().redirectedFrom()); // null
@@ -3975,6 +4222,7 @@ console.log(response.request().redirectedFrom()); // null
- returns: <[null]|[Request]> New request issued by the browser if the server responded with redirect.
This method is the opposite of [request.redirectedFrom()](#requestredirectedfrom):
+
```js
console.log(request.redirectedFrom().redirectedTo() === request); // true
```
@@ -3982,8 +4230,9 @@ console.log(request.redirectedFrom().redirectedTo() === request); // true
#### request.resourceType()
- returns: <[string]>
-Contains the request's resource type as it was perceived by the rendering engine.
-ResourceType will be one of the following: `document`, `stylesheet`, `image`, `media`, `font`, `script`, `texttrack`, `xhr`, `fetch`, `eventsource`, `websocket`, `manifest`, `other`.
+Contains the request's resource type as it was perceived by the rendering engine. ResourceType will be one of the
+following: `document`, `stylesheet`, `image`, `media`, `font`, `script`, `texttrack`, `xhr`, `fetch`, `eventsource`,
+`websocket`, `manifest`, `other`.
#### request.response()
- returns: <[Promise]<[null]|[Response]>> A matching [Response] object, or `null` if the response was not received due to error.
@@ -4000,7 +4249,9 @@ ResourceType will be one of the following: `document`, `stylesheet`, `image`, `m
- `responseStart` <[number]> Time immediately after the browser starts requesting the resource from the server, cache, or local resource. The value is given in milliseconds relative to `startTime`, -1 if not available.
- `responseEnd` <[number]> Time immediately after the browser receives the last byte of the resource or immediately before the transport connection is closed, whichever comes first. The value is given in milliseconds relative to `startTime`, -1 if not available.
-Returns resource timing information for given request. Most of the timing values become available upon the response, `responseEnd` becomes available when request finishes. Find more information at [Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming).
+Returns resource timing information for given request. Most of the timing values become available upon the response,
+`responseEnd` becomes available when request finishes. Find more information at [Resource Timing
+API](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming).
```js
const [request] = await Promise.all([
@@ -4076,7 +4327,8 @@ Contains the URL of the response.
### class: Selectors
-Selectors can be used to install custom selector engines. See [Working with selectors](#working-with-selectors) for more information.
+Selectors can be used to install custom selector engines. See [Working with selectors](#working-with-selectors) for more
+information.
<!-- GEN:toc -->
- [selectors.register(name, script[, options])](#selectorsregistername-script-options)
@@ -4092,6 +4344,7 @@ Selectors can be used to install custom selector engines. See [Working with sele
- returns: <[Promise]>
An example of registering selector engine that queries elements based on a tag name:
+
```js
const { selectors, firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
@@ -4133,10 +4386,10 @@ const { selectors, firefox } = require('playwright'); // Or 'chromium' or 'webk
})();
```
-
### class: Route
-Whenever a network route is set up with [page.route(url, handler)](#pagerouteurl-handler) or [browserContext.route(url, handler)](#browsercontextrouteurl-handler), the `Route` object allows to handle the route.
+Whenever a network route is set up with [page.route(url, handler)](#pagerouteurl-handler) or [browserContext.route(url,
+handler)](#browsercontextrouteurl-handler), the `Route` object allows to handle the route.
<!-- GEN:toc -->
- [route.abort([errorCode])](#routeaborterrorcode)
@@ -4146,12 +4399,10 @@ Whenever a network route is set up with [page.route(url, handler)](#pagerouteurl
<!-- GEN:stop -->
#### route.abort([errorCode])
-- `errorCode` <[string]> Optional error code. Defaults to `failed`, could be
- one of the following:
+- `errorCode` <[string]> Optional error code. Defaults to `failed`, could be one of the following:
- `'aborted'` - An operation was aborted (due to user action)
- `'accessdenied'` - Permission to access a resource, other than the network, was denied
- - `'addressunreachable'` - The IP address is unreachable. This usually means
- that there is no route to the specified host or network.
+ - `'addressunreachable'` - The IP address is unreachable. This usually means that there is no route to the specified host or network.
- `'blockedbyclient'` - The client chose to block the request.
- `'blockedbyresponse'` - The request failed because the response was delivered along with requirements which are not met ('X-Frame-Options' and 'Content-Security-Policy' ancestor checks, for instance).
- `'connectionaborted'` - A connection timed out as a result of not receiving an ACK for data sent.
@@ -4221,7 +4472,6 @@ await page.route('**/xhr_endpoint', route => route.fulfill({ path: 'mock_data.js
#### route.request()
- returns: <[Request]> A request to be routed.
-
### class: WebSocket
The [WebSocket] class represents websocket connections in the page.
@@ -4274,25 +4524,30 @@ Contains the URL of the WebSocket.
- `timeout` <[number]> 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)](#browsercontextsetdefaulttimeouttimeout).
- returns: <[Promise]<[Object]>> Promise which resolves to the event data value.
-Waits for event to fire and passes its value into the predicate function. Resolves when the predicate returns truthy value. Will throw an error if the webSocket is closed before the event
-is fired.
+Waits for event to fire and passes its value into the predicate function. Resolves when the predicate returns truthy
+value. Will throw an error if the webSocket is closed before the event is fired.
### class: TimeoutError
-
* extends: [Error]
-TimeoutError is emitted whenever certain operations are terminated due to timeout, e.g. [page.waitForSelector(selector[, options])](#pagewaitforselectorselector-options) or [browserType.launch([options])](#browsertypelaunchoptions).
+TimeoutError is emitted whenever certain operations are terminated due to timeout, e.g. [page.waitForSelector(selector[,
+options])](#pagewaitforselectorselector-options) or [browserType.launch([options])](#browsertypelaunchoptions).
### class: Accessibility
-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).
+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.
+Accessibility is a very platform-specific thing. On different platforms, there are different screen readers that might
+have wildly different output.
-Blink - Chromium's rendering engine - has a concept of "accessibility tree", which is then translated into different platform-specific APIs. Accessibility namespace gives users
-access to the Blink Accessibility Tree.
+Blink - Chromium's rendering engine - has a concept of "accessibility tree", which is then translated into different
+platform-specific APIs. Accessibility namespace gives users access to the Blink Accessibility Tree.
-Most of the accessibility tree gets filtered out when converting from Blink 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.
+Most of the accessibility tree gets filtered out when converting from Blink 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.
<!-- GEN:toc -->
- [accessibility.snapshot([options])](#accessibilitysnapshotoptions)
@@ -4330,19 +4585,21 @@ Most of the accessibility tree gets filtered out when converting from Blink AX T
- `orientation` <[string]> Whether the node is oriented horizontally or vertically, if applicable.
- `children` <[Array]<[Object]>> Child [AXNode]s of this node, if any, if applicable.
-Captures the current state of the accessibility tree. The returned object represents the root accessible node of the page.
+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`.
+> **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`.
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);
@@ -4361,9 +4618,9 @@ function findFocusedNode(node) {
### class: Worker
-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.
+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 => {
@@ -4393,23 +4650,27 @@ Emitted when this dedicated [WebWorker](https://developer.mozilla.org/en-US/docs
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`
-If the function passed to the `worker.evaluate` returns a [Promise], then `worker.evaluate` would wait for the promise to resolve and return its value.
+If the function passed to the `worker.evaluate` returns a [Promise], then `worker.evaluate` would wait for the promise
+to resolve and return its value.
-If the function passed to the `worker.evaluate` returns a non-[Serializable] value, then `worker.evaluate` resolves to `undefined`. DevTools Protocol also supports transferring some additional values that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.
+If the function passed to the `worker.evaluate` returns a non-[Serializable] value, then `worker.evaluate` resolves to
+`undefined`. DevTools Protocol also supports transferring some additional values that are not serializable by `JSON`:
+`-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.
#### worker.evaluateHandle(pageFunction[, arg])
- `pageFunction` <[function]|[string]> Function to be evaluated in the page context
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[JSHandle]>> Promise which resolves to the return value of `pageFunction` as in-page object (JSHandle)
-The only difference between `worker.evaluate` and `worker.evaluateHandle` is that `worker.evaluateHandle` returns in-page object (JSHandle).
+The only difference between `worker.evaluate` and `worker.evaluateHandle` is that `worker.evaluateHandle` returns
+in-page object (JSHandle).
-If the function passed to the `worker.evaluateHandle` returns a [Promise], then `worker.evaluateHandle` would wait for the promise to resolve and return its value.
+If the function passed to the `worker.evaluateHandle` returns a [Promise], then `worker.evaluateHandle` would wait for
+the promise to resolve and return its value.
#### worker.url()
- returns: <[string]>
-
### class: BrowserServer
<!-- GEN:toc -->
@@ -4440,12 +4701,14 @@ Kills the browser process and waits for the process to exit.
#### browserServer.wsEndpoint()
- returns: <[string]> Browser websocket url.
-Browser websocket endpoint which can be used as an argument to [browserType.connect(options)](#browsertypeconnectoptions) to establish connection to the browser.
+Browser websocket endpoint which can be used as an argument to
+[browserType.connect(options)](#browsertypeconnectoptions) to establish connection to the browser.
### class: BrowserType
-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:
+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'.
@@ -4481,7 +4744,7 @@ This methods attaches Playwright to an existing browser instance.
- returns: <[string]> A path where Playwright expects to find a bundled browser executable.
#### browserType.launch([options])
-- `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields:
+- `options` <[Object]>
- `headless` <[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`.
- `executablePath` <[string]> Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). Note that Playwright only works with the bundled Chromium, Firefox or WebKit, use at your own risk.
- `args` <[Array]<[string]>> Additional arguments to pass to the browser instance. The list of Chromium flags can be found [here](http://peter.sh/experiments/chromium-command-line-switches/).
@@ -4504,25 +4767,32 @@ This methods attaches Playwright to an existing browser instance.
- `slowMo` <[number]> Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on.
- returns: <[Promise]<[Browser]>> Promise which resolves to browser instance.
-
You can use `ignoreDefaultArgs` to filter out `--mute-audio` from default arguments:
+
```js
const browser = await chromium.launch({ // Or 'firefox' or 'webkit'.
ignoreDefaultArgs: ['--mute-audio']
});
```
-> **Chromium-only** Playwright can also be used to control the Chrome browser, 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.
+> **Chromium-only** Playwright can also be used to control the Chrome browser, 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.
+> 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.
>
> In [browserType.launch([options])](#browsertypelaunchoptions) above, any mention of Chromium also applies to Chrome.
>
-> See [`this article`](https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/) for a description of the 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.
+> See [`this article`](https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/) for
+a description of the 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.
#### browserType.launchPersistentContext(userDataDir, [options])
- `userDataDir` <[string]> 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) and [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options#User_Profile).
-- `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields:
+- `options` <[Object]>
- `headless` <[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`.
- `executablePath` <[string]> Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). **BEWARE**: Playwright is only guaranteed to work with the bundled Chromium, Firefox or WebKit, use at your own risk.
- `args` <[Array]<[string]>> Additional arguments to pass to the browser instance. The list of Chromium flags can be found [here](http://peter.sh/experiments/chromium-command-line-switches/).
@@ -4580,10 +4850,11 @@ const browser = await chromium.launch({ // Or 'firefox' or 'webkit'.
- `height` <[number]> Video frame height.
- returns: <[Promise]<[BrowserContext]>> Promise that resolves to 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.
+Launches browser that uses persistent storage located at `userDataDir` and returns the only context. Closing this
+context will automatically close the browser.
#### browserType.launchServer([options])
-- `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields:
+- `options` <[Object]>
- `headless` <[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`.
- `port` <[number]> Port to use for the web socket. Defaults to 0 that picks any available port.
- `executablePath` <[string]> Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). **BEWARE**: Playwright is only guaranteed to work with the bundled Chromium, Firefox or WebKit, use at your own risk.
@@ -4606,7 +4877,8 @@ Launches browser that uses persistent storage located at `userDataDir` and retur
- `devtools` <[boolean]> **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`.
- returns: <[Promise]<[BrowserServer]>> Promise which resolves to the browser app instance.
-Launches browser server that client can connect to. An example of launching a browser executable and connecting to it later:
+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'.
@@ -4621,7 +4893,6 @@ const { chromium } = require('playwright'); // Or 'webkit' or 'firefox'.
})();
```
-
#### browserType.name()
- returns: <[string]>
@@ -4666,11 +4937,12 @@ Determines whether sink is interested in the logger with the given name and seve
- `color` <[string]> preferred logger color
### class: ChromiumBrowser
-
* extends: [Browser]
-Chromium-specific features including Tracing, service worker support, etc.
-You can use [`chromiumBrowser.startTracing`](#chromiumbrowserstarttracingpage-options) and [`chromiumBrowser.stopTracing`](#chromiumbrowserstoptracing) to create a trace file which can be opened in Chrome DevTools or [timeline viewer](https://chromedevtools.github.io/timeline-viewer/).
+Chromium-specific features including Tracing, service worker support, etc. You can use
+[`chromiumBrowser.startTracing`](#chromiumbrowserstarttracingpage-options) and
+[`chromiumBrowser.stopTracing`](#chromiumbrowserstoptracing) to create a trace file which can be opened in Chrome
+DevTools or [timeline viewer](https://chromedevtools.github.io/timeline-viewer/).
```js
await browser.startTracing(page, {path: 'trace.json'});
@@ -4683,6 +4955,7 @@ await browser.stopTracing();
- [chromiumBrowser.startTracing([page, options])](#chromiumbrowserstarttracingpage-options)
- [chromiumBrowser.stopTracing()](#chromiumbrowserstoptracing)
<!-- GEN:stop -->
+
<!-- GEN:toc-extends-Browser -->
- [event: 'disconnected'](#event-disconnected)
- [browser.close()](#browserclose)
@@ -4694,8 +4967,7 @@ await browser.stopTracing();
<!-- GEN:stop -->
#### chromiumBrowser.newBrowserCDPSession()
-- returns: <[Promise]<[CDPSession]>> Promise that resolves to the newly created browser
-session.
+- returns: <[Promise]<[CDPSession]>> Promise that resolves to the newly created browser session.
#### chromiumBrowser.startTracing([page, options])
- `page` <[Page]> Optional, if specified, tracing includes screenshots of the given page.
@@ -4711,7 +4983,6 @@ Only one trace can be active at a time per browser.
- returns: <[Promise]<[Buffer]>> Promise which resolves to buffer with trace data.
### class: ChromiumBrowserContext
-
* extends: [BrowserContext]
Chromium-specific features including background pages, service worker support, etc.
@@ -4727,6 +4998,7 @@ const backgroundPage = await context.waitForEvent('backgroundpage');
- [chromiumBrowserContext.newCDPSession(page)](#chromiumbrowsercontextnewcdpsessionpage)
- [chromiumBrowserContext.serviceWorkers()](#chromiumbrowsercontextserviceworkers)
<!-- GEN:stop -->
+
<!-- GEN:toc-extends-BrowserContext -->
- [event: 'close'](#event-close)
- [event: 'page'](#event-page)
@@ -4810,17 +5082,19 @@ const v8toIstanbul = require('v8-to-istanbul');
<!-- GEN:stop -->
#### chromiumCoverage.startCSSCoverage([options])
-- `options` <[Object]> Set of configurable options for coverage
+- `options` <[Object]>
- `resetOnNavigation` <[boolean]> Whether to reset coverage on every navigation. Defaults to `true`.
- returns: <[Promise]> Promise that resolves when coverage is started
#### chromiumCoverage.startJSCoverage([options])
-- `options` <[Object]> Set of configurable options for coverage
+- `options` <[Object]>
- `resetOnNavigation` <[boolean]> Whether to reset coverage on every navigation. Defaults to `true`.
- `reportAnonymousScripts` <[boolean]> Whether anonymous scripts generated by the page should be reported. Defaults to `false`.
- returns: <[Promise]> Promise that resolves when coverage is started
-> **NOTE** Anonymous scripts are ones that don't have an associated url. These are scripts that are dynamically created on the page using `eval` or `new Function`. If `reportAnonymousScripts` is set to `true`, anonymous scripts will have `__playwright_evaluation_script__` as their URL.
+> **NOTE** Anonymous scripts are ones that don't have an associated url. These are scripts that are dynamically created
+on the page using `eval` or `new Function`. If `reportAnonymousScripts` is set to `true`, anonymous scripts will have
+`__playwright_evaluation_script__` as their URL.
#### chromiumCoverage.stopCSSCoverage()
- returns: <[Promise]<[Array]<[Object]>>> Promise that resolves to the array of coverage reports for all stylesheets
@@ -4849,7 +5123,6 @@ const v8toIstanbul = require('v8-to-istanbul');
reported.
### class: CDPSession
-
* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
The `CDPSession` instances are used to talk raw Chrome Devtools Protocol:
@@ -4879,8 +5152,8 @@ await client.send('Animation.setPlaybackRate', {
#### cdpSession.detach()
- returns: <[Promise]>
-Detaches the CDPSession from the target. Once detached, the CDPSession object won't emit any events and can't be used
-to send messages.
+Detaches the CDPSession from the target. Once detached, the CDPSession object won't emit any events and can't be used to
+send messages.
#### cdpSession.send(method[, params])
- `method` <[string]> protocol method name
@@ -4888,7 +5161,6 @@ to send messages.
- returns: <[Promise]<[Object]>>
### class: FirefoxBrowser
-
* extends: [Browser]
Firefox browser instance does not expose Firefox-specific features.
@@ -4904,7 +5176,6 @@ Firefox browser instance does not expose Firefox-specific features.
<!-- GEN:stop -->
### class: WebKitBrowser
-
* extends: [Browser]
WebKit browser instance does not expose WebKit-specific features.
@@ -4919,6 +5190,7 @@ WebKit browser instance does not expose WebKit-specific features.
- [browser.version()](#browserversion)
<!-- GEN:stop -->
+
### EvaluationArgument
Playwright evaluation methods like [page.evaluate(pageFunction[, arg])](#pageevaluatepagefunction-arg) take a single optional argument. This argument can be a mix of [Serializable] values and [JSHandle] or [ElementHandle] instances. Handles are automatically converted to the value they represent.
diff --git a/utils/doclint/cli.js b/utils/doclint/cli.js
index 94b4cc820b..d34d64f157 100755
--- a/utils/doclint/cli.js
+++ b/utils/doclint/cli.js
@@ -21,7 +21,7 @@ const path = require('path');
const os = require('os');
const Source = require('./Source');
const Message = require('./Message');
-const { renderMdTemplate, extractParamDescriptions } = require('./../parse_md');
+const { renderMdTemplate } = require('./../parse_md');
const { spawnSync } = require('child_process');
const PROJECT_DIR = path.join(__dirname, '..', '..');
diff --git a/utils/parse_md.js b/utils/parse_md.js
index e867707593..95e463de9e 100644
--- a/utils/parse_md.js
+++ b/utils/parse_md.js
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+const maxColumns = 120;
+
function normalizeLines(content) {
const inLines = content.split('\n');
let inCodeBlock = false;
@@ -26,6 +28,7 @@ function normalizeLines(content) {
|| line.trim().startsWith('<')
|| line.trim().startsWith('>')
|| line.trim().startsWith('-')
+ || line.trim().startsWith('*')
|| singleLineExpression;
if (line.startsWith('```')) {
inCodeBlock = !inCodeBlock;
@@ -56,7 +59,8 @@ function buildTree(lines) {
if (line.startsWith('```')) {
const node = {
- code: []
+ code: [],
+ codeLang: line.substring(3)
};
root.ul.push(node);
line = lines[++i];
@@ -69,7 +73,7 @@ function buildTree(lines) {
if (line.startsWith('<!-- GEN')) {
const node = {
- gen: []
+ gen: [line]
};
root.ul.push(node);
line = lines[++i];
@@ -77,6 +81,7 @@ function buildTree(lines) {
node.gen.push(line);
line = lines[++i];
}
+ node.gen.push(line);
continue;
}
@@ -88,12 +93,17 @@ function buildTree(lines) {
continue;
}
- const list = line.match(/^(\s*)(-|1.) /);
+ const list = line.match(/^(\s*)(-|1.|\*) /);
const depth = list ? (list[1].length / 2) : 0;
const node = {};
if (list) {
node.li = line.substring(list[0].length);
- node.liType = line.trim().startsWith('1.') ? 'ordinals' : 'default';
+ if (line.trim().startsWith('1.'))
+ node.liType = 'ordinal';
+ else if (line.trim().startsWith('*'))
+ node.liType = 'bullet';
+ else
+ node.liType = 'default';
} else {
node.text = line;
}
@@ -109,17 +119,96 @@ function parseMd(content) {
return buildTree(normalizeLines(content));
}
-function renderMd(node) {
+function renderMd(nodes) {
const result = [];
- const visit = (node, indent, result) => {
- result.push(`${indent}- ${node.li}`);
- for (const child of node.ul || [])
- visit(child, indent + ' ', result);
- };
- visit(node, '', result);
+ let lastNode;
+ for (let node of nodes) {
+ innerRenderMdNode(node, lastNode, result);
+ lastNode = node;
+ }
+ return result.join('\n');
+}
+
+function renderMdNode(node, lastNode) {
+ const result = [];
+ innerRenderMdNode(node, lastNode, result);
return result.join('\n');
}
+function innerRenderMdNode(node, lastNode, result) {
+ const newLine = () => {
+ if (result[result.length - 1] !== '')
+ result.push('');
+ };
+
+ if (node.h1) {
+ newLine();
+ result.push(`# ${node.h1}`);
+ }
+ if (node.h2) {
+ newLine();
+ result.push(`## ${node.h2}`);
+ }
+ if (node.h3) {
+ newLine();
+ result.push(`### ${node.h3}`);
+ }
+ if (node.h4) {
+ newLine();
+ result.push(`#### ${node.h4}`);
+ }
+ if (node.text) {
+ const bothComments = node.text.startsWith('>') && lastNode && lastNode.text && lastNode.text.startsWith('>');
+ if (!bothComments && lastNode && (lastNode.text || lastNode.li || lastNode.h1 || lastNode.h2 || lastNode.h3 || lastNode.h4))
+ newLine();
+ printText(node, result);
+ }
+ if (node.code) {
+ newLine();
+ result.push('```' + node.codeLang);
+ for (const line of node.code)
+ result.push(line);
+ result.push('```');
+ newLine();
+ }
+ if (node.gen) {
+ newLine();
+ for (const line of node.gen)
+ result.push(line);
+ newLine();
+ }
+ if (node.li) {
+ const visit = (node, indent) => {
+ let char;
+ switch (node.liType) {
+ case 'bullet': char = '*'; break;
+ case 'default': char = '-'; break;
+ case 'ordinal': char = '1.'; break;
+ }
+ result.push(`${indent}${char} ${node.li}`);
+ for (const child of node.ul || [])
+ visit(child, indent + ' ');
+ };
+ visit(node, '');
+ }
+}
+
+function printText(node, result) {
+ let line = node.text;
+ while (line.length > maxColumns) {
+ let index = line.lastIndexOf(' ', maxColumns);
+ if (index === -1) {
+ index = line.indexOf(' ', maxColumns);
+ if (index === -1)
+ break;
+ }
+ result.push(line.substring(0, index));
+ line = line.substring(index + 1);
+ }
+ if (line.length)
+ result.push(line);
+}
+
function renderMdTemplate(body, params) {
const map = new Map();
let nodes;
@@ -148,13 +237,13 @@ function renderMdTemplate(body, params) {
let snippet;
if (line.endsWith('-as-is')) {
- snippet = nodes.map(node => renderMd(node)).join('\n');
+ snippet = nodes.map(node => renderMdNode(node)).join('\n');
} else {
const { name, type } = parseArgument(nodes[0].li);
nodes[0].li = `\`${name}\` ${type}`;
if (nodes[1])
nodes[0].li += ` ${nodes[1].text}`;
- snippet = renderMd(nodes[0]);
+ snippet = renderMdNode(nodes[0]);
}
for (const l of snippet.split('\n'))
result.push(indent + l);
@@ -181,7 +270,7 @@ function extractParamDescription(group, node) {
group = `context-option-${name.toLowerCase()}`;
console.log(`## ${group}`);
console.log();
- console.log(renderMd(node));
+ console.log(renderMdNode(node));
console.log();
console.log(text);
console.log();