chore: generate usage: sections based on snippets (#18965)

This commit is contained in:
Pavel Feldman 2022-11-21 10:40:21 -08:00 committed by GitHub
parent 3fb4b3bbf9
commit 620e8547d4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
24 changed files with 541 additions and 52 deletions

View file

@ -58,6 +58,8 @@ The Chromium accessibility tree contains nodes that go unused on most platforms
will discard them as well for an easier to process tree, unless [`option: interestingOnly`] is set to `false`. will discard them as well for an easier to process tree, unless [`option: interestingOnly`] is set to `false`.
::: :::
**Usage**
An example of dumping the entire accessibility tree: An example of dumping the entire accessibility tree:
```js ```js

View file

@ -140,6 +140,8 @@ Prevents automatic playwright driver installation on attach. Assumes that the dr
Launches Playwright Android server that clients can connect to. See the following example: Launches Playwright Android server that clients can connect to. See the following example:
**Usage**
Server Side: Server Side:
```js ```js

View file

@ -188,9 +188,9 @@ discards all stored responses, and makes [`method: APIResponse.body`] throw "Res
- returns: <[APIResponse]> - returns: <[APIResponse]>
Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and update Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and update
context cookies from the response. The method will automatically follow redirects. context cookies from the response. The method will automatically follow redirects. JSON objects can be passed directly to the request.
JSON objects can be passed directly to the request: **Usage**
```js ```js
await request.fetch('https://example.com/api/createBook', { await request.fetch('https://example.com/api/createBook', {
@ -351,6 +351,8 @@ Sends HTTP(S) [GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GE
The method will populate request cookies from the context and update The method will populate request cookies from the context and update
context cookies from the response. The method will automatically follow redirects. context cookies from the response. The method will automatically follow redirects.
**Usage**
Request parameters can be configured with `params` option, they will be serialized into the URL search parameters: Request parameters can be configured with `params` option, they will be serialized into the URL search parameters:
```js ```js
@ -535,6 +537,8 @@ Sends HTTP(S) [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/P
The method will populate request cookies from the context and update The method will populate request cookies from the context and update
context cookies from the response. The method will automatically follow redirects. context cookies from the response. The method will automatically follow redirects.
**Usage**
JSON objects can be passed directly to the request: JSON objects can be passed directly to the request:
```js ```js

View file

@ -74,6 +74,8 @@ The opposite of [`method: APIResponseAssertions.toBeOK`].
Ensures the response status code is within `200..299` range. Ensures the response status code is within `200..299` range.
**Usage**
```js ```js
await expect(response).toBeOK(); await expect(response).toBeOK();
``` ```

View file

@ -108,6 +108,8 @@ The [Browser] object itself is considered to be disposed and cannot be used anym
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.
**Usage**
```js ```js
const browser = await pw.webkit.launch(); const browser = await pw.webkit.launch();
console.log(browser.contexts().length); // prints `0` console.log(browser.contexts().length); // prints `0`
@ -173,6 +175,8 @@ If directly using this method to create [BrowserContext]s, it is best practice t
and before calling [`method: Browser.close`]. This will ensure the `context` is closed gracefully and any artifacts—like HARs and videos—are fully flushed and saved. and before calling [`method: Browser.close`]. This will ensure the `context` is closed gracefully and any artifacts—like HARs and videos—are fully flushed and saved.
::: :::
**Usage**
```js ```js
(async () => { (async () => {
const browser = await playwright.firefox.launch(); // Or 'chromium' or 'webkit'. const browser = await playwright.firefox.launch(); // Or 'chromium' or 'webkit'.
@ -292,6 +296,8 @@ This API controls [Chromium Tracing](https://www.chromium.org/developers/how-tos
You can use [`method: Browser.startTracing`] and [`method: Browser.stopTracing`] to create a trace file that can You can use [`method: Browser.startTracing`] and [`method: Browser.stopTracing`] to create a trace file that can
be opened in Chrome DevTools performance panel. be opened in Chrome DevTools performance panel.
**Usage**
```js ```js
await browser.startTracing(page, {path: 'trace.json'}); await browser.startTracing(page, {path: 'trace.json'});
await page.goto('https://www.google.com'); await page.goto('https://www.google.com');

View file

@ -203,6 +203,8 @@ Emitted when new service worker is created in the context.
Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies can be Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies can be
obtained via [`method: BrowserContext.cookies`]. obtained via [`method: BrowserContext.cookies`].
**Usage**
```js ```js
await browserContext.addCookies([cookieObject1, cookieObject2]); await browserContext.addCookies([cookieObject1, cookieObject2]);
``` ```
@ -247,6 +249,8 @@ Adds a script which would be evaluated in one of the following scenarios:
The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend 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 JavaScript environment, e.g. to seed `Math.random`.
**Usage**
An example of overriding `Math.random` before the page loads: An example of overriding `Math.random` before the page loads:
```js browser ```js browser
@ -336,6 +340,8 @@ Clears context cookies.
Clears all permission overrides for the browser context. Clears all permission overrides for the browser context.
**Usage**
```js ```js
const context = await browser.newContext(); const context = await browser.newContext();
await context.grantPermissions(['clipboard-read']); await context.grantPermissions(['clipboard-read']);
@ -415,6 +421,8 @@ BrowserContext, page: Page, frame: Frame }`.
See [`method: Page.exposeBinding`] for page-only version. See [`method: Page.exposeBinding`] for page-only version.
**Usage**
An example of exposing page URL to all frames in all pages in the context: An example of exposing page URL to all frames in all pages in the context:
```js ```js
@ -639,6 +647,8 @@ If the [`param: callback`] returns a [Promise], it will be awaited.
See [`method: Page.exposeFunction`] for page-only version. See [`method: Page.exposeFunction`] for page-only version.
**Usage**
An example of adding a `sha256` function to all pages in the context: An example of adding a `sha256` function to all pages in the context:
```js ```js
@ -894,6 +904,8 @@ is enabled, every request matching the url pattern will stall unless it's contin
[`method: BrowserContext.route`] will not intercept requests intercepted by Service Worker. See [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when using request interception by setting [`option: Browser.newContext.serviceWorkers`] to `'block'`. [`method: BrowserContext.route`] will not intercept requests intercepted by Service Worker. See [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when using request interception by setting [`option: Browser.newContext.serviceWorkers`] to `'block'`.
::: :::
**Usage**
An example of a naive handler that aborts all image requests: An example of a naive handler that aborts all image requests:
```js ```js
@ -1170,6 +1182,8 @@ An object containing additional HTTP headers to be sent with every request. All
Sets the context's geolocation. Passing `null` or `undefined` emulates position unavailable. Sets the context's geolocation. Passing `null` or `undefined` emulates position unavailable.
**Usage**
```js ```js
await browserContext.setGeolocation({latitude: 59.95, longitude: 30.31667}); await browserContext.setGeolocation({latitude: 59.95, longitude: 30.31667});
``` ```
@ -1295,6 +1309,8 @@ Optional handler function used to register a routing with [`method: BrowserConte
Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
value. Will throw an error if the context closes before the event is fired. Returns the event data value. value. Will throw an error if the context closes before the event is fired. Returns the event data value.
**Usage**
```js ```js
const [page, _] = await Promise.all([ const [page, _] = await Promise.all([
context.waitForEvent('page'), context.waitForEvent('page'),

View file

@ -136,6 +136,8 @@ The default browser context is accessible via [`method: Browser.contexts`].
Connecting over the Chrome DevTools Protocol is only supported for Chromium-based browsers. Connecting over the Chrome DevTools Protocol is only supported for Chromium-based browsers.
::: :::
**Usage**
```js ```js
const browser = await playwright.chromium.connectOverCDP('http://localhost:9222'); const browser = await playwright.chromium.connectOverCDP('http://localhost:9222');
const defaultContext = browser.contexts()[0]; const defaultContext = browser.contexts()[0];
@ -218,6 +220,8 @@ A path where Playwright expects to find a bundled browser executable.
Returns the browser instance. Returns the browser instance.
**Usage**
You can use [`option: ignoreDefaultArgs`] to filter out `--mute-audio` from default arguments: You can use [`option: ignoreDefaultArgs`] to filter out `--mute-audio` from default arguments:
```js ```js
@ -324,6 +328,8 @@ use a temporary directory instead.
Returns the browser app instance. You can connect to it via [`method: BrowserType.connect`], which requires the major/minor client/server version to match (1.2.3 → is compatible with 1.2.x). Returns the browser app instance. You can connect to it via [`method: BrowserType.connect`], which requires the major/minor client/server version to match (1.2.3 → is compatible with 1.2.x).
**Usage**
Launches browser server that client can connect to. An example of launching a browser executable and connecting to it Launches browser server that client can connect to. An example of launching a browser executable and connecting to it
later: later:

View file

@ -118,7 +118,8 @@ Optional argument to pass to [`param: expression`].
- returns: <[Page]> - returns: <[Page]>
Convenience method that waits for the first application window to be opened. Convenience method that waits for the first application window to be opened.
Typically your script will start with:
**Usage**
```js ```js
const electronApp = await electron.launch({ const electronApp = await electron.launch({
@ -140,6 +141,8 @@ Returns the main process for this Electron Application.
Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy value. Will throw an error if the application is closed before the event is fired. Returns the event data value. Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy value. Will throw an error if the application is closed before the event is fired. Returns the event data value.
**Usage**
```js ```js
const [window] = await Promise.all([ const [window] = await Promise.all([
electronApp.waitForEvent('window'), electronApp.waitForEvent('window'),

View file

@ -127,6 +127,8 @@ Elements from child frames return the bounding box relative to the main frame, u
Assuming the page is static, it is safe to use bounding box coordinates to perform input. For example, the following 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. snippet should click the center of the element.
**Usage**
```js ```js
const box = await elementHandle.boundingBox(); const box = await elementHandle.boundingBox();
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
@ -283,6 +285,8 @@ The snippet below dispatches the `click` event on the element. Regardless of the
is dispatched. This is equivalent to calling is dispatched. This is equivalent to calling
[element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click). [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
**Usage**
```js ```js
await elementHandle.dispatchEvent('click'); await elementHandle.dispatchEvent('click');
``` ```
@ -381,7 +385,7 @@ details. If no elements match the selector, the method throws an error.
If [`param: expression`] returns a [Promise], then [`method: ElementHandle.evalOnSelector`] would wait for the promise to resolve and return its If [`param: expression`] returns a [Promise], then [`method: ElementHandle.evalOnSelector`] would wait for the promise to resolve and return its
value. value.
Examples: **Usage**
```js ```js
const tweetHandle = await page.$('.tweet'); const tweetHandle = await page.$('.tweet');
@ -441,7 +445,7 @@ matched elements as a first argument to [`param: expression`]. See
If [`param: expression`] returns a [Promise], then [`method: ElementHandle.evalOnSelectorAll`] would wait for the promise to resolve and return its If [`param: expression`] returns a [Promise], then [`method: ElementHandle.evalOnSelectorAll`] would wait for the promise to resolve and return its
value. value.
Examples: **Usage**
```html ```html
<div class="feed"> <div class="feed">
@ -733,6 +737,8 @@ Returns the array of option values that have been successfully selected.
Triggers a `change` and `input` event once all the provided options have been selected. Triggers a `change` and `input` event once all the provided options have been selected.
**Usage**
```js ```js
// single selection matching the value // single selection matching the value
handle.selectOption('blue'); handle.selectOption('blue');
@ -912,6 +918,8 @@ Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup`
To press a special key, like `Control` or `ArrowDown`, use [`method: ElementHandle.press`]. To press a special key, like `Control` or `ArrowDown`, use [`method: ElementHandle.press`].
**Usage**
```js ```js
await elementHandle.type('Hello'); // Types instantly await elementHandle.type('Hello'); // Types instantly
await elementHandle.type('World', {delay: 100}); // Types slower, like a user await elementHandle.type('World', {delay: 100}); // Types slower, like a user
@ -1058,6 +1066,8 @@ appear/disappear from dom, or become visible/hidden). If at the moment of callin
satisfies the condition, the method will return immediately. If the selector doesn't satisfy the condition for the satisfies the condition, the method will return immediately. If the selector doesn't satisfy the condition for the
[`option: timeout`] milliseconds, the function will throw. [`option: timeout`] milliseconds, the function will throw.
**Usage**
```js ```js
await page.setContent(`<div><span></span></div>`); await page.setContent(`<div><span></span></div>`);
const div = await page.$('div'); const div = await page.$('div');

View file

@ -342,6 +342,8 @@ The snippet below dispatches the `click` event on the element. Regardless of the
is dispatched. This is equivalent to calling is dispatched. This is equivalent to calling
[element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click). [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
**Usage**
```js ```js
await frame.dispatchEvent('button#submit', 'click'); await frame.dispatchEvent('button#submit', 'click');
``` ```
@ -482,7 +484,7 @@ elements match the selector, the method throws an error.
If [`param: expression`] returns a [Promise], then [`method: Frame.evalOnSelector`] would wait for the promise to resolve and return its If [`param: expression`] returns a [Promise], then [`method: Frame.evalOnSelector`] would wait for the promise to resolve and return its
value. value.
Examples: **Usage**
```js ```js
const searchValue = await frame.$eval('#search', el => el.value); const searchValue = await frame.$eval('#search', el => el.value);
@ -549,7 +551,7 @@ more details.
If [`param: expression`] returns a [Promise], then [`method: Frame.evalOnSelectorAll`] would wait for the promise to resolve and return its If [`param: expression`] returns a [Promise], then [`method: Frame.evalOnSelectorAll`] would wait for the promise to resolve and return its
value. value.
Examples: **Usage**
```js ```js
const divsCounts = await frame.$$eval('div', (divs, min) => divs.length >= min, 10); const divsCounts = await frame.$$eval('div', (divs, min) => divs.length >= min, 10);
@ -596,6 +598,8 @@ If the function passed to the [`method: Frame.evaluate`] returns a non-[Serializ
[`method: Frame.evaluate`] returns `undefined`. Playwright also supports transferring some [`method: Frame.evaluate`] returns `undefined`. Playwright also supports transferring some
additional values that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`. additional values that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.
**Usage**
```js ```js
const result = await frame.evaluate(([x, y]) => { const result = await frame.evaluate(([x, y]) => {
return Promise.resolve(x * y); return Promise.resolve(x * y);
@ -704,6 +708,8 @@ The only difference between [`method: Frame.evaluate`] and [`method: Frame.evalu
If the function, passed to the [`method: Frame.evaluateHandle`], returns a [Promise], then If the function, passed to the [`method: Frame.evaluateHandle`], returns a [Promise], then
[`method: Frame.evaluateHandle`] would wait for the promise to resolve and return its value. [`method: Frame.evaluateHandle`] would wait for the promise to resolve and return its value.
**Usage**
```js ```js
const aWindowHandle = await frame.evaluateHandle(() => Promise.resolve(window)); const aWindowHandle = await frame.evaluateHandle(() => Promise.resolve(window));
aWindowHandle; // Handle for the window object. aWindowHandle; // Handle for the window object.
@ -853,6 +859,8 @@ frame.
This method throws an error if the frame has been detached before `frameElement()` returns. This method throws an error if the frame has been detached before `frameElement()` returns.
**Usage**
```js ```js
const frameElement = await frame.frameElement(); const frameElement = await frame.frameElement();
const contentFrame = await frameElement.contentFrame(); const contentFrame = await frameElement.contentFrame();
@ -888,8 +896,11 @@ Console.WriteLine(frame == contentFrame); // -> True
- returns: <[FrameLocator]> - returns: <[FrameLocator]>
When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements
in that iframe. Following snippet locates element with text "Submit" in the iframe with id `my-frame`, in that iframe.
like `<iframe id="my-frame">`:
**Usage**
Following snippet locates element with text "Submit" in the iframe with id `my-frame`, like `<iframe id="my-frame">`:
```js ```js
const locator = frame.frameLocator('#my-iframe').getByText('Submit'); const locator = frame.frameLocator('#my-iframe').getByText('Submit');
@ -1387,6 +1398,8 @@ Returns the array of option values that have been successfully selected.
Triggers a `change` and `input` event once all the provided options have been selected. Triggers a `change` and `input` event once all the provided options have been selected.
**Usage**
```js ```js
// single selection matching the value // single selection matching the value
frame.selectOption('select#colors', 'blue'); frame.selectOption('select#colors', 'blue');
@ -1605,6 +1618,8 @@ send fine-grained keyboard events. To fill values in form fields, use [`method:
To press a special key, like `Control` or `ArrowDown`, use [`method: Keyboard.press`]. To press a special key, like `Control` or `ArrowDown`, use [`method: Keyboard.press`].
**Usage**
```js ```js
await frame.type('#mytextarea', 'Hello'); // Types instantly await frame.type('#mytextarea', 'Hello'); // Types instantly
await frame.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user await frame.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user
@ -1707,6 +1722,8 @@ Returns frame's url.
Returns when the [`param: expression`] returns a truthy value, returns that value. Returns when the [`param: expression`] returns a truthy value, returns that value.
**Usage**
The [`method: Frame.waitForFunction`] can be used to observe viewport size change: The [`method: Frame.waitForFunction`] can be used to observe viewport size change:
```js ```js
@ -1842,6 +1859,8 @@ Waits for the required load state to be reached.
This returns when the frame reaches a required load state, `load` by default. The navigation must have been committed This returns 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. when this method is called. If current document has already reached the required state, resolves immediately.
**Usage**
```js ```js
await frame.click('button'); // Click triggers navigation. await frame.click('button'); // Click triggers navigation.
await frame.waitForLoadState(); // Waits for 'load' state by default. await frame.waitForLoadState(); // Waits for 'load' state by default.
@ -1884,6 +1903,8 @@ Waits for the frame navigation and returns the main resource response. In case o
will resolve with the response of the last redirect. In case of navigation to a different anchor or navigation due to 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`. History API usage, the navigation will resolve with `null`.
**Usage**
This method waits for the frame to navigate to a new URL. It is useful for when you run code which will indirectly cause This method waits for the frame to navigate to a new URL. It is useful for when you run code which will indirectly cause
the frame to navigate. Consider this example: the frame to navigate. Consider this example:
@ -1955,6 +1976,8 @@ visible/hidden). If at the moment of calling the method [`param: selector`] alre
will return immediately. If the selector doesn't satisfy the condition for the [`option: timeout`] milliseconds, the will return immediately. If the selector doesn't satisfy the condition for the [`option: timeout`] milliseconds, the
function will throw. function will throw.
**Usage**
This method works across navigations: This method works across navigations:
```js ```js
@ -2083,6 +2106,8 @@ A timeout to wait for
Waits for the frame to navigate to the given URL. Waits for the frame to navigate to the given URL.
**Usage**
```js ```js
await frame.click('a.delayed-navigation'); // Clicking the link will indirectly cause a navigation await frame.click('a.delayed-navigation'); // Clicking the link will indirectly cause a navigation
await frame.waitForURL('**/target.html'); await frame.waitForURL('**/target.html');

View file

@ -57,7 +57,7 @@ This method passes this handle as the first argument to [`param: expression`].
If [`param: expression`] returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return If [`param: expression`] returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return
its value. its value.
Examples: **Usage**
```js ```js
const tweetHandle = await page.$('.tweet .retweets'); const tweetHandle = await page.$('.tweet .retweets');
@ -123,6 +123,8 @@ Optional argument to pass to [`param: expression`].
The method returns a map with **own property names** as keys and JSHandle instances for the property values. The method returns a map with **own property names** as keys and JSHandle instances for the property values.
**Usage**
```js ```js
const handle = await page.evaluateHandle(() => ({window, document})); const handle = await page.evaluateHandle(() => ({window, document}));
const properties = await handle.getProperties(); const properties = await handle.getProperties();

View file

@ -180,6 +180,8 @@ Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
Dispatches only `input` event, does not emit the `keydown`, `keyup` or `keypress` events. Dispatches only `input` event, does not emit the `keydown`, `keyup` or `keypress` events.
**Usage**
```js ```js
page.keyboard.insertText('嗨'); page.keyboard.insertText('嗨');
``` ```
@ -231,6 +233,8 @@ respective texts.
Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When specified with the Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When specified with the
modifier, modifier is pressed and being held while the subsequent key is being pressed. modifier, modifier is pressed and being held while the subsequent key is being pressed.
**Usage**
```js ```js
const page = await browser.newPage(); const page = await browser.newPage();
await page.goto('https://keycode.info'); await page.goto('https://keycode.info');
@ -311,6 +315,8 @@ Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in t
To press a special key, like `Control` or `ArrowDown`, use [`method: Keyboard.press`]. To press a special key, like `Control` or `ArrowDown`, use [`method: Keyboard.press`].
**Usage**
```js ```js
await page.keyboard.type('Hello'); // Types instantly await page.keyboard.type('Hello'); // Types instantly
await page.keyboard.type('World', {delay: 100}); // Types slower, like a user await page.keyboard.type('World', {delay: 100}); // Types slower, like a user

View file

@ -47,6 +47,8 @@ Elements from child frames return the bounding box relative to the main frame, u
Assuming the page is static, it is safe to use bounding box coordinates to perform input. For example, the following 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. snippet should click the center of the element.
**Usage**
```js ```js
const box = await element.boundingBox(); const box = await element.boundingBox();
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
@ -222,6 +224,8 @@ The snippet below dispatches the `click` event on the element. Regardless of the
is dispatched. This is equivalent to calling is dispatched. This is equivalent to calling
[element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click). [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
**Usage**
```js ```js
await element.dispatchEvent('click'); await element.dispatchEvent('click');
``` ```
@ -314,6 +318,8 @@ This method drags the locator to another target locator or target position. It w
first move to the source element, perform a `mousedown`, then move to the target first move to the source element, perform a `mousedown`, then move to the target
element or position and perform a `mouseup`. element or position and perform a `mouseup`.
**Usage**
```js ```js
const source = page.locator('#source'); const source = page.locator('#source');
const target = page.locator('#target'); const target = page.locator('#target');
@ -425,7 +431,7 @@ This method passes this handle as the first argument to [`param: expression`].
If [`param: expression`] returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return If [`param: expression`] returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return
its value. its value.
Examples: **Usage**
```js ```js
const tweets = page.locator('.tweet .retweets'); const tweets = page.locator('.tweet .retweets');
@ -474,7 +480,7 @@ a first argument to [`param: expression`]. Returns the result of [`param: expres
If [`param: expression`] returns a [Promise], then [`method: Locator.evaluateAll`] would wait for the promise If [`param: expression`] returns a [Promise], then [`method: Locator.evaluateAll`] would wait for the promise
to resolve and return its value. to resolve and return its value.
Examples: **Usage**
```js ```js
const elements = page.locator('div'); const elements = page.locator('div');
@ -568,6 +574,8 @@ Value to set for the `<input>`, `<textarea>` or `[contenteditable]` element.
This method narrows existing locator according to the options, for example filters by text. This method narrows existing locator according to the options, for example filters by text.
It can be chained to filter multiple times. It can be chained to filter multiple times.
**Usage**
```js ```js
const rowLocator = page.locator('tr'); const rowLocator = page.locator('tr');
// ... // ...
@ -638,6 +646,8 @@ Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus
* since: v1.17 * since: v1.17
- returns: <[FrameLocator]> - returns: <[FrameLocator]>
**Usage**
When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements
in that iframe: in that iframe:
@ -993,6 +1003,8 @@ Returns the array of option values that have been successfully selected.
Triggers a `change` and `input` event once all the provided options have been selected. Triggers a `change` and `input` event once all the provided options have been selected.
**Usage**
```js ```js
// single selection matching the value // single selection matching the value
element.selectOption('blue'); element.selectOption('blue');
@ -1175,6 +1187,8 @@ Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup`
To press a special key, like `Control` or `ArrowDown`, use [`method: Locator.press`]. To press a special key, like `Control` or `ArrowDown`, use [`method: Locator.press`].
**Usage**
```js ```js
await element.type('Hello'); // Types instantly await element.type('Hello'); // Types instantly
await element.type('World', {delay: 100}); // Types slower, like a user await element.type('World', {delay: 100}); // Types slower, like a user
@ -1290,6 +1304,8 @@ Returns when element specified by locator satisfies the [`option: state`] option
If target element already satisfies the condition, the method returns immediately. Otherwise, waits for up to If target element already satisfies the condition, the method returns immediately. Otherwise, waits for up to
[`option: timeout`] milliseconds until the condition is met. [`option: timeout`] milliseconds until the condition is met.
**Usage**
```js ```js
const orderSent = page.locator('#order-sent'); const orderSent = page.locator('#order-sent');
await orderSent.waitFor(); await orderSent.waitFor();

View file

@ -423,6 +423,8 @@ Expected options currently selected.
Ensures the [Locator] points to a checked input. Ensures the [Locator] points to a checked input.
**Usage**
```js ```js
const locator = page.getByLabel('Subscribe to newsletter'); const locator = page.getByLabel('Subscribe to newsletter');
await expect(locator).toBeChecked(); await expect(locator).toBeChecked();
@ -472,6 +474,8 @@ Note that only native control elements such as HTML `button`, `input`, `select`,
can be disabled by setting "disabled" attribute. "disabled" attribute on other elements is ignored can be disabled by setting "disabled" attribute. "disabled" attribute on other elements is ignored
by the browser. by the browser.
**Usage**
```js ```js
const locator = page.locator('button.submit'); const locator = page.locator('button.submit');
await expect(locator).toBeDisabled(); await expect(locator).toBeDisabled();
@ -513,6 +517,8 @@ await Expect(locator).ToBeDisabledAsync();
Ensures the [Locator] points to an editable element. Ensures the [Locator] points to an editable element.
**Usage**
```js ```js
const locator = page.getByRole('textbox'); const locator = page.getByRole('textbox');
await expect(locator).toBeEditable(); await expect(locator).toBeEditable();
@ -558,6 +564,8 @@ await Expect(locator).ToBeEditableAsync();
Ensures the [Locator] points to an empty editable element or to a DOM node that has no text. Ensures the [Locator] points to an empty editable element or to a DOM node that has no text.
**Usage**
```js ```js
const locator = page.locator('div.warning'); const locator = page.locator('div.warning');
await expect(locator).toBeEmpty(); await expect(locator).toBeEmpty();
@ -599,6 +607,8 @@ await Expect(locator).ToBeEmptyAsync();
Ensures the [Locator] points to an enabled element. Ensures the [Locator] points to an enabled element.
**Usage**
```js ```js
const locator = page.locator('button.submit'); const locator = page.locator('button.submit');
await expect(locator).toBeEnabled(); await expect(locator).toBeEnabled();
@ -644,6 +654,8 @@ await Expect(locator).toBeEnabledAsync();
Ensures the [Locator] points to a focused DOM node. Ensures the [Locator] points to a focused DOM node.
**Usage**
```js ```js
const locator = page.getByRole('textbox'); const locator = page.getByRole('textbox');
await expect(locator).toBeFocused(); await expect(locator).toBeFocused();
@ -685,6 +697,8 @@ await Expect(locator).ToBeFocusedAsync();
Ensures that [Locator] either does not resolve to any DOM node, or resolves to a [non-visible](./actionability.md#visible) one. Ensures that [Locator] either does not resolve to any DOM node, or resolves to a [non-visible](./actionability.md#visible) one.
**Usage**
```js ```js
const locator = page.locator('.my-element'); const locator = page.locator('.my-element');
await expect(locator).toBeHidden(); await expect(locator).toBeHidden();
@ -726,6 +740,8 @@ await Expect(locator).ToBeHiddenAsync();
Ensures that [Locator] points to an [attached](./actionability.md#attached) and [visible](./actionability.md#visible) DOM node. Ensures that [Locator] points to an [attached](./actionability.md#attached) and [visible](./actionability.md#visible) DOM node.
**Usage**
```js ```js
const locator = page.locator('.my-element'); const locator = page.locator('.my-element');
await expect(locator).toBeVisible(); await expect(locator).toBeVisible();
@ -771,6 +787,8 @@ await Expect(locator).ToBeVisibleAsync();
Ensures the [Locator] points to an element that contains the given text. You can use regular expressions for the value as well. Ensures the [Locator] points to an element that contains the given text. You can use regular expressions for the value as well.
**Usage**
```js ```js
const locator = page.locator('.title'); const locator = page.locator('.title');
await expect(locator).toContainText('substring'); await expect(locator).toContainText('substring');
@ -936,6 +954,8 @@ Whether to use `element.innerText` instead of `element.textContent` when retriev
Ensures the [Locator] points to an element with given attribute. Ensures the [Locator] points to an element with given attribute.
**Usage**
```js ```js
const locator = page.locator('input'); const locator = page.locator('input');
await expect(locator).toHaveAttribute('type', 'text'); await expect(locator).toHaveAttribute('type', 'text');
@ -990,6 +1010,8 @@ Expected attribute value.
Ensures the [Locator] points to an element with given CSS classes. This needs to be a full match Ensures the [Locator] points to an element with given CSS classes. This needs to be a full match
or using a relaxed regular expression. or using a relaxed regular expression.
**Usage**
```html ```html
<div class='selected row' id='component'></div> <div class='selected row' id='component'></div>
``` ```
@ -1084,6 +1106,8 @@ Expected class or RegExp or a list of those.
Ensures the [Locator] resolves to an exact number of DOM nodes. Ensures the [Locator] resolves to an exact number of DOM nodes.
**Usage**
```js ```js
const list = page.locator('list > .component'); const list = page.locator('list > .component');
await expect(list).toHaveCount(3); await expect(list).toHaveCount(3);
@ -1131,6 +1155,8 @@ Expected count.
Ensures the [Locator] resolves to an element with the given computed CSS style. Ensures the [Locator] resolves to an element with the given computed CSS style.
**Usage**
```js ```js
const locator = page.getByRole('button'); const locator = page.getByRole('button');
await expect(locator).toHaveCSS('display', 'flex'); await expect(locator).toHaveCSS('display', 'flex');
@ -1184,6 +1210,8 @@ CSS property value.
Ensures the [Locator] points to an element with the given DOM Node ID. Ensures the [Locator] points to an element with the given DOM Node ID.
**Usage**
```js ```js
const locator = page.getByRole('textbox'); const locator = page.getByRole('textbox');
await expect(locator).toHaveId('lastname'); await expect(locator).toHaveId('lastname');
@ -1232,6 +1260,8 @@ Element id.
Ensures the [Locator] points to an element with given JavaScript property. Note that this property can be Ensures the [Locator] points to an element with given JavaScript property. Note that this property can be
of a primitive type as well as a plain serializable JavaScript object. of a primitive type as well as a plain serializable JavaScript object.
**Usage**
```js ```js
const locator = page.locator('.component'); const locator = page.locator('.component');
await expect(locator).toHaveJSProperty('loaded', true); await expect(locator).toHaveJSProperty('loaded', true);
@ -1285,6 +1315,8 @@ Property value.
This function will wait until two consecutive locator screenshots This function will wait until two consecutive locator screenshots
yield the same result, and then compare the last screenshot with the expectation. yield the same result, and then compare the last screenshot with the expectation.
**Usage**
```js ```js
const locator = page.getByRole('button'); const locator = page.getByRole('button');
await expect(locator).toHaveScreenshot('image.png'); await expect(locator).toHaveScreenshot('image.png');
@ -1330,6 +1362,8 @@ Snapshot name.
This function will wait until two consecutive locator screenshots This function will wait until two consecutive locator screenshots
yield the same result, and then compare the last screenshot with the expectation. yield the same result, and then compare the last screenshot with the expectation.
**Usage**
```js ```js
const locator = page.getByRole('button'); const locator = page.getByRole('button');
await expect(locator).toHaveScreenshot(); await expect(locator).toHaveScreenshot();
@ -1369,6 +1403,8 @@ await expect(locator).toHaveScreenshot();
Ensures the [Locator] points to an element with the given text. You can use regular expressions for the value as well. Ensures the [Locator] points to an element with the given text. You can use regular expressions for the value as well.
**Usage**
```js ```js
const locator = page.locator('.title'); const locator = page.locator('.title');
await expect(locator).toHaveText(/Welcome, Test User/); await expect(locator).toHaveText(/Welcome, Test User/);
@ -1534,6 +1570,8 @@ Whether to use `element.innerText` instead of `element.textContent` when retriev
Ensures the [Locator] points to an element with the given input value. You can use regular expressions for the value as well. Ensures the [Locator] points to an element with the given input value. You can use regular expressions for the value as well.
**Usage**
```js ```js
const locator = page.locator('input[type=number]'); const locator = page.locator('input[type=number]');
await expect(locator).toHaveValue(/[0-9]/); await expect(locator).toHaveValue(/[0-9]/);
@ -1583,6 +1621,8 @@ Expected value.
Ensures the [Locator] points to multi-select/combobox (i.e. a `select` with the `multiple` attribute) and the specified values are selected. Ensures the [Locator] points to multi-select/combobox (i.e. a `select` with the `multiple` attribute) and the specified values are selected.
**Usage**
For example, given the following element: For example, given the following element:
```html ```html

View file

@ -573,6 +573,8 @@ Adds a script which would be evaluated in one of the following scenarios:
The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend 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 JavaScript environment, e.g. to seed `Math.random`.
**Usage**
An example of overriding `Math.random` before the page loads: An example of overriding `Math.random` before the page loads:
```js browser ```js browser
@ -896,6 +898,8 @@ The snippet below dispatches the `click` event on the element. Regardless of the
is dispatched. This is equivalent to calling is dispatched. This is equivalent to calling
[element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click). [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
**Usage**
```js ```js
await page.dispatchEvent('button#submit', 'click'); await page.dispatchEvent('button#submit', 'click');
``` ```
@ -991,6 +995,8 @@ This method drags the source element to the target element.
It will first move to the source element, perform a `mousedown`, It will first move to the source element, perform a `mousedown`,
then move to the target element and perform a `mouseup`. then move to the target element and perform a `mouseup`.
**Usage**
```js ```js
await page.dragAndDrop('#source', '#target'); await page.dragAndDrop('#source', '#target');
// or specify exact positions relative to the top-left corners of the elements: // or specify exact positions relative to the top-left corners of the elements:
@ -1071,6 +1077,8 @@ await Page.DragAndDropAsync("#source", "#target", new()
This method changes the `CSS media type` through the `media` argument, and/or the `'prefers-colors-scheme'` media feature, using the `colorScheme` argument. This method changes the `CSS media type` through the `media` argument, and/or the `'prefers-colors-scheme'` media feature, using the `colorScheme` argument.
**Usage**
```js ```js
await page.evaluate(() => matchMedia('screen').matches); await page.evaluate(() => matchMedia('screen').matches);
// → true // → true
@ -1292,7 +1300,7 @@ The method finds an element matching the specified selector within the page and
If [`param: expression`] returns a [Promise], then [`method: Page.evalOnSelector`] would wait for the promise to resolve and If [`param: expression`] returns a [Promise], then [`method: Page.evalOnSelector`] would wait for the promise to resolve and
return its value. return its value.
Examples: **Usage**
```js ```js
const searchValue = await page.$eval('#search', el => el.value); const searchValue = await page.$eval('#search', el => el.value);
@ -1360,7 +1368,7 @@ a first argument to [`param: expression`]. Returns the result of [`param: expres
If [`param: expression`] returns a [Promise], then [`method: Page.evalOnSelectorAll`] would wait for the promise to resolve and If [`param: expression`] returns a [Promise], then [`method: Page.evalOnSelectorAll`] would wait for the promise to resolve and
return its value. return its value.
Examples: **Usage**
```js ```js
const divCounts = await page.$$eval('div', (divs, min) => divs.length >= min, 10); const divCounts = await page.$$eval('div', (divs, min) => divs.length >= min, 10);
@ -1407,6 +1415,8 @@ If the function passed to the [`method: Page.evaluate`] returns a non-[Serializa
[`method: Page.evaluate`] resolves to `undefined`. Playwright also supports transferring some [`method: Page.evaluate`] resolves to `undefined`. Playwright also supports transferring some
additional values that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`. additional values that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`.
**Usage**
Passing argument to [`param: expression`]: Passing argument to [`param: expression`]:
```js ```js
@ -1520,6 +1530,8 @@ The only difference between [`method: Page.evaluate`] and [`method: Page.evaluat
If the function passed to the [`method: Page.evaluateHandle`] returns a [Promise], then [`method: Page.evaluateHandle`] would wait for the If the function passed to the [`method: Page.evaluateHandle`] returns a [Promise], then [`method: Page.evaluateHandle`] would wait for the
promise to resolve and return its value. promise to resolve and return its value.
**Usage**
```js ```js
const aWindowHandle = await page.evaluateHandle(() => Promise.resolve(window)); const aWindowHandle = await page.evaluateHandle(() => Promise.resolve(window));
aWindowHandle; // Handle for the window object. aWindowHandle; // Handle for the window object.
@ -1629,6 +1641,8 @@ See [`method: BrowserContext.exposeBinding`] for the context-wide version.
Functions installed via [`method: Page.exposeBinding`] survive navigations. Functions installed via [`method: Page.exposeBinding`] survive navigations.
::: :::
**Usage**
An example of exposing page URL to all frames in a page: An example of exposing page URL to all frames in a page:
```js ```js
@ -1863,6 +1877,8 @@ See [`method: BrowserContext.exposeFunction`] for context-wide exposed function.
Functions installed via [`method: Page.exposeFunction`] survive navigations. Functions installed via [`method: Page.exposeFunction`] survive navigations.
::: :::
**Usage**
An example of adding a `sha256` function to the page: An example of adding a `sha256` function to the page:
```js ```js
@ -2091,6 +2107,8 @@ Shortcut for main frame's [`method: Frame.focus`].
Returns frame matching the specified criteria. Either `name` or `url` must be specified. Returns frame matching the specified criteria. Either `name` or `url` must be specified.
**Usage**
```js ```js
const frame = page.frame('frame-name'); const frame = page.frame('frame-name');
``` ```
@ -2159,7 +2177,11 @@ A glob pattern, regex pattern or predicate receiving frame's `url` as a [URL] ob
- returns: <[FrameLocator]> - returns: <[FrameLocator]>
When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements
in that iframe. Following snippet locates element with text "Submit" in the iframe with id `my-frame`, in that iframe.
**Usage**
Following snippet locates element with text "Submit" in the iframe with id `my-frame`,
like `<iframe id="my-frame">`: like `<iframe id="my-frame">`:
```js ```js
@ -2627,6 +2649,8 @@ By default, `page.pdf()` generates a pdf with modified colors for printing. Use
force rendering of exact colors. force rendering of exact colors.
::: :::
**Usage**
```js ```js
// Generates a PDF with 'screen' media type. // Generates a PDF with 'screen' media type.
await page.emulateMedia({media: 'screen'}); await page.emulateMedia({media: 'screen'});
@ -2831,6 +2855,8 @@ respective texts.
Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When specified with the Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When specified with the
modifier, modifier is pressed and being held while the subsequent key is being pressed. modifier, modifier is pressed and being held while the subsequent key is being pressed.
**Usage**
```js ```js
const page = await browser.newPage(); const page = await browser.newPage();
await page.goto('https://keycode.info'); await page.goto('https://keycode.info');
@ -2992,6 +3018,8 @@ The handler will only be called for the first url if the response is a redirect.
[`method: Page.route`] will not intercept requests intercepted by Service Worker. See [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when using request interception by setting [`option: Browser.newContext.serviceWorkers`] to `'block'`. [`method: Page.route`] will not intercept requests intercepted by Service Worker. See [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when using request interception by setting [`option: Browser.newContext.serviceWorkers`] to `'block'`.
::: :::
**Usage**
An example of a naive handler that aborts all image requests: An example of a naive handler that aborts all image requests:
```js ```js
@ -3209,6 +3237,8 @@ Returns the array of option values that have been successfully selected.
Triggers a `change` and `input` event once all the provided options have been selected. Triggers a `change` and `input` event once all the provided options have been selected.
**Usage**
```js ```js
// single selection matching the value // single selection matching the value
page.selectOption('select#colors', 'blue'); page.selectOption('select#colors', 'blue');
@ -3422,6 +3452,8 @@ In the case of multiple pages in a single browser, each page can have its own vi
[`method: Page.setViewportSize`] will resize the page. A lot of websites don't expect phones to change size, so you should set the [`method: 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. [`method: Page.setViewportSize`] will also reset `screen` size, use [`method: Browser.newContext`] with `screen` and `viewport` parameters if you need better control of these properties. viewport size before navigating to the page. [`method: Page.setViewportSize`] will also reset `screen` size, use [`method: Browser.newContext`] with `screen` and `viewport` parameters if you need better control of these properties.
**Usage**
```js ```js
const page = await browser.newPage(); const page = await browser.newPage();
await page.setViewportSize({ await page.setViewportSize({
@ -3550,6 +3582,8 @@ fine-grained keyboard events. To fill values in form fields, use [`method: Page.
To press a special key, like `Control` or `ArrowDown`, use [`method: Keyboard.press`]. To press a special key, like `Control` or `ArrowDown`, use [`method: Keyboard.press`].
**Usage**
```js ```js
await page.type('#mytextarea', 'Hello'); // Types instantly await page.type('#mytextarea', 'Hello'); // Types instantly
await page.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user await page.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user
@ -3747,6 +3781,8 @@ Receives the [Download] object and resolves to truthy value when the waiting sho
Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
value. Will throw an error if the page is closed before the event is fired. Returns the event data value. value. Will throw an error if the page is closed before the event is fired. Returns the event data value.
**Usage**
```js ```js
// Note that Promise.all prevents a race condition // Note that Promise.all prevents a race condition
// between clicking and waiting for the event. // between clicking and waiting for the event.
@ -3809,6 +3845,8 @@ Receives the [FileChooser] object and resolves to truthy value when the waiting
Returns when the [`param: expression`] returns a truthy value. It resolves to a JSHandle of the truthy value. Returns when the [`param: expression`] returns a truthy value. It resolves to a JSHandle of the truthy value.
**Usage**
The [`method: Page.waitForFunction`] can be used to observe viewport size change: The [`method: Page.waitForFunction`] can be used to observe viewport size change:
```js ```js
@ -3946,6 +3984,8 @@ Returns 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 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. when this method is called. If current document has already reached the required state, resolves immediately.
**Usage**
```js ```js
await page.getByRole('button').click(); // Click triggers navigation. await page.getByRole('button').click(); // Click triggers navigation.
await page.waitForLoadState(); // The promise resolves after 'load' event. await page.waitForLoadState(); // The promise resolves after 'load' event.
@ -4036,6 +4076,8 @@ Waits for the main frame navigation and returns the main resource response. In c
will resolve with the response of the last redirect. In case of navigation to a different anchor or navigation due to 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`. History API usage, the navigation will resolve with `null`.
**Usage**
This resolves when the page navigates to a new URL or reloads. It is useful for when you run code which will indirectly 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`. cause the page to navigate. e.g. The click target has an `onclick` handler that triggers navigation from a `setTimeout`.
Consider this example: Consider this example:
@ -4125,6 +4167,8 @@ Receives the [Page] object and resolves to truthy value when the waiting should
Waits for the matching request and returns it. See [waiting for event](../events.md#waiting-for-event) for more details about events. Waits for the matching request and returns it. See [waiting for event](../events.md#waiting-for-event) for more details about events.
**Usage**
```js ```js
// Note that Promise.all prevents a race condition // Note that Promise.all prevents a race condition
// between clicking and waiting for the request. // between clicking and waiting for the request.
@ -4248,6 +4292,8 @@ Receives the [Request] object and resolves to truthy value when the waiting shou
Returns the matched response. See [waiting for event](../events.md#waiting-for-event) for more details about events. Returns the matched response. See [waiting for event](../events.md#waiting-for-event) for more details about events.
**Usage**
```js ```js
// Note that Promise.all prevents a race condition // Note that Promise.all prevents a race condition
// between clicking and waiting for the response. // between clicking and waiting for the response.
@ -4365,6 +4411,8 @@ visible/hidden). If at the moment of calling the method [`param: selector`] alre
will return immediately. If the selector doesn't satisfy the condition for the [`option: timeout`] milliseconds, the will return immediately. If the selector doesn't satisfy the condition for the [`option: timeout`] milliseconds, the
function will throw. function will throw.
**Usage**
This method works across navigations: This method works across navigations:
```js ```js
@ -4484,6 +4532,8 @@ Waits for the given [`param: timeout`] in milliseconds.
Note that `page.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going to be 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. flaky. Use signals such as network events, selectors becoming visible and others instead.
**Usage**
```js ```js
// wait for 1 second // wait for 1 second
await page.waitForTimeout(1000); await page.waitForTimeout(1000);
@ -4522,6 +4572,8 @@ A timeout to wait for
Waits for the main frame to navigate to the given URL. Waits for the main frame to navigate to the given URL.
**Usage**
```js ```js
await page.click('a.delayed-navigation'); // Clicking the link will indirectly cause a navigation await page.click('a.delayed-navigation'); // Clicking the link will indirectly cause a navigation
await page.waitForURL('**/target.html'); await page.waitForURL('**/target.html');

View file

@ -132,6 +132,8 @@ Expected URL string or RegExp.
This function will wait until two consecutive page screenshots This function will wait until two consecutive page screenshots
yield the same result, and then compare the last screenshot with the expectation. yield the same result, and then compare the last screenshot with the expectation.
**Usage**
```js ```js
await expect(page).toHaveScreenshot('image.png'); await expect(page).toHaveScreenshot('image.png');
``` ```
@ -182,6 +184,8 @@ Snapshot name.
This function will wait until two consecutive page screenshots This function will wait until two consecutive page screenshots
yield the same result, and then compare the last screenshot with the expectation. yield the same result, and then compare the last screenshot with the expectation.
**Usage**
```js ```js
await expect(page).toHaveScreenshot(); await expect(page).toHaveScreenshot();
``` ```
@ -226,6 +230,8 @@ await expect(page).toHaveScreenshot();
Ensures the page has the given title. Ensures the page has the given title.
**Usage**
```js ```js
await expect(page).toHaveTitle(/.*checkout/); await expect(page).toHaveTitle(/.*checkout/);
``` ```
@ -273,6 +279,8 @@ Expected title or RegExp.
Ensures the page is navigated to the given URL. Ensures the page is navigated to the given URL.
**Usage**
```js ```js
await expect(page).toHaveURL(/.*checkout/); await expect(page).toHaveURL(/.*checkout/);
``` ```

View file

@ -84,6 +84,8 @@ By default, the timeout for assertions is set to 5 seconds.
Creates a [APIResponseAssertions] object for the given [APIResponse]. Creates a [APIResponseAssertions] object for the given [APIResponse].
**Usage**
```java ```java
PlaywrightAssertions.assertThat(response).isOK(); PlaywrightAssertions.assertThat(response).isOK();
``` ```
@ -105,6 +107,8 @@ PlaywrightAssertions.assertThat(response).isOK();
Creates a [LocatorAssertions] object for the given [Locator]. Creates a [LocatorAssertions] object for the given [Locator].
**Usage**
```java ```java
PlaywrightAssertions.assertThat(locator).isVisible(); PlaywrightAssertions.assertThat(locator).isVisible();
``` ```
@ -130,6 +134,8 @@ await Expect(locator).ToBeVisibleAsync();
Creates a [PageAssertions] object for the given [Page]. Creates a [PageAssertions] object for the given [Page].
**Usage**
```java ```java
PlaywrightAssertions.assertThat(page).hasTitle("News"); PlaywrightAssertions.assertThat(page).hasTitle("News");
``` ```
@ -150,6 +156,8 @@ await Expect(page).ToHaveTitleAsync("News");
Changes default timeout for Playwright assertions from 5 seconds to the specified value. Changes default timeout for Playwright assertions from 5 seconds to the specified value.
**Usage**
```java ```java
PlaywrightAssertions.setDefaultAssertionTimeout(30_000); PlaywrightAssertions.setDefaultAssertionTimeout(30_000);
``` ```

View file

@ -29,6 +29,8 @@ An object with all the request HTTP headers associated with this request. The he
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.
**Usage**
Example of logging of all the failed requests: Example of logging of all the failed requests:
```js ```js
@ -133,6 +135,8 @@ When the server responds with a redirect, Playwright creates a new [Request] obj
`redirectedFrom()` and `redirectedTo()` methods. When multiple server redirects has happened, it is possible to `redirectedFrom()` and `redirectedTo()` methods. When multiple server redirects has happened, it is possible to
construct the whole redirect chain by repeatedly calling `redirectedFrom()`. construct the whole redirect chain by repeatedly calling `redirectedFrom()`.
**Usage**
For example, if the website `http://example.com` redirects to `https://example.com`: For example, if the website `http://example.com` redirects to `https://example.com`:
```js ```js
@ -193,6 +197,8 @@ Console.WriteLine(response.Request.RedirectedFrom?.Url); // null
New request issued by the browser if the server responded with redirect. New request issued by the browser if the server responded with redirect.
**Usage**
This method is the opposite of [`method: Request.redirectedFrom`]: This method is the opposite of [`method: Request.redirectedFrom`]:
```js ```js
@ -272,6 +278,8 @@ Returns resource timing information for given request. Most of the timing values
`responseEnd` becomes available when request finishes. Find more information at `responseEnd` becomes available when request finishes. Find more information at
[Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming). [Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming).
**Usage**
```js ```js
const [request] = await Promise.all([ const [request] = await Promise.all([
page.waitForEvent('requestfinished'), page.waitForEvent('requestfinished'),

View file

@ -41,6 +41,8 @@ Optional error code. Defaults to `failed`, could be one of the following:
Continues route's request with optional overrides. Continues route's request with optional overrides.
**Usage**
```js ```js
await page.route('**/*', (route, request) => { await page.route('**/*', (route, request) => {
// Override headers // Override headers
@ -138,6 +140,8 @@ That way the last registered route can always override all the previous ones. In
request will be handled by the bottom-most handler first, then it'll fall back to the previous one and request will be handled by the bottom-most handler first, then it'll fall back to the previous one and
in the end will be aborted by the first registered route. in the end will be aborted by the first registered route.
**Usage**
```js ```js
await page.route('**/*', route => { await page.route('**/*', route => {
// Runs last. // Runs last.
@ -409,6 +413,8 @@ If set changes the request HTTP headers. Header values will be converted to a st
Fulfills route's request with given response. Fulfills route's request with given response.
**Usage**
An example of fulfilling all requests with 404 responses: An example of fulfilling all requests with 404 responses:
```js ```js

View file

@ -14,6 +14,8 @@ expect(screenshot).toMatchSnapshot('landing-page.png');
Ensures that passed value, either a [string] or a [Buffer], matches the expected snapshot stored in the test snapshots directory. Ensures that passed value, either a [string] or a [Buffer], matches the expected snapshot stored in the test snapshots directory.
**Usage**
```js ```js
// Basic usage. // Basic usage.
expect(await page.screenshot()).toMatchSnapshot('landing-page.png'); expect(await page.screenshot()).toMatchSnapshot('landing-page.png');
@ -53,6 +55,8 @@ Snapshot name.
Ensures that passed value, either a [string] or a [Buffer], matches the expected snapshot stored in the test snapshots directory. Ensures that passed value, either a [string] or a [Buffer], matches the expected snapshot stored in the test snapshots directory.
**Usage**
```js ```js
// Basic usage and the file name is derived from the test name. // Basic usage and the file name is derived from the test name.
expect(await page.screenshot()).toMatchSnapshot(); expect(await page.screenshot()).toMatchSnapshot();

View file

@ -7,6 +7,8 @@ information.
## async method: Selectors.register ## async method: Selectors.register
* since: v1.8 * since: v1.8
**Usage**
An example of registering selector engine that queries elements based on a tag name: An example of registering selector engine that queries elements based on a tag name:
```js ```js

View file

@ -65,6 +65,8 @@ await context.Tracing.StopAsync(new()
Start tracing. Start tracing.
**Usage**
```js ```js
await context.tracing.start({ screenshots: true, snapshots: true }); await context.tracing.start({ screenshots: true, snapshots: true });
const page = await context.newPage(); const page = await context.newPage();
@ -161,6 +163,8 @@ Trace name to be shown in the Trace Viewer.
Start a new trace chunk. If you'd like to record multiple traces on the same [BrowserContext], use [`method: Tracing.start`] once, and then create multiple trace chunks with [`method: Tracing.startChunk`] and [`method: Tracing.stopChunk`]. Start a new trace chunk. If you'd like to record multiple traces on the same [BrowserContext], use [`method: Tracing.start`] once, and then create multiple trace chunks with [`method: Tracing.startChunk`] and [`method: Tracing.stopChunk`].
**Usage**
```js ```js
await context.tracing.start({ screenshots: true, snapshots: true }); await context.tracing.start({ screenshots: true, snapshots: true });
const page = await context.newPage(); const page = await context.newPage();

File diff suppressed because it is too large Load diff

View file

@ -3387,6 +3387,8 @@ interface APIResponseAssertions {
/** /**
* Ensures the response status code is within `200..299` range. * Ensures the response status code is within `200..299` range.
* *
* **Usage**
*
* ```js * ```js
* await expect(response).toBeOK(); * await expect(response).toBeOK();
* ``` * ```
@ -3426,6 +3428,8 @@ interface LocatorAssertions {
/** /**
* Ensures the [Locator] points to a checked input. * Ensures the [Locator] points to a checked input.
* *
* **Usage**
*
* ```js * ```js
* const locator = page.getByLabel('Subscribe to newsletter'); * const locator = page.getByLabel('Subscribe to newsletter');
* await expect(locator).toBeChecked(); * await expect(locator).toBeChecked();
@ -3449,6 +3453,8 @@ interface LocatorAssertions {
* that only native control elements such as HTML `button`, `input`, `select`, `textarea`, `option`, `optgroup` can be * that only native control elements such as HTML `button`, `input`, `select`, `textarea`, `option`, `optgroup` can be
* disabled by setting "disabled" attribute. "disabled" attribute on other elements is ignored by the browser. * disabled by setting "disabled" attribute. "disabled" attribute on other elements is ignored by the browser.
* *
* **Usage**
*
* ```js * ```js
* const locator = page.locator('button.submit'); * const locator = page.locator('button.submit');
* await expect(locator).toBeDisabled(); * await expect(locator).toBeDisabled();
@ -3466,6 +3472,8 @@ interface LocatorAssertions {
/** /**
* Ensures the [Locator] points to an editable element. * Ensures the [Locator] points to an editable element.
* *
* **Usage**
*
* ```js * ```js
* const locator = page.getByRole('textbox'); * const locator = page.getByRole('textbox');
* await expect(locator).toBeEditable(); * await expect(locator).toBeEditable();
@ -3485,6 +3493,8 @@ interface LocatorAssertions {
/** /**
* Ensures the [Locator] points to an empty editable element or to a DOM node that has no text. * Ensures the [Locator] points to an empty editable element or to a DOM node that has no text.
* *
* **Usage**
*
* ```js * ```js
* const locator = page.locator('div.warning'); * const locator = page.locator('div.warning');
* await expect(locator).toBeEmpty(); * await expect(locator).toBeEmpty();
@ -3502,6 +3512,8 @@ interface LocatorAssertions {
/** /**
* Ensures the [Locator] points to an enabled element. * Ensures the [Locator] points to an enabled element.
* *
* **Usage**
*
* ```js * ```js
* const locator = page.locator('button.submit'); * const locator = page.locator('button.submit');
* await expect(locator).toBeEnabled(); * await expect(locator).toBeEnabled();
@ -3521,6 +3533,8 @@ interface LocatorAssertions {
/** /**
* Ensures the [Locator] points to a focused DOM node. * Ensures the [Locator] points to a focused DOM node.
* *
* **Usage**
*
* ```js * ```js
* const locator = page.getByRole('textbox'); * const locator = page.getByRole('textbox');
* await expect(locator).toBeFocused(); * await expect(locator).toBeFocused();
@ -3539,6 +3553,8 @@ interface LocatorAssertions {
* Ensures that [Locator] either does not resolve to any DOM node, or resolves to a * Ensures that [Locator] either does not resolve to any DOM node, or resolves to a
* [non-visible](https://playwright.dev/docs/api/actionability#visible) one. * [non-visible](https://playwright.dev/docs/api/actionability#visible) one.
* *
* **Usage**
*
* ```js * ```js
* const locator = page.locator('.my-element'); * const locator = page.locator('.my-element');
* await expect(locator).toBeHidden(); * await expect(locator).toBeHidden();
@ -3557,6 +3573,8 @@ interface LocatorAssertions {
* Ensures that [Locator] points to an [attached](https://playwright.dev/docs/api/actionability#attached) and * Ensures that [Locator] points to an [attached](https://playwright.dev/docs/api/actionability#attached) and
* [visible](https://playwright.dev/docs/api/actionability#visible) DOM node. * [visible](https://playwright.dev/docs/api/actionability#visible) DOM node.
* *
* **Usage**
*
* ```js * ```js
* const locator = page.locator('.my-element'); * const locator = page.locator('.my-element');
* await expect(locator).toBeVisible(); * await expect(locator).toBeVisible();
@ -3577,6 +3595,8 @@ interface LocatorAssertions {
* Ensures the [Locator] points to an element that contains the given text. You can use regular expressions for the * Ensures the [Locator] points to an element that contains the given text. You can use regular expressions for the
* value as well. * value as well.
* *
* **Usage**
*
* ```js * ```js
* const locator = page.locator('.title'); * const locator = page.locator('.title');
* await expect(locator).toContainText('substring'); * await expect(locator).toContainText('substring');
@ -3639,6 +3659,8 @@ interface LocatorAssertions {
/** /**
* Ensures the [Locator] points to an element with given attribute. * Ensures the [Locator] points to an element with given attribute.
* *
* **Usage**
*
* ```js * ```js
* const locator = page.locator('input'); * const locator = page.locator('input');
* await expect(locator).toHaveAttribute('type', 'text'); * await expect(locator).toHaveAttribute('type', 'text');
@ -3659,6 +3681,8 @@ interface LocatorAssertions {
* Ensures the [Locator] points to an element with given CSS classes. This needs to be a full match or using a relaxed * Ensures the [Locator] points to an element with given CSS classes. This needs to be a full match or using a relaxed
* regular expression. * regular expression.
* *
* **Usage**
*
* ```html * ```html
* <div class='selected row' id='component'></div> * <div class='selected row' id='component'></div>
* ``` * ```
@ -3689,6 +3713,8 @@ interface LocatorAssertions {
/** /**
* Ensures the [Locator] resolves to an exact number of DOM nodes. * Ensures the [Locator] resolves to an exact number of DOM nodes.
* *
* **Usage**
*
* ```js * ```js
* const list = page.locator('list > .component'); * const list = page.locator('list > .component');
* await expect(list).toHaveCount(3); * await expect(list).toHaveCount(3);
@ -3707,6 +3733,8 @@ interface LocatorAssertions {
/** /**
* Ensures the [Locator] resolves to an element with the given computed CSS style. * Ensures the [Locator] resolves to an element with the given computed CSS style.
* *
* **Usage**
*
* ```js * ```js
* const locator = page.getByRole('button'); * const locator = page.getByRole('button');
* await expect(locator).toHaveCSS('display', 'flex'); * await expect(locator).toHaveCSS('display', 'flex');
@ -3726,6 +3754,8 @@ interface LocatorAssertions {
/** /**
* Ensures the [Locator] points to an element with the given DOM Node ID. * Ensures the [Locator] points to an element with the given DOM Node ID.
* *
* **Usage**
*
* ```js * ```js
* const locator = page.getByRole('textbox'); * const locator = page.getByRole('textbox');
* await expect(locator).toHaveId('lastname'); * await expect(locator).toHaveId('lastname');
@ -3745,6 +3775,8 @@ interface LocatorAssertions {
* Ensures the [Locator] points to an element with given JavaScript property. Note that this property can be of a * Ensures the [Locator] points to an element with given JavaScript property. Note that this property can be of a
* primitive type as well as a plain serializable JavaScript object. * primitive type as well as a plain serializable JavaScript object.
* *
* **Usage**
*
* ```js * ```js
* const locator = page.locator('.component'); * const locator = page.locator('.component');
* await expect(locator).toHaveJSProperty('loaded', true); * await expect(locator).toHaveJSProperty('loaded', true);
@ -3765,6 +3797,8 @@ interface LocatorAssertions {
* This function will wait until two consecutive locator screenshots yield the same result, and then compare the last * This function will wait until two consecutive locator screenshots yield the same result, and then compare the last
* screenshot with the expectation. * screenshot with the expectation.
* *
* **Usage**
*
* ```js * ```js
* const locator = page.getByRole('button'); * const locator = page.getByRole('button');
* await expect(locator).toHaveScreenshot('image.png'); * await expect(locator).toHaveScreenshot('image.png');
@ -3840,6 +3874,8 @@ interface LocatorAssertions {
* This function will wait until two consecutive locator screenshots yield the same result, and then compare the last * This function will wait until two consecutive locator screenshots yield the same result, and then compare the last
* screenshot with the expectation. * screenshot with the expectation.
* *
* **Usage**
*
* ```js * ```js
* const locator = page.getByRole('button'); * const locator = page.getByRole('button');
* await expect(locator).toHaveScreenshot(); * await expect(locator).toHaveScreenshot();
@ -3914,6 +3950,8 @@ interface LocatorAssertions {
* Ensures the [Locator] points to an element with the given text. You can use regular expressions for the value as * Ensures the [Locator] points to an element with the given text. You can use regular expressions for the value as
* well. * well.
* *
* **Usage**
*
* ```js * ```js
* const locator = page.locator('.title'); * const locator = page.locator('.title');
* await expect(locator).toHaveText(/Welcome, Test User/); * await expect(locator).toHaveText(/Welcome, Test User/);
@ -3976,6 +4014,8 @@ interface LocatorAssertions {
* Ensures the [Locator] points to an element with the given input value. You can use regular expressions for the * Ensures the [Locator] points to an element with the given input value. You can use regular expressions for the
* value as well. * value as well.
* *
* **Usage**
*
* ```js * ```js
* const locator = page.locator('input[type=number]'); * const locator = page.locator('input[type=number]');
* await expect(locator).toHaveValue(/[0-9]/); * await expect(locator).toHaveValue(/[0-9]/);
@ -3995,6 +4035,8 @@ interface LocatorAssertions {
* Ensures the [Locator] points to multi-select/combobox (i.e. a `select` with the `multiple` attribute) and the * Ensures the [Locator] points to multi-select/combobox (i.e. a `select` with the `multiple` attribute) and the
* specified values are selected. * specified values are selected.
* *
* **Usage**
*
* For example, given the following element: * For example, given the following element:
* *
* ```html * ```html
@ -4054,6 +4096,8 @@ interface PageAssertions {
* This function will wait until two consecutive page screenshots yield the same result, and then compare the last * This function will wait until two consecutive page screenshots yield the same result, and then compare the last
* screenshot with the expectation. * screenshot with the expectation.
* *
* **Usage**
*
* ```js * ```js
* await expect(page).toHaveScreenshot('image.png'); * await expect(page).toHaveScreenshot('image.png');
* ``` * ```
@ -4159,6 +4203,8 @@ interface PageAssertions {
* This function will wait until two consecutive page screenshots yield the same result, and then compare the last * This function will wait until two consecutive page screenshots yield the same result, and then compare the last
* screenshot with the expectation. * screenshot with the expectation.
* *
* **Usage**
*
* ```js * ```js
* await expect(page).toHaveScreenshot(); * await expect(page).toHaveScreenshot();
* ``` * ```
@ -4262,6 +4308,8 @@ interface PageAssertions {
/** /**
* Ensures the page has the given title. * Ensures the page has the given title.
* *
* **Usage**
*
* ```js * ```js
* await expect(page).toHaveTitle(/.*checkout/); * await expect(page).toHaveTitle(/.*checkout/);
* ``` * ```
@ -4279,6 +4327,8 @@ interface PageAssertions {
/** /**
* Ensures the page is navigated to the given URL. * Ensures the page is navigated to the given URL.
* *
* **Usage**
*
* ```js * ```js
* await expect(page).toHaveURL(/.*checkout/); * await expect(page).toHaveURL(/.*checkout/);
* ``` * ```
@ -4307,6 +4357,8 @@ interface ScreenshotAssertions {
* Ensures that passed value, either a [string] or a [Buffer], matches the expected snapshot stored in the test * Ensures that passed value, either a [string] or a [Buffer], matches the expected snapshot stored in the test
* snapshots directory. * snapshots directory.
* *
* **Usage**
*
* ```js * ```js
* // Basic usage. * // Basic usage.
* expect(await page.screenshot()).toMatchSnapshot('landing-page.png'); * expect(await page.screenshot()).toMatchSnapshot('landing-page.png');
@ -4353,6 +4405,8 @@ interface ScreenshotAssertions {
* Ensures that passed value, either a [string] or a [Buffer], matches the expected snapshot stored in the test * Ensures that passed value, either a [string] or a [Buffer], matches the expected snapshot stored in the test
* snapshots directory. * snapshots directory.
* *
* **Usage**
*
* ```js * ```js
* // Basic usage and the file name is derived from the test name. * // Basic usage and the file name is derived from the test name.
* expect(await page.screenshot()).toMatchSnapshot(); * expect(await page.screenshot()).toMatchSnapshot();