Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
docs: bring snippets higher up in the docs
Pavel Feldman3979d4f4921e
diff --git a/docs/emulation.md b/docs/emulation.mdindex 61f5106bbc..9b14b00b5e 100644--- a/docs/emulation.md+++ b/docs/emulation.md@@ -21,14 +21,14 @@ Most of these parameters are configured during the browser context construction,## User agent+All pages created in the context above will share the user agent specified:+```jsconst context = await browser.newContext({userAgent: 'My user agent'});```-All pages created in the context above will share the user agent specified.-#### API reference- [`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:```js+// Create context with given viewportconst context = await browser.newContext({- viewport: {- width: 1280,- height: 1024- }+ viewport: { width: 1280, height: 1024 }});-```-Resize viewport for individual pages:--```js-await page.setViewportSize({ 'width': 1600, 'height': 1200 });-```-Emulate desktop device with the high-DPI screen and touch support:+// Resize viewport for individual page+await page.setViewportSize(+ { 'width': 1600, 'height': 1200 });-```js+// Emulate high-DPIconst context = await browser.newContext({- viewport: {- width: 2560,- height: 1440,- },+ viewport: { width: 2560, height: 1440 },deviceScaleFactor: 2,- hasTouch: true});-```-Create device with the dark color scheme:-```js+// Create device with the dark color scheme:const context = await browser.newContext({colorScheme: 'dark'});-```--Change color scheme for individual pages:-```js+// Change color scheme for the pageawait 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:```js-const { chromium, devices } = require('playwright');+const { chromium, devices } =+ require('playwright');const browser = await chromium.launch();const pixel2 = devices['Pixel 2'];@@ -113,6 +99,7 @@ All pages created in the context above will share the same device parameters.## Locale & timezone```js+// Emulate locale and timeconst context = await browser.newContext({locale: 'de-DE',timezoneId: 'Europe/Berlin',diff --git a/docs/input.md b/docs/input.mdindex e5468acab7..16b1268450 100644--- a/docs/input.md+++ b/docs/input.md@@ -14,22 +14,19 @@## 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.-#### Variations-```js-// <input id=date type=date>+// Text input+await page.fill('#name', 'Peter');++// Date inputawait page.fill('#date', '2020-02-02');-// <input id=date type=time>+// Time inputawait page.fill('#time', '13-15');-// <input id=local type=datetime-local>+// Local datetime inputawait page.fill('#local', '2020-03-02T05:15');```@@ -43,16 +40,16 @@ await page.fill('#local', '2020-03-02T05:15');## 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-// <input id=agree type=checkbox></input>+// Check the checkboxawait 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');```-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- [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-```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.You can specify option `value`, `label` or `elementHandle` to select. Multiple options can be selected.-#### Variations-```js// Single selection matching the valueawait page.selectOption('select#colors', 'blue');@@ -91,7 +76,7 @@ await page.selectOption('select#colors', { label: 'Blue' });// Multiple selected itemsawait page.selectOption('select#colors', ['red', 'green', 'blue']);-// Select the option element handle+// Select the option via element handleconst option = await page.$('#best-option');await page.selectOption('select#colors', option);```@@ -106,40 +91,37 @@ await page.selectOption('select#colors', option);## Mouse click-```js-// <button id=submit></button>+Performs a simple human click.+```js+// Generic clickawait page.click('button#submit');-```--Performs a simple human click. Under the hood, this and other pointer-related methods:--- 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 stop moving, for example, until css transition finishes-- scroll the element into view-- 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--#### Variations-```js-// Double click element+// Double clickawait page.dblclick('#item');-// Right click element+// Right clickawait page.click('#item', { button: 'right' });-// Shift click element+// Shift + clickawait page.click('#item', { modifiers: ['Shift'] });-// Hover over element without clicking+// Hover over elementawait page.hover('#item');-// Click the top left corner of the element+// Click the top left cornerawait page.click('#item', { position: { x: 0, y: 0} });```+Under the hood, this and other pointer-related methods:++- 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 stop moving, for example, until css transition finishes+- scroll the element into view+- 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+#### API reference- [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-```js-// <textarea id=area></textarea>+Type into the field character by character, as if it was a user with a real keyboard.+```js+// Type characted by characterawait 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@@ -178,13 +161,13 @@ But sometimes it is important to type into the field character by character, as## Keys and shortcuts```js-// <button id=submit></button>+// Hit Enterawait page.press('#submit', 'Enter');-// <input id=name></input>+// Dispatch Control+Rightawait page.press('#name', 'Control+ArrowRight');-// <input id=value></input>+// Press $ sign on keyboardawait 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`.--#### 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.@@ -236,30 +211,25 @@ Note that you still need to specify the capital `A` in `Shift-A` to produce the## Upload files```js-// <input id=upload type=file>-+// Select one fileawait 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.--#### Variations--```js-// Select multiple files.+// Select multiple filesawait 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 memoryawait page.setInputFiles('input#upload', {name: 'file.txt',mimeType: 'text/plain',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- [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+For the dynamic pages that handle focus events, you can focus the given element.```js-// <input id=name>-await page.focus('input#name');```-For the dynamic pages that handle focus events, you can focus the given element.-#### API reference- [page.focus(selector, [options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#pagefocusselector-options)diff --git a/docs/network.md b/docs/network.mdindex bf1f88f8fe..f92896be9a 100644--- a/docs/network.md+++ b/docs/network.md@@ -127,8 +127,6 @@ const [response] = await Promise.all([## Handle requests-You can mock API endpoints via handling the network quests in your Playwright script.-```jsawait page.route('**/api/fetch_data', route => route.fulfill({status: 200,@@ -137,6 +135,8 @@ await page.route('**/api/fetch_data', route => route.fulfill({await page.goto('https://example.com');```+You can mock API endpoints via handling the network quests in your Playwright script.+#### Variations```js@@ -163,45 +163,29 @@ await page.goto('https://example.com');## Modify requests```js+// Delete headerawait page.route('**/*', route => {const headers = route.request().headers();delete headers['X-Secret'];route.continue({headers});});-await page.goto('https://chromium.org');-```-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/>+You can continue requests with modifications. Example above removes an HTTP header from the outgoing requests.## Abort requests```js-const page = await browser.newPage();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 typeawait page.route('**/*', route => {return route.request().resourceType() === 'image' ?route.abort() : route.continue();});-await page.goto('https://chromium.org');```#### API referencediff --git a/docs/verification.md b/docs/verification.mdindex d52249c194..54d6ef16e4 100644--- a/docs/verification.md+++ b/docs/verification.md@@ -64,30 +64,20 @@ await myArrayHandle.dispose();## Capturing screenshot-Take screenshot of the page's viewport and save it in a png file:```js+// Save to fileawait page.screenshot({path: 'screenshot.png'});-```--#### Variations--Capture particular element:-```js-const elementHandle = await page.$('.header');-await elementHandle.screenshot({ path: 'screenshot.png' });-```-Capture full page screenshot:-```js+// Capture full pageawait page.screenshot({path: 'screenshot.png', fullPage: true});-```-Capture screenshot into a Node [Buffer](https://nodejs.org/api/buffer.html#buffer_class_buffer).-```js+// Capture into bufferconst buffer = await page.screenshot();console.log(buffer.toString('base64'));-```+// Capture given element+const elementHandle = await page.$('.header');+await elementHandle.screenshot({ path: 'screenshot.png' });#### API reference