docs: bring snippets higher up in the docs

This commit is contained in:
Pavel Feldman 2020-05-02 17:21:46 -07:00
parent 03ca297890
commit 3979d4f492
4 changed files with 74 additions and 146 deletions

View file

@ -21,14 +21,14 @@ Most of these parameters are configured during the browser context construction,
## User agent ## User agent
All pages created in the context above will share the user agent specified:
```js ```js
const context = await browser.newContext({ const context = await browser.newContext({
userAgent: 'My user agent' userAgent: 'My user agent'
}); });
``` ```
All pages created in the context above will share the user agent specified.
#### API reference #### API reference
- [`browser.newContext([options])`](./api.md#browsernewcontextoptions) - [`browser.newContext([options])`](./api.md#browsernewcontextoptions)
@ -40,42 +40,27 @@ All pages created in the context above will share the user agent specified.
Create a context with custom viewport size: Create a context with custom viewport size:
```js ```js
// Create context with given viewport
const context = await browser.newContext({ const context = await browser.newContext({
viewport: { viewport: { width: 1280, height: 1024 }
width: 1280,
height: 1024
}
}); });
```
Resize viewport for individual pages:
```js // Resize viewport for individual page
await page.setViewportSize({ 'width': 1600, 'height': 1200 }); await page.setViewportSize(
``` { 'width': 1600, 'height': 1200 });
Emulate desktop device with the high-DPI screen and touch support: // Emulate high-DPI
```js
const context = await browser.newContext({ const context = await browser.newContext({
viewport: { viewport: { width: 2560, height: 1440 },
width: 2560,
height: 1440,
},
deviceScaleFactor: 2, deviceScaleFactor: 2,
hasTouch: true
}); });
```
Create device with the dark color scheme: // Create device with the dark color scheme:
```js
const context = await browser.newContext({ const context = await browser.newContext({
colorScheme: 'dark' colorScheme: 'dark'
}); });
```
Change color scheme for individual pages: // Change color scheme for the page
```js
await page.emulateMedia({ colorScheme: 'dark' }); await page.emulateMedia({ colorScheme: 'dark' });
``` ```
@ -92,7 +77,8 @@ await page.emulateMedia({ colorScheme: 'dark' });
Playwright comes with a registry of device parameters for selected mobile devices. It can be used to simulate browser behavior on a mobile device: Playwright comes with a registry of device parameters for selected mobile devices. It can be used to simulate browser behavior on a mobile device:
```js ```js
const { chromium, devices } = require('playwright'); const { chromium, devices } =
require('playwright');
const browser = await chromium.launch(); const browser = await chromium.launch();
const pixel2 = devices['Pixel 2']; const pixel2 = devices['Pixel 2'];
@ -113,6 +99,7 @@ All pages created in the context above will share the same device parameters.
## Locale & timezone ## Locale & timezone
```js ```js
// Emulate locale and time
const context = await browser.newContext({ const context = await browser.newContext({
locale: 'de-DE', locale: 'de-DE',
timezoneId: 'Europe/Berlin', timezoneId: 'Europe/Berlin',

View file

@ -14,22 +14,19 @@
## Text input ## Text input
```js
await page.fill('#name', 'Peter');
```
This is the easiest way to fill out the form fields. It focuses the element and triggers an `input` event with the entered text. It works for `<input>`, `<textarea>` and `[contenteditable]` elements. This is the easiest way to fill out the form fields. It focuses the element and triggers an `input` event with the entered text. It works for `<input>`, `<textarea>` and `[contenteditable]` elements.
#### Variations
```js ```js
// <input id=date type=date> // Text input
await page.fill('#name', 'Peter');
// Date input
await page.fill('#date', '2020-02-02'); await page.fill('#date', '2020-02-02');
// <input id=date type=time> // Time input
await page.fill('#time', '13-15'); await page.fill('#time', '13-15');
// <input id=local type=datetime-local> // Local datetime input
await page.fill('#local', '2020-03-02T05:15'); await page.fill('#local', '2020-03-02T05:15');
``` ```
@ -43,16 +40,16 @@ await page.fill('#local', '2020-03-02T05:15');
## Checkboxes ## Checkboxes
This is the easiest way to check and uncheck a checkbox. This method can be used on the `input[type=checkbox]` and on the `label` associated with that input.
```js ```js
// <input id=agree type=checkbox></input> // Check the checkbox
await page.check('#agree'); await page.check('#agree');
// <label id=subscribe-label for=subscribe><input id=subscribe type=checkbox checked></input></label> // Uncheck by input <label>.
await page.uncheck('#subscribe-label'); await page.uncheck('#subscribe-label');
``` ```
This is the easiest way to check and uncheck a checkbox. This method can be used on the `input[type=checkbox]` and on the `label` associated with that input.
#### API reference #### API reference
- [page.check(selector[, options])](./api.md#pagecheckselector-options) — main frame - [page.check(selector[, options])](./api.md#pagecheckselector-options) — main frame
@ -66,21 +63,9 @@ This is the easiest way to check and uncheck a checkbox. This method can be used
## Select options ## Select options
```js
// <select id=colors>
// <option value="red">Red</option>
// <option value="green">Green</option>
// <option value="blue">Blue</option>
// </select>
await page.selectOption('select#colors', 'green');
```
Selects one or multiple options in the `<select>` element. Selects one or multiple options in the `<select>` element.
You can specify option `value`, `label` or `elementHandle` to select. Multiple options can be selected. You can specify option `value`, `label` or `elementHandle` to select. Multiple options can be selected.
#### Variations
```js ```js
// Single selection matching the value // Single selection matching the value
await page.selectOption('select#colors', 'blue'); await page.selectOption('select#colors', 'blue');
@ -91,7 +76,7 @@ await page.selectOption('select#colors', { label: 'Blue' });
// Multiple selected items // Multiple selected items
await page.selectOption('select#colors', ['red', 'green', 'blue']); await page.selectOption('select#colors', ['red', 'green', 'blue']);
// Select the option element handle // Select the option via element handle
const option = await page.$('#best-option'); const option = await page.$('#best-option');
await page.selectOption('select#colors', option); await page.selectOption('select#colors', option);
``` ```
@ -106,13 +91,29 @@ await page.selectOption('select#colors', option);
## Mouse click ## Mouse click
```js Performs a simple human click.
// <button id=submit></button>
```js
// Generic click
await page.click('button#submit'); await page.click('button#submit');
// Double click
await page.dblclick('#item');
// Right click
await page.click('#item', { button: 'right' });
// Shift + click
await page.click('#item', { modifiers: ['Shift'] });
// Hover over element
await page.hover('#item');
// Click the top left corner
await page.click('#item', { position: { x: 0, y: 0} });
``` ```
Performs a simple human click. Under the hood, this and other pointer-related methods: Under the hood, this and other pointer-related methods:
- wait for element with given selector to be in DOM - wait for element with given selector to be in DOM
- wait for it to become displayed, i.e. not empty, no `display:none`, no `visibility:hidden` - wait for it to become displayed, i.e. not empty, no `display:none`, no `visibility:hidden`
@ -121,25 +122,6 @@ Performs a simple human click. Under the hood, this and other pointer-related me
- wait for it to receive pointer events at the action point, for example, waits until element becomes non-obscured by other elements - wait for it to receive pointer events at the action point, for example, waits until element becomes non-obscured by other elements
- retry if the element is detached during any of the above checks - retry if the element is detached during any of the above checks
#### Variations
```js
// Double click element
await page.dblclick('#item');
// Right click element
await page.click('#item', { button: 'right' });
// Shift click element
await page.click('#item', { modifiers: ['Shift'] });
// Hover over element without clicking
await page.hover('#item');
// Click the top left corner of the element
await page.click('#item', { position: { x: 0, y: 0} });
```
#### API reference #### API reference
- [page.click(selector[, options])](./api.md#pageclickselector-options) — main frame - [page.click(selector[, options])](./api.md#pageclickselector-options) — main frame
@ -156,15 +138,16 @@ await page.click('#item', { position: { x: 0, y: 0} });
## Type characters ## Type characters
```js Type into the field character by character, as if it was a user with a real keyboard.
// <textarea id=area></textarea>
```js
// Type characted by character
await page.type('#area', 'Hello World!'); await page.type('#area', 'Hello World!');
``` ```
Note that most of the time, [`page.fill`](#text-input) will just work. You only need to type characters if there is special keyboard handling on the page. This method will emit all the necessary keyboard events, with all the `keydown`, `keyup`, `keypress` events in place. You can even specify the optional `delay` between the key presses to simulate real user behavior.
But sometimes it is important to type into the field character by character, as if it was a user with a real keyboard. This method will emit all the necessary keyboard events, with all the `keydown`, `keyup`, `keypress` events in place. You can even specify the optional `delay` between the key presses to simulate real user behavior. > **NOTE** that most of the time, [`page.fill`](#text-input) will just work. You only need to type characters if there is special keyboard handling on the page.
#### API reference #### API reference
@ -178,13 +161,13 @@ But sometimes it is important to type into the field character by character, as
## Keys and shortcuts ## Keys and shortcuts
```js ```js
// <button id=submit></button> // Hit Enter
await page.press('#submit', 'Enter'); await page.press('#submit', 'Enter');
// <input id=name></input> // Dispatch Control+Right
await page.press('#name', 'Control+ArrowRight'); await page.press('#name', 'Control+ArrowRight');
// <input id=value></input> // Press $ sign on keyboard
await page.press('#value', '$'); await page.press('#value', '$');
``` ```
@ -200,14 +183,6 @@ ArrowUp, F1 - F12, Digit0 - Digit9, KeyA - KeyZ, etc.
- Following modification shortcuts are also supported: `Shift, Control, Alt, Meta`. - Following modification shortcuts are also supported: `Shift, Control, Alt, Meta`.
#### Variations
```js
// <input id=name></input>
await page.press('#name', '$');
```
Simple version produces a single character. This character is case-sensitive, so `"a"` and `"A"` will produce different results. Simple version produces a single character. This character is case-sensitive, so `"a"` and `"A"` will produce different results.
@ -236,30 +211,25 @@ Note that you still need to specify the capital `A` in `Shift-A` to produce the
## Upload files ## Upload files
```js ```js
// <input id=upload type=file> // Select one file
await page.setInputFiles('input#upload', 'myfile.pdf'); await page.setInputFiles('input#upload', 'myfile.pdf');
```
You can select input files for upload using the `page.setInputFiles` method. It expects first argument to point to an [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) with the type `"file"`. Multiple files can be passed in the array. If some of the file paths are relative, they are resolved relative to the [current working directory](https://nodejs.org/api/process.html#process_process_cwd). Empty array clears the selected files. // Select multiple files
#### Variations
```js
// Select multiple files.
await page.setInputFiles('input#upload', ['file1.txt', 'file2.txt']); await page.setInputFiles('input#upload', ['file1.txt', 'file2.txt']);
// Upload buffer from memory, without reading from file. // Remove all the selected files
await page.setInputFiles('input#upload', []);
// Upload buffer from memory
await page.setInputFiles('input#upload', { await page.setInputFiles('input#upload', {
name: 'file.txt', name: 'file.txt',
mimeType: 'text/plain', mimeType: 'text/plain',
buffer: Buffer.from('this is test') buffer: Buffer.from('this is test')
}); });
// Remove all the selected files
await page.setInputFiles('input#upload', []);
``` ```
You can select input files for upload using the `page.setInputFiles` method. It expects first argument to point to an [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) with the type `"file"`. Multiple files can be passed in the array. If some of the file paths are relative, they are resolved relative to the [current working directory](https://nodejs.org/api/process.html#process_process_cwd). Empty array clears the selected files.
#### API reference #### API reference
- [page.setInputFiles(selector, files[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#pagesetinputfilesselector-value-options) - [page.setInputFiles(selector, files[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#pagesetinputfilesselector-value-options)
@ -270,15 +240,12 @@ await page.setInputFiles('input#upload', []);
## Focus element ## Focus element
For the dynamic pages that handle focus events, you can focus the given element.
```js ```js
// <input id=name>
await page.focus('input#name'); await page.focus('input#name');
``` ```
For the dynamic pages that handle focus events, you can focus the given element.
#### API reference #### API reference
- [page.focus(selector, [options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#pagefocusselector-options) - [page.focus(selector, [options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#pagefocusselector-options)

View file

@ -127,8 +127,6 @@ const [response] = await Promise.all([
## Handle requests ## Handle requests
You can mock API endpoints via handling the network quests in your Playwright script.
```js ```js
await page.route('**/api/fetch_data', route => route.fulfill({ await page.route('**/api/fetch_data', route => route.fulfill({
status: 200, status: 200,
@ -137,6 +135,8 @@ await page.route('**/api/fetch_data', route => route.fulfill({
await page.goto('https://example.com'); await page.goto('https://example.com');
``` ```
You can mock API endpoints via handling the network quests in your Playwright script.
#### Variations #### Variations
```js ```js
@ -163,45 +163,29 @@ await page.goto('https://example.com');
## Modify requests ## Modify requests
```js ```js
// Delete header
await page.route('**/*', route => { await page.route('**/*', route => {
const headers = route.request().headers(); const headers = route.request().headers();
delete headers['X-Secret']; delete headers['X-Secret'];
route.continue({headers}); route.continue({headers});
}); });
await page.goto('https://chromium.org');
// Continue requests as POST.
await page.route('**/*', route => route.continue({method: 'POST'}));
``` ```
You can continue requests with modifications. Example above removes an HTTP header from the outgoing requests. You can continue requests with modifications. Example above removes an HTTP header from the outgoing requests.
#### Variations
```js
// Continue requests as POST.
await page.route('**/*', route => route.continue({method: 'POST'}));
await page.goto('https://chromium.org');
```
<br/>
## Abort requests ## Abort requests
```js ```js
const page = await browser.newPage();
await page.route('**/*.{png,jpg,jpeg}', route => route.abort()); await page.route('**/*.{png,jpg,jpeg}', route => route.abort());
await page.goto('https://example.com');
```
#### Variations
```js
// Abort requests based on their type.
// Abort based on the request type
await page.route('**/*', route => { await page.route('**/*', route => {
return route.request().resourceType() === 'image' ? return route.request().resourceType() === 'image' ?
route.abort() : route.continue(); route.abort() : route.continue();
}); });
await page.goto('https://chromium.org');
``` ```
#### API reference #### API reference

View file

@ -64,30 +64,20 @@ await myArrayHandle.dispose();
## Capturing screenshot ## Capturing screenshot
Take screenshot of the page's viewport and save it in a png file:
```js ```js
// Save to file
await page.screenshot({path: 'screenshot.png'}); await page.screenshot({path: 'screenshot.png'});
```
#### Variations // Capture full page
Capture particular element:
```js
const elementHandle = await page.$('.header');
await elementHandle.screenshot({ path: 'screenshot.png' });
```
Capture full page screenshot:
```js
await page.screenshot({path: 'screenshot.png', fullPage: true}); await page.screenshot({path: 'screenshot.png', fullPage: true});
```
Capture screenshot into a Node [Buffer](https://nodejs.org/api/buffer.html#buffer_class_buffer). // Capture into buffer
```js
const buffer = await page.screenshot(); const buffer = await page.screenshot();
console.log(buffer.toString('base64')); console.log(buffer.toString('base64'));
```
// Capture given element
const elementHandle = await page.$('.header');
await elementHandle.screenshot({ path: 'screenshot.png' });
#### API reference #### API reference