doc: split classes into files (#4864)

This commit is contained in:
Pavel Feldman 2021-01-01 15:17:27 -08:00 committed by GitHub
parent ba291372e7
commit e0e836cb6e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
100 changed files with 9063 additions and 8424 deletions

View file

@ -1,6 +1,5 @@
# Contributing # Contributing
<!-- gen:toc -->
- [How to Contribute](#how-to-contribute) - [How to Contribute](#how-to-contribute)
* [Getting Code](#getting-code) * [Getting Code](#getting-code)
* [Code reviews](#code-reviews) * [Code reviews](#code-reviews)
@ -13,7 +12,6 @@
* [Public API Coverage](#public-api-coverage) * [Public API Coverage](#public-api-coverage)
- [Contributor License Agreement](#contributor-license-agreement) - [Contributor License Agreement](#contributor-license-agreement)
* [Code of Conduct](#code-of-conduct) * [Code of Conduct](#code-of-conduct)
<!-- gen:stop -->
## How to Contribute ## How to Contribute

53
docs-src/README.md Normal file
View file

@ -0,0 +1,53 @@
---
id: README
title: "Documentation"
---
### Capabilities
Playwright is a library to automate [Chromium](https://www.chromium.org/Home), [Firefox](https://www.mozilla.org/en-US/firefox/new/) and [WebKit](https://webkit.org/) with a single API. Playwright is built to enable cross-browser web automation that is **ever-green**, **capable**, **reliable** and **fast**.
* Ever-green browser engines
* Headless execution
* Scenarios that span multiple pages, domains and iframes
* Auto-wait for elements to be ready before executing actions (like click, fill)
* Reliable signals instead of timeouts (like network response, popup, navigation)
* Intercept network activity for stubbing and mocking network requests
* Emulate mobile devices, geolocation, permissions
* Support for web components via shadow-piercing selectors
* Native input events for mouse and keyboard
* Upload and download files
### Table of contents
1. Introduction
- [Why Playwright?](./why-playwright.md)
- [Get started](./intro.md)
- [Core concepts](./core-concepts.md)
- [Debugging](./debug.md)
- [Supported languages](./languages.md)
1. Guides
- [Selectors](./selectors.md)
- [Input](./input.md)
- [Emulation](./emulation.md)
- [Network](./network.md)
- [Assertions](./assertions.md)
- [Verification](./verification.md)
- [Navigations](./navigations.md)
- [Multi-page scenarios](./multi-pages.md)
1. Tutorials
- [Authentication](./auth.md)
- [Page object models](./pom.md)
1. Integrations
- [Test runners](./test-runners.md)
- [Docker](./docker/README.md)
- [Continuous integration](./ci.md)
1. Reference
- [API Reference](./api.md)
- [Actionability](./actionability.md)
- [Advanced installation](./installation.md)
- [Extensibility](./extensibility.md)
1. Get help
- [Slack community](https://join.slack.com/t/playwright/shared_invite/enQtOTEyMTUxMzgxMjIwLThjMDUxZmIyNTRiMTJjNjIyMzdmZDA3MTQxZWUwZTFjZjQwNGYxZGM5MzRmNzZlMWI5ZWUyOTkzMjE5Njg1NDg)
- [Stack Overflow](https://stackoverflow.com/tags/playwright)
- [GitHub](https://github.com/microsoft/playwright/issues)

View file

@ -1,4 +1,7 @@
# Actionability ---
id: actionability
title: "Actionability"
---
Playwright does a range of actionability checks on the elements before performing certain actions. These checks ensure that action behaves as expected, for example Playwright does not click on a disabled button. Playwright does a range of actionability checks on the elements before performing certain actions. These checks ensure that action behaves as expected, for example Playwright does not click on a disabled button.

View file

@ -71,7 +71,7 @@ This object can be used to launch or connect to Firefox, returning instances of
## property: Playwright.selectors ## property: Playwright.selectors
- type: <[Selectors]> - type: <[Selectors]>
Selectors can be used to install custom selector engines. See [Working with selectors](#working-with-selectors) for more information. Selectors can be used to install custom selector engines. See [Working with selectors](./selectors.md#working-with-selectors) for more information.
## property: Playwright.webkit ## property: Playwright.webkit
- type: <[BrowserType]> - type: <[BrowserType]>
@ -2476,7 +2476,7 @@ console.log(text);
Returns the ElementHandle pointing to the frame element. Returns the ElementHandle pointing to the frame element.
The method finds an element matching the specified selector within the frame. See [Working with The method finds an element matching the specified selector within the frame. See [Working with
selectors](#working-with-selectors) for more details. If no elements match the selector, returns `null`. selectors](./selectors.md#working-with-selectors) for more details. If no elements match the selector, returns `null`.
### param: Frame.$.selector = %%-query-selector-%% ### param: Frame.$.selector = %%-query-selector-%%
@ -2486,7 +2486,7 @@ selectors](#working-with-selectors) for more details. If no elements match the s
Returns the ElementHandles pointing to the frame elements. Returns the ElementHandles pointing to the frame elements.
The method finds all elements matching the specified selector within the frame. See [Working with The method finds all elements matching the specified selector within the frame. See [Working with
selectors](#working-with-selectors) for more details. If no elements match the selector, returns empty array. selectors](./selectors.md#working-with-selectors) for more details. If no elements match the selector, returns empty array.
### param: Frame.$$.selector = %%-query-selector-%% ### param: Frame.$$.selector = %%-query-selector-%%
@ -2496,7 +2496,7 @@ selectors](#working-with-selectors) for more details. If no elements match the s
Returns the return value of [`param: pageFunction`] Returns the return value of [`param: pageFunction`]
The method finds an element matching the specified selector within the frame and passes it as a first argument to The method finds an element matching the specified selector within the frame and passes it as a first argument to
[`param: pageFunction`]. See [Working with selectors](#working-with-selectors) for more details. If no elements match [`param: pageFunction`]. See [Working with selectors](./selectors.md#working-with-selectors) for more details. If no elements match
the selector, the method throws an error. the selector, the method throws an error.
If [`param: pageFunction`] returns a [Promise], then `frame.$eval` would wait for the promise to resolve and return If [`param: pageFunction`] returns a [Promise], then `frame.$eval` would wait for the promise to resolve and return
@ -2528,7 +2528,7 @@ Optional argument to pass to [`param: pageFunction`]
Returns the return value of [`param: pageFunction`] Returns the return value of [`param: pageFunction`]
The method finds all elements matching the specified selector within the frame and passes an array of matched elements The method finds all elements matching the specified selector within the frame and passes an array of matched elements
as a first argument to [`param: pageFunction`]. See [Working with selectors](#working-with-selectors) for more as a first argument to [`param: pageFunction`]. See [Working with selectors](./selectors.md#working-with-selectors) for more
details. details.
If [`param: pageFunction`] returns a [Promise], then `frame.$$eval` would wait for the promise to resolve and return If [`param: pageFunction`] returns a [Promise], then `frame.$$eval` would wait for the promise to resolve and return
@ -3326,7 +3326,7 @@ ElementHandle instances can be used as an argument in [`method: Page.$eval`] and
- returns: <[null]|[ElementHandle]> - returns: <[null]|[ElementHandle]>
The method finds an element matching the specified selector in the `ElementHandle`'s subtree. See [Working with The method finds an element matching the specified selector in the `ElementHandle`'s subtree. See [Working with
selectors](#working-with-selectors) for more details. If no elements match the selector, returns `null`. selectors](./selectors.md#working-with-selectors) for more details. If no elements match the selector, returns `null`.
### param: ElementHandle.$.selector = %%-query-selector-%% ### param: ElementHandle.$.selector = %%-query-selector-%%
@ -3334,7 +3334,7 @@ selectors](#working-with-selectors) for more details. If no elements match the s
- returns: <[Array]<[ElementHandle]>> - returns: <[Array]<[ElementHandle]>>
The method finds all elements matching the specified selector in the `ElementHandle`s subtree. See [Working with The method finds all elements matching the specified selector in the `ElementHandle`s subtree. See [Working with
selectors](#working-with-selectors) for more details. If no elements match the selector, returns empty array. selectors](./selectors.md#working-with-selectors) for more details. If no elements match the selector, returns empty array.
### param: ElementHandle.$$.selector = %%-query-selector-%% ### param: ElementHandle.$$.selector = %%-query-selector-%%
@ -3344,7 +3344,7 @@ selectors](#working-with-selectors) for more details. If no elements match the s
Returns the return value of [`param: pageFunction`] Returns the return value of [`param: pageFunction`]
The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a first The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a first
argument to [`param: pageFunction`]. See [Working with selectors](#working-with-selectors) for more details. If no argument to [`param: pageFunction`]. See [Working with selectors](./selectors.md#working-with-selectors) for more details. If no
elements match the selector, the method throws an error. elements match the selector, the method throws an error.
If [`param: pageFunction`] returns a [Promise], then `frame.$eval` would wait for the promise to resolve and return If [`param: pageFunction`] returns a [Promise], then `frame.$eval` would wait for the promise to resolve and return
@ -3376,7 +3376,7 @@ Optional argument to pass to [`param: pageFunction`]
Returns the return value of [`param: pageFunction`] Returns the return value of [`param: pageFunction`]
The method finds all elements matching the specified selector in the `ElementHandle`'s subtree and passes an array of The method finds all elements matching the specified selector in the `ElementHandle`'s subtree and passes an array of
matched elements as a first argument to [`param: pageFunction`]. See [Working with selectors](#working-with-selectors) matched elements as a first argument to [`param: pageFunction`]. See [Working with selectors](./selectors.md#working-with-selectors)
for more details. for more details.
If [`param: pageFunction`] returns a [Promise], then `frame.$$eval` would wait for the promise to resolve and return If [`param: pageFunction`] returns a [Promise], then `frame.$$eval` would wait for the promise to resolve and return
@ -4650,7 +4650,7 @@ Contains the URL of the response.
# class: Selectors # class: Selectors
Selectors can be used to install custom selector engines. See [Working with selectors](#working-with-selectors) for more Selectors can be used to install custom selector engines. See [Working with selectors](./selectors.md#working-with-selectors) for more
information. information.
## async method: Selectors.register ## async method: Selectors.register

View file

@ -1,157 +0,0 @@
### EvaluationArgument
Playwright evaluation methods like [`method: Page.evaluate`] take a single optional argument. This argument can be a mix of [Serializable] values and [JSHandle] or [ElementHandle] instances. Handles are automatically converted to the value they represent.
See examples for various scenarios:
```js
// A primitive value.
await page.evaluate(num => num, 42);
// An array.
await page.evaluate(array => array.length, [1, 2, 3]);
// An object.
await page.evaluate(object => object.foo, { foo: 'bar' });
// A single handle.
const button = await page.$('button');
await page.evaluate(button => button.textContent, button);
// Alternative notation using elementHandle.evaluate.
await button.evaluate((button, from) => button.textContent.substring(from), 5);
// Object with multiple handles.
const button1 = await page.$('.button1');
const button2 = await page.$('.button2');
await page.evaluate(
o => o.button1.textContent + o.button2.textContent,
{ button1, button2 });
// Obejct destructuring works. Note that property names must match
// between the destructured object and the argument.
// Also note the required parenthesis.
await page.evaluate(
({ button1, button2 }) => button1.textContent + button2.textContent,
{ button1, button2 });
// Array works as well. Arbitrary names can be used for destructuring.
// Note the required parenthesis.
await page.evaluate(
([b1, b2]) => b1.textContent + b2.textContent,
[button1, button2]);
// Any non-cyclic mix of serializables and handles works.
await page.evaluate(
x => x.button1.textContent + x.list[0].textContent + String(x.foo),
{ button1, list: [button2], foo: null });
```
### Environment Variables
> **NOTE** [playwright-core](https://www.npmjs.com/package/playwright-core) **does not** respect environment variables.
Playwright looks for certain [environment variables](https://en.wikipedia.org/wiki/Environment_variable) to aid its operations.
If Playwright doesn't find them in the environment, a lowercased variant of these variables will be used from the [npm config](https://docs.npmjs.com/cli/config).
- `PLAYWRIGHT_DOWNLOAD_HOST` - overwrite URL prefix that is used to download browsers. Note: this includes protocol and might even include path prefix. By default, Playwright uses `https://storage.googleapis.com` to download Chromium and `https://playwright.azureedge.net` to download Webkit & Firefox. You can also use browser-specific download hosts that superceed the `PLAYWRIGHT_DOWNLOAD_HOST` variable:
- `PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST` - host to specify Chromium downloads
- `PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST` - host to specify Firefox downloads
- `PLAYWRIGHT_WEBKIT_DOWNLOAD_HOST` - host to specify Webkit downloads
- `PLAYWRIGHT_BROWSERS_PATH` - specify a shared directory that playwright will use to download browsers and to look for browsers when launching browser instances.
- `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` - set to non-empty value to skip browser downloads altogether.
```sh
# Linux/macOS
# Install browsers to the shared location.
$ PLAYWRIGHT_BROWSERS_PATH=$HOME/playwright-browsers npm install --save-dev playwright
# Use shared location to find browsers.
$ PLAYWRIGHT_BROWSERS_PATH=$HOME/playwright-browsers node playwright-script.js
# Windows
# Install browsers to the shared location.
$ set PLAYWRIGHT_BROWSERS_PATH=%USERPROFILE%\playwright-browsers
$ npm install --save-dev playwright
# Use shared location to find browsers.
$ set PLAYWRIGHT_BROWSERS_PATH=%USERPROFILE%\playwright-browsers
$ node playwright-script.js
```
### Working with selectors
Selector describes an element in the page. It can be used to obtain `ElementHandle` (see [`method: Page.$`] for example) or shortcut element operations to avoid intermediate handle (see [`method: Page.click`] for example).
Selector has the following format: `engine=body [>> engine=body]*`. Here `engine` is one of the supported [selector engines](./selectors.md) (e.g. `css` or `xpath`), and `body` is a selector body in the format of the particular engine. When multiple `engine=body` clauses are present (separated by `>>`), next one is queried relative to the previous one's result.
Playwright also supports the following CSS extensions:
* `:text("string")` - Matches elements that contain specific text node. Learn more about [text selector](./selectors.md#css-extension-text).
* `:visible` - Matches only visible elements. Learn more about [visible selector](./selectors.md#css-extension-visible).
* `:light(selector)` - Matches in the light DOM only as opposite to piercing open shadow roots. Learn more about [shadow piercing](./selectors.md#shadow-piercing).
<!--
* `:right-of(selector)`, `:left-of(selector)`, `:above(selector)`, `:below(selector)`, `:near(selector)`, `:within(selector)` - Match elements based on their relative position to another element. Learn more about [proximity selectors](./selectors.md#css-extension-proximity).
-->
For convenience, selectors in the wrong format are heuristically converted to the right format:
- selector starting with `//` or `..` is assumed to be `xpath=selector`;
- selector starting and ending with a quote (either `"` or `'`) is assumed to be `text=selector`;
- otherwise selector is assumed to be `css=selector`.
```js
// queries 'div' css selector
const handle = await page.$('css=div');
// queries '//html/body/div' xpath selector
const handle = await page.$('xpath=//html/body/div');
// queries '"foo"' text selector
const handle = await page.$('text="foo"');
// queries 'span' css selector inside the result of '//html/body/div' xpath selector
const handle = await page.$('xpath=//html/body/div >> css=span');
// converted to 'css=div'
const handle = await page.$('div');
// converted to 'xpath=//html/body/div'
const handle = await page.$('//html/body/div');
// converted to 'text="foo"'
const handle = await page.$('"foo"');
// queries '../span' xpath selector starting with the result of 'div' css selector
const handle = await page.$('div >> ../span');
// queries 'span' css selector inside the div handle
const handle = await divHandle.$('css=span');
```
### Working with Chrome Extensions
Playwright can be used for testing Chrome Extensions.
> **NOTE** Extensions in Chrome / Chromium currently only work in non-headless mode.
The following is code for getting a handle to the [background page](https://developer.chrome.com/extensions/background_pages) of an extension whose source is located in `./my-extension`:
```js
const { chromium } = require('playwright');
(async () => {
const pathToExtension = require('path').join(__dirname, 'my-extension');
const userDataDir = '/tmp/test-user-data-dir';
const browserContext = await chromium.launchPersistentContext(userDataDir,{
headless: false,
args: [
`--disable-extensions-except=${pathToExtension}`,
`--load-extension=${pathToExtension}`
]
});
const backgroundPage = browserContext.backgroundPages()[0];
// Test the background page as you would any other page.
await browserContext.close();
})();
```
> **NOTE** It is not yet possible to test extension popups or content scripts.

View file

@ -1,7 +0,0 @@
# Playwright API <!-- GEN:version -->Tip-Of-Tree<!-- GEN:stop-->
##### Table of Contents
<!-- GEN:toc-top-level -->
<!-- GEN:stop -->

View file

@ -45,7 +45,7 @@ Whether to bypass the [actionability](./actionability.md) checks. Defaults to `f
- `selector` <[string]> - `selector` <[string]>
A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See
[working with selectors](#working-with-selectors) for more details. [working with selectors](./selectors.md#working-with-selectors) for more details.
## input-position ## input-position
- `position` <[Object]> - `position` <[Object]>
@ -85,7 +85,7 @@ defaults to 1. See [UIEvent.detail].
## query-selector ## query-selector
- `selector` <[string]> - `selector` <[string]>
A selector to query for. See [working with selectors](#working-with-selectors) for more details. A selector to query for. See [working with selectors](./selectors.md#working-with-selectors) for more details.
## wait-for-selector-state ## wait-for-selector-state
- `state` <"attached"|"detached"|"visible"|"hidden"> - `state` <"attached"|"detached"|"visible"|"hidden">

View file

@ -1,14 +1,14 @@
# Assertions ---
id: assertions
title: "Assertions"
---
The Playwright API can be used to read element contents and properties for test assertions. These values are fetched from the browser page and asserted in The Playwright API can be used to read element contents and properties for test assertions. These values are fetched from the browser page and asserted in
Node.js. Node.js.
The examples in this guide use the built-in [`assert` module](https://nodejs.org/api/assert.html), but they can be used with any assertion library (like [Expect](https://www.npmjs.com/package/expect) or [Chai](https://www.npmjs.com/package/chai)). See [Test runners](test-runners.md) for more info. The examples in this guide use the built-in [`assert` module](https://nodejs.org/api/assert.html), but they can be used with any assertion library (like [Expect](https://www.npmjs.com/package/expect) or [Chai](https://www.npmjs.com/package/chai)). See [Test runners](test-runners.md) for more info.
<!-- GEN:toc-top-level --> <!-- TOC -->
<!-- GEN:stop -->
<br/>
## Common patterns ## Common patterns

View file

@ -1,4 +1,8 @@
# Authentication ---
id: auth
title: "Authentication"
---
Playwright can be used to automate scenarios that require authentication. Playwright can be used to automate scenarios that require authentication.
Tests written with Playwright execute in isolated clean-slate environments called Tests written with Playwright execute in isolated clean-slate environments called
@ -11,8 +15,7 @@ login in every context and speeds up test execution.
app UI). For [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication) app UI). For [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication)
use [`browser.newContext`](./network.md#http-authentication). use [`browser.newContext`](./network.md#http-authentication).
<!-- GEN:toc --> <!-- TOC -->
<!-- GEN:stop -->
## Automate logging in ## Automate logging in

View file

@ -1,10 +1,12 @@
# Continuous Integration ---
id: ci
title: "Continuous Integration"
---
Playwright tests can be executed in CI environments. We have created sample Playwright tests can be executed in CI environments. We have created sample
configurations for common CI providers. configurations for common CI providers.
<!-- GEN:toc --> <!-- TOC -->
<!-- GEN:stop -->
## Introduction ## Introduction

View file

@ -1,9 +1,11 @@
# Playwright CLI ---
id: cli
title: "Command Line Interface"
---
Playwright comes with the command line tools that run via `npx` or as a part of the `npm` scripts. Playwright comes with the command line tools that run via `npx` or as a part of the `npm` scripts.
<!-- GEN:toc --> <!-- TOC -->
<!-- GEN:stop -->
## Usage ## Usage

View file

@ -1,4 +1,7 @@
# Core concepts ---
id: core-concepts
title: "Core concepts"
---
Playwright provides a set of APIs to automate Chromium, Firefox and WebKit Playwright provides a set of APIs to automate Chromium, Firefox and WebKit
browsers. By using the Playwright API, you can write JavaScript code to create browsers. By using the Playwright API, you can write JavaScript code to create
@ -8,8 +11,7 @@ Along with a test runner Playwright can be used to automate user interactions to
validate and test web applications. The Playwright API enables this through validate and test web applications. The Playwright API enables this through
the following primitives. the following primitives.
<!-- GEN:toc-top-level --> <!-- TOC -->
<!-- GEN:stop -->
<br/> <br/>
@ -245,10 +247,53 @@ const status = await page.evaluate(async () => {
}); });
``` ```
### Evaluation ## Evaluation Argument
Playwright evaluation methods like [`method: Page.evaluate`] take a single optional argument. This argument can be a mix of [Serializable] values and [JSHandle] or [ElementHandle] instances. Handles are automatically converted to the value they represent.
```js
// A primitive value.
await page.evaluate(num => num, 42);
// An array.
await page.evaluate(array => array.length, [1, 2, 3]);
// An object.
await page.evaluate(object => object.foo, { foo: 'bar' });
// A single handle.
const button = await page.$('button');
await page.evaluate(button => button.textContent, button);
// Alternative notation using elementHandle.evaluate.
await button.evaluate((button, from) => button.textContent.substring(from), 5);
// Object with multiple handles.
const button1 = await page.$('.button1');
const button2 = await page.$('.button2');
await page.evaluate(
o => o.button1.textContent + o.button2.textContent,
{ button1, button2 });
// Object destructuring works. Note that property names must match
// between the destructured object and the argument.
// Also note the required parenthesis.
await page.evaluate(
({ button1, button2 }) => button1.textContent + button2.textContent,
{ button1, button2 });
// Array works as well. Arbitrary names can be used for destructuring.
// Note the required parenthesis.
await page.evaluate(
([b1, b2]) => b1.textContent + b2.textContent,
[button1, button2]);
// Any non-cyclic mix of serializables and handles works.
await page.evaluate(
x => x.button1.textContent + x.list[0].textContent + String(x.foo),
{ button1, list: [button2], foo: null });
```
Functions passed inside [`method: Page.evaluate`] can accept parameters. These parameters are
serialized and sent into your web page over the wire. You can pass primitive types, JSON-alike objects and remote object handles received from the page.
Right: Right:

View file

@ -1,11 +1,13 @@
# Debugging tools ---
id: debug
title: "Debugging tools"
---
Playwright scripts work with existing debugging tools, like Node.js debuggers Playwright scripts work with existing debugging tools, like Node.js debuggers
and browser developer tools. Playwright also introduces new debugging features and browser developer tools. Playwright also introduces new debugging features
for browser automation. for browser automation.
<!-- GEN:toc --> <!-- TOC -->
<!-- GEN:stop -->
## Run in headful mode ## Run in headful mode

View file

@ -1,4 +1,7 @@
# Device and environment emulation ---
id: emulation
title: "Device and environment emulation"
---
Playwright allows overriding various parameters of the device where the browser is running: Playwright allows overriding various parameters of the device where the browser is running:
- viewport size, device scale factor, touch support - viewport size, device scale factor, touch support
@ -8,8 +11,7 @@ Playwright allows overriding various parameters of the device where the browser
Most of these parameters are configured during the browser context construction, but some of them such as viewport size can be changed for individual pages. Most of these parameters are configured during the browser context construction, but some of them such as viewport size can be changed for individual pages.
<!-- GEN:toc-top-level --> <!-- TOC -->
<!-- GEN:stop -->
<br/> <br/>

View file

@ -1,7 +1,9 @@
# Extensibility ---
id: extensibility
title: "Extensibility"
---
<!-- GEN:toc-top-level --> <!-- TOC -->
<!-- GEN:stop -->
## Custom selector engines ## Custom selector engines

View file

@ -1,9 +1,9 @@
# Input ---
id: input
title: "Input"
---
<!-- GEN:toc-top-level --> <!-- TOC -->
<!-- GEN:stop -->
<br/>
## Text input ## Text input

View file

@ -1,9 +1,9 @@
# Advanced installation ---
id: installation
title: "Advanced installation"
---
<!-- GEN:toc --> <!-- TOC -->
<!-- GEN:stop -->
<br>
## Managing browser binaries ## Managing browser binaries

View file

@ -1,7 +1,9 @@
# Getting Started ---
id: intro
title: "Getting Started"
---
<!-- GEN:toc-top-level --> <!-- TOC -->
<!-- GEN:stop -->
## Installation ## Installation

View file

@ -1,9 +1,11 @@
# Supported languages ---
id: languages
title: "Supported languages"
---
The Playwright API is available in multiple languages. The Playwright API is available in multiple languages.
<!-- GEN:toc --> <!-- TOC -->
<!-- GEN:stop -->
## JavaScript and TypeScript ## JavaScript and TypeScript

View file

@ -3,7 +3,7 @@
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -1,4 +1,9 @@
# Experimental support for Chrome for Android ---
id: mobile
title: "Experimental support for Chrome for Android"
---
<!-- TOC -->
You can try Playwright against Chrome for Android today. This support is experimental. Support for devices is tracked in the issue [#1122](https://github.com/microsoft/playwright/issues/1122). You can try Playwright against Chrome for Android today. This support is experimental. Support for devices is tracked in the issue [#1122](https://github.com/microsoft/playwright/issues/1122).

View file

@ -1,10 +1,12 @@
# Multi-page scenarios ---
id: multi-pages
title: "Multi-page scenarios"
---
Playwright can automate scenarios that span multiple browser contexts or multiple Playwright can automate scenarios that span multiple browser contexts or multiple
tabs in a browser window. tabs in a browser window.
<!-- GEN:toc-top-level --> <!-- TOC -->
<!-- GEN:stop -->
## Multiple contexts ## Multiple contexts

View file

@ -1,9 +1,11 @@
# Navigations ---
id: navigations
title: "Navigations"
---
Playwright can navigate to URLs and handle navigations caused by page interactions. This guide covers common scenarios to wait for page navigations and loading to complete. Playwright can navigate to URLs and handle navigations caused by page interactions. This guide covers common scenarios to wait for page navigations and loading to complete.
<!-- GEN:toc-top-level --> <!-- TOC -->
<!-- GEN:stop -->
## Navigation lifecycle ## Navigation lifecycle
Playwright splits the process of showing a new document in a page into **navigation** and **loading**. Playwright splits the process of showing a new document in a page into **navigation** and **loading**.

View file

@ -1,11 +1,13 @@
# Network ---
id: network
title: "Network"
---
Playwright provides APIs to **monitor** and **modify** network traffic, both HTTP and HTTPS. Playwright provides APIs to **monitor** and **modify** network traffic, both HTTP and HTTPS.
Any requests that page does, including [XHRs](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) and Any requests that page does, including [XHRs](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) and
[fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) requests, can be tracked, modified and handled. [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) requests, can be tracked, modified and handled.
<!-- GEN:toc-top-level --> <!-- TOC -->
<!-- GEN:stop -->
<br/> <br/>

View file

@ -1,9 +1,12 @@
# Page Object Models ---
id: pom
title: "Page Object Models"
---
Large test suites can be structured to optimize ease of authoring and maintenance. Large test suites can be structured to optimize ease of authoring and maintenance.
Page object models are one such approach to structure your test suite. Page object models are one such approach to structure your test suite.
<!-- GEN:toc-top-level --> <!-- TOC -->
<!-- GEN:stop -->
## Introduction ## Introduction
A page object represents a part of your web application. An e-commerce web A page object represents a part of your web application. An e-commerce web

View file

@ -1,9 +1,85 @@
# Element selectors ---
id: selectors
title: "Element selectors"
---
Selectors query elements on the web page for interactions, like [`method: Page.click`], and to obtain `ElementHandle` through [`method: Page.$`]. Built-in selectors auto-pierce [shadow DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM). Selectors query elements on the web page for interactions, like [`method: Page.click`], and to obtain `ElementHandle` through [`method: Page.$`]. Built-in selectors auto-pierce [shadow DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM).
<!-- GEN:toc-top-level --> <!-- TOC -->
<!-- GEN:stop -->
## Working with selectors
Selector describes an element in the page. It can be used to obtain `ElementHandle` (see [`method: Page.$`] for example) or shortcut element operations to avoid intermediate handle (see [`method: Page.click`] for example).
Selector has the following format: `engine=body [>> engine=body]*`. Here `engine` is one of the supported [selector engines](./selectors.md) (e.g. `css` or `xpath`), and `body` is a selector body in the format of the particular engine. When multiple `engine=body` clauses are present (separated by `>>`), next one is queried relative to the previous one's result.
Playwright also supports the following CSS extensions:
* `:text("string")` - Matches elements that contain specific text node. Learn more about [text selector](./selectors.md#css-extension-text).
* `:visible` - Matches only visible elements. Learn more about [visible selector](./selectors.md#css-extension-visible).
* `:light(selector)` - Matches in the light DOM only as opposite to piercing open shadow roots. Learn more about [shadow piercing](./selectors.md#shadow-piercing).
<!--
* `:right-of(selector)`, `:left-of(selector)`, `:above(selector)`, `:below(selector)`, `:near(selector)`, `:within(selector)` - Match elements based on their relative position to another element. Learn more about [proximity selectors](./selectors.md#css-extension-proximity).
-->
For convenience, selectors in the wrong format are heuristically converted to the right format:
- selector starting with `//` or `..` is assumed to be `xpath=selector`;
- selector starting and ending with a quote (either `"` or `'`) is assumed to be `text=selector`;
- otherwise selector is assumed to be `css=selector`.
```js
// queries 'div' css selector
const handle = await page.$('css=div');
// queries '//html/body/div' xpath selector
const handle = await page.$('xpath=//html/body/div');
// queries '"foo"' text selector
const handle = await page.$('text="foo"');
// queries 'span' css selector inside the result of '//html/body/div' xpath selector
const handle = await page.$('xpath=//html/body/div >> css=span');
// converted to 'css=div'
const handle = await page.$('div');
// converted to 'xpath=//html/body/div'
const handle = await page.$('//html/body/div');
// converted to 'text="foo"'
const handle = await page.$('"foo"');
// queries '../span' xpath selector starting with the result of 'div' css selector
const handle = await page.$('div >> ../span');
// queries 'span' css selector inside the div handle
const handle = await divHandle.$('css=span');
```
### Working with Chrome Extensions
Playwright can be used for testing Chrome Extensions.
> **NOTE** Extensions in Chrome / Chromium currently only work in non-headless mode.
The following is code for getting a handle to the [background page](https://developer.chrome.com/extensions/background_pages) of an extension whose source is located in `./my-extension`:
```js
const { chromium } = require('playwright');
(async () => {
const pathToExtension = require('path').join(__dirname, 'my-extension');
const userDataDir = '/tmp/test-user-data-dir';
const browserContext = await chromium.launchPersistentContext(userDataDir,{
headless: false,
args: [
`--disable-extensions-except=${pathToExtension}`,
`--load-extension=${pathToExtension}`
]
});
const backgroundPage = browserContext.backgroundPages()[0];
// Test the background page as you would any other page.
await browserContext.close();
})();
```
## Syntax ## Syntax
Selectors are defined by selector engine name and selector body, `engine=body`. Selectors are defined by selector engine name and selector body, `engine=body`.

View file

@ -1,4 +1,7 @@
# Community Showcase ---
id: showcase
title: "Community Showcase"
---
## Users ## Users

View file

@ -1,13 +1,11 @@
# Test Runners ---
id: test-runners
title: "Test Runners"
---
With a few lines of code, you can hook up Playwright to your favorite JavaScript test runner. With a few lines of code, you can hook up Playwright to your favorite JavaScript test runner.
<!-- GEN:toc --> <!-- TOC -->
<!-- GEN:stop -->
<br>
<br>
## Jest / Jasmine ## Jest / Jasmine

View file

@ -1,7 +1,9 @@
# Troubleshooting ---
id: troubleshooting
title: "Troubleshooting"
---
<!-- GEN:toc --> <!-- TOC -->
<!-- GEN:stop -->
## Browser dependencies ## Browser dependencies

View file

@ -1,9 +1,9 @@
# Verification ---
id: verification
title: "Verification"
---
<!-- GEN:toc-top-level --> <!-- TOC -->
<!-- GEN:stop -->
<br/>
## Videos ## Videos

View file

@ -1,9 +1,11 @@
# Why Playwright? ---
id: why-playwright
title: "Why Playwright?"
---
Playwright enables fast, reliable and capable automation across all modern browsers. This guide covers those key differentiators to help you decide on the right tool for your automated tests. Playwright enables fast, reliable and capable automation across all modern browsers. This guide covers those key differentiators to help you decide on the right tool for your automated tests.
<!-- GEN:toc-top-level --> <!-- TOC -->
<!-- GEN:stop -->
## Support for all browsers ## Support for all browsers
* **Test on Chromium, Firefox and WebKit**. Playwright has full API coverage for all modern browsers, including Google Chrome and Microsoft Edge (with [Chromium](https://www.chromium.org/)), Apple Safari (with [WebKit](https://webkit.org/)) and Mozilla Firefox. * **Test on Chromium, Firefox and WebKit**. Playwright has full API coverage for all modern browsers, including Google Chrome and Microsoft Edge (with [Chromium](https://www.chromium.org/)), Apple Safari (with [WebKit](https://webkit.org/)) and Mozilla Firefox.

View file

@ -1,9 +1,11 @@
# Documentation ---
id: README
title: "Documentation"
---
### Capabilities ### Capabilities
Playwright is a library to automate [Chromium](https://www.chromium.org/Home), [Firefox](https://www.mozilla.org/en-US/firefox/new/) and [WebKit](https://webkit.org/) with a single API. Playwright is built to enable cross-browser web automation that is **ever-green**, **capable**, **reliable** and **fast**. Playwright is a library to automate [Chromium](https://www.chromium.org/Home), [Firefox](https://www.mozilla.org/en-US/firefox/new/) and [WebKit](https://webkit.org/) with a single API. Playwright is built to enable cross-browser web automation that is **ever-green**, **capable**, **reliable** and **fast**.
* Ever-green browser engines * Ever-green browser engines
* Headless execution * Headless execution
* Scenarios that span multiple pages, domains and iframes * Scenarios that span multiple pages, domains and iframes
@ -16,36 +18,91 @@ Playwright is a library to automate [Chromium](https://www.chromium.org/Home), [
* Upload and download files * Upload and download files
### Table of contents ### Table of contents
1. Introduction 1. Introduction
- [Why Playwright?](./why-playwright.md) - [Why Playwright?](./why-playwright.md)
- [Get started](./intro.md) - [Get started](./intro.md)
- [Core concepts](./core-concepts.md) - [Core concepts](./core-concepts.md)
- [Debugging](./debug.md) - [Debugging](./debug.md)
- [Supported languages](./languages.md) - [Supported languages](./languages.md)
- [Using Playwright CLI](./cli.md)
1. Guides 1. Guides
- [Selectors](./selectors.md) - [Selectors](./selectors.md)
- [Input](./input.md) - [Input](./input.md)
- [Emulation](./emulation.md) - [Emulation](./emulation.md)
- [Network](./network.md) - [Network](./network.md)
- [Assertions](./assertions.md) - [Assertions](./assertions.md)
- [Verification](./verification.md) - [Verification](./verification.md)
- [Navigations](./navigations.md) - [Navigations](./navigations.md)
- [Multi-page scenarios](./multi-pages.md) - [Multi-page scenarios](./multi-pages.md)
1. Tutorials 1. Tutorials
- [Authentication](./auth.md) - [Authentication](./auth.md)
- [Page object models](./pom.md) - [Page object models](./pom.md)
1. Integrations 1. Integrations
- [Test runners](./test-runners.md) - [Test runners](./test-runners.md)
- [Docker](./docker/README.md) - [Docker](./docker/README.md)
- [Continuous integration](./ci.md) - [Continuous integration](./ci.md)
1. Reference 1. Reference
- [API Reference](./api.md) - [API Reference](./api.md)
- [Actionability](./actionability.md) - [Actionability](./actionability.md)
- [Advanced installation](./installation.md) - [Advanced installation](./installation.md)
- [Extensibility](./extensibility.md) - [Extensibility](./extensibility.md)
1. Get help 1. Get help
- [Slack community](https://join.slack.com/t/playwright/shared_invite/enQtOTEyMTUxMzgxMjIwLThjMDUxZmIyNTRiMTJjNjIyMzdmZDA3MTQxZWUwZTFjZjQwNGYxZGM5MzRmNzZlMWI5ZWUyOTkzMjE5Njg1NDg) - [Slack community](https://join.slack.com/t/playwright/shared_invite/enQtOTEyMTUxMzgxMjIwLThjMDUxZmIyNTRiMTJjNjIyMzdmZDA3MTQxZWUwZTFjZjQwNGYxZGM5MzRmNzZlMWI5ZWUyOTkzMjE5Njg1NDg)
- [Stack Overflow](https://stackoverflow.com/tags/playwright) - [Stack Overflow](https://stackoverflow.com/tags/playwright)
- [GitHub](https://github.com/microsoft/playwright/issues) - [GitHub](https://github.com/microsoft/playwright/issues)
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

View file

@ -1,18 +1,13 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: actionability
title: "Actionability"
---
# Actionability Playwright does a range of actionability checks on the elements before performing certain actions. These checks ensure that action behaves as expected, for example Playwright does not click on a disabled button.
Playwright does a range of actionability checks on the elements before Playwright waits until all the relevant actionability checks pass before performing an action. This means that action will fail with `TimeoutError` if checks do not pass within the specified `timeout`.
performing certain actions. These checks ensure that action behaves as expected,
for example Playwright does not click on a disabled button.
Playwright waits until all the relevant actionability checks pass before Some actions like `page.click()` support `{force: true}` option that disable non-essential actionability checks, for example passing `force` to `click()` method will not check that the target element actually receives click events.
performing an action. This means that action will fail with `TimeoutError` if
checks do not pass within the specified `timeout`.
Some actions like `page.click()` support `{force: true}` option that disable
non-essential actionability checks, for example passing `force` to `click()`
method will not check that the target element actually receives click events.
| Actions | Performed checks | | Actions | Performed checks |
| ------ | ------- | | ------ | ------- |
@ -26,19 +21,15 @@ method will not check that the target element actually receives click events.
### Visible ### Visible
Element is considered visible when it has non-empty bounding box and does not Element is considered visible when it has non-empty bounding box and does not have `visibility:hidden` computed style. Note that elements of zero size or with `display:none` are not considered visible.
have `visibility:hidden` computed style. Note that elements of zero size or with
`display:none` are not considered visible.
### Stable ### Stable
Element is considered stable when it has maintained the same bounding box for at Element is considered stable when it has maintained the same bounding box for at least two consecutive animation frames.
least two consecutive animation frames.
### Enabled ### Enabled
Element is considered enabled when it is not a `<button>`, `<select>` or Element is considered enabled when it is not a `<button>`, `<select>` or `<input>` with a `disabled` property set.
`<input>` with a `disabled` property set.
### Editable ### Editable
@ -46,30 +37,19 @@ Element is considered editable when it does not have `readonly` property set.
### Receiving events ### Receiving events
Element is considered receiving pointer events when it is the hit target of the Element is considered receiving pointer events when it is the hit target of the pointer event at the action point. For example, when clicking at the point `(10;10)`, Playwright checks whether some other element (usually an overlay) will instead capture the click at `(10;10)`.
pointer event at the action point. For example, when clicking at the point
`(10;10)`, Playwright checks whether some other element (usually an overlay)
will instead capture the click at `(10;10)`.
### Attached ### Attached
Element is considered attached when it is Element is considered attached when it is [connected](https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected) to a Document or a ShadowRoot.
[connected](https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected)
to a Document or a ShadowRoot.
Attached check differs between selector-based and handle-based actions, like Attached check differs between selector-based and handle-based actions, like `page.click(selector, options)` as opposite to `elementHandle.click(options)`:
`page.click(selector, options)` as opposite to `elementHandle.click(options)`: - For selector-based actions, Playwright first waits for an element matching `selector` to be attached to the DOM, and then checks that element is still attached before performing the action. If element was detached, the action is retried from the start.
- For selector-based actions, Playwright first waits for an element matching
`selector` to be attached to the DOM, and then checks that element is still
attached before performing the action. If element was detached, the action
is retried from the start.
- For handle-based actions, Playwright throws if the element is not attached. - For handle-based actions, Playwright throws if the element is not attached.
For example, consider a scenario where Playwright will click `Sign Up` button For example, consider a scenario where Playwright will click `Sign Up` button regardless of when the `page.click()` call was made:
regardless of when the `page.click()` call was made:
- page is checking that user name is unique and `Sign Up` button is disabled; - page is checking that user name is unique and `Sign Up` button is disabled;
- after checking with the server, the disabled `Sign Up` button is replaced - after checking with the server, the disabled `Sign Up` button is replaced with another one that is now enabled.
with another one that is now enabled.
[Visible]: #visible "Visible" [Visible]: #visible "Visible"
[Stable]: #stable "Stable" [Stable]: #stable "Stable"
@ -77,44 +57,44 @@ regardless of when the `page.click()` call was made:
[Editable]: #editable "Editable" [Editable]: #editable "Editable"
[Receiving Events]: #receiving-events "Receiving Events" [Receiving Events]: #receiving-events "Receiving Events"
[Attached]: #attached "Attached" [Attached]: #attached "Attached"
[Playwright]: api.md#class-playwright "Playwright" [Playwright]: api/class-playwright.md "Playwright"
[Browser]: api.md#class-browser "Browser" [Browser]: api/class-browser.md "Browser"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api.md#class-page "Page" [Page]: api/class-page.md "Page"
[Frame]: api.md#class-frame "Frame" [Frame]: api/class-frame.md "Frame"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api.md#class-dialog "Dialog" [Dialog]: api/class-dialog.md "Dialog"
[Download]: api.md#class-download "Download" [Download]: api/class-download.md "Download"
[Video]: api.md#class-video "Video" [Video]: api/class-video.md "Video"
[FileChooser]: api.md#class-filechooser "FileChooser" [FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api.md#class-keyboard "Keyboard" [Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api.md#class-mouse "Mouse" [Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api.md#class-request "Request" [Request]: api/class-request.md "Request"
[Response]: api.md#class-response "Response" [Response]: api/class-response.md "Response"
[Selectors]: api.md#class-selectors "Selectors" [Selectors]: api/class-selectors.md "Selectors"
[Route]: api.md#class-route "Route" [Route]: api/class-route.md "Route"
[WebSocket]: api.md#class-websocket "WebSocket" [WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api.md#class-accessibility "Accessibility" [Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api.md#class-worker "Worker" [Worker]: api/class-worker.md "Worker"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api.md#class-browsertype "BrowserType" [BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api.md#class-logger "Logger" [Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api.md#class-cdpsession "CDPSession" [CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

File diff suppressed because it is too large Load diff

View file

@ -1,30 +1,19 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: assertions
title: "Assertions"
---
# Assertions The Playwright API can be used to read element contents and properties for test assertions. These values are fetched from the browser page and asserted in Node.js.
The Playwright API can be used to read element contents and properties for test The examples in this guide use the built-in [`assert` module](https://nodejs.org/api/assert.html), but they can be used with any assertion library (like [Expect](https://www.npmjs.com/package/expect) or [Chai](https://www.npmjs.com/package/chai)). See [Test runners](test-runners.md) for more info.
assertions. These values are fetched from the browser page and asserted in
Node.js.
The examples in this guide use the built-in
[`assert` module](https://nodejs.org/api/assert.html), but they can be used with
any assertion library (like [Expect](https://www.npmjs.com/package/expect) or
[Chai](https://www.npmjs.com/package/chai)). See [Test runners](test-runners.md)
for more info.
<!-- GEN:toc-top-level -->
- [Common patterns](#common-patterns) - [Common patterns](#common-patterns)
- [Element Handles](#element-handles) - [Element Handles](#element-handles)
- [Custom assertions](#custom-assertions) - [Custom assertions](#custom-assertions)
<!-- GEN:stop -->
<br/>
## Common patterns ## Common patterns
Playwright provides convenience APIs for common assertion tasks, like finding Playwright provides convenience APIs for common assertion tasks, like finding the text content of an element. These APIs require a [selector](./selectors.md) to locate the element.
the text content of an element. These APIs require a [selector](./selectors.md)
to locate the element.
```js ```js
// Assert text content // Assert text content
@ -45,28 +34,22 @@ assert(checked);
``` ```
#### API reference #### API reference
- [page.textContent(selector[, options])](./api.md#pagetextcontentselector-options) - [page.textContent(selector[, options])](api/class-page.md#pagetextcontentselector-options)
- [page.innerText(selector[, options])](./api.md#pageinnertextselector-options) - [page.innerText(selector[, options])](api/class-page.md#pageinnertextselector-options)
- [page.innerHTML(selector[, options])](./api.md#pageinnerhtmlselector-options) - [page.innerHTML(selector[, options])](api/class-page.md#pageinnerhtmlselector-options)
- [page.getAttribute(selector, name[, options])](./api.md#pagegetattributeselector-name-options) - [page.getAttribute(selector, name[, options])](api/class-page.md#pagegetattributeselector-name-options)
- [frame.textContent(selector[, options])](./api.md#frametextcontentselector-options) - [frame.textContent(selector[, options])](api/class-frame.md#frametextcontentselector-options)
- [frame.innerText(selector[, options])](./api.md#frameinnertextselector-options) - [frame.innerText(selector[, options])](api/class-frame.md#frameinnertextselector-options)
- [frame.innerHTML(selector[, options])](./api.md#frameinnerhtmlselector-options) - [frame.innerHTML(selector[, options])](api/class-frame.md#frameinnerhtmlselector-options)
- [frame.getAttribute(selector, name[, options])](./api.md#framegetattributeselector-name-options) - [frame.getAttribute(selector, name[, options])](api/class-frame.md#framegetattributeselector-name-options)
<br/> <br/>
## Element Handles ## Element Handles
[ElementHandle] objects represent in-page DOM elements. They can be used to [ElementHandle] objects represent in-page DOM elements. They can be used to assert for multiple properties of the element.
assert for multiple properties of the element.
It is recommended to fetch the `ElementHandle` object with It is recommended to fetch the `ElementHandle` object with [page.waitForSelector(selector[, options])](api/class-page.md#pagewaitforselectorselector-options) or [frame.waitForSelector(selector[, options])](api/class-frame.md#framewaitforselectorselector-options). These APIs wait for the element to be visible and then return an `ElementHandle`.
[page.waitForSelector(selector[, options])](./api.md#pagewaitforselectorselector-options)
or
[frame.waitForSelector(selector[, options])](./api.md#framewaitforselectorselector-options).
These APIs wait for the element to be visible and then return an
`ElementHandle`.
```js ```js
// Get the element handle // Get the element handle
@ -82,24 +65,19 @@ assert(classNames.includes('highlighted'));
``` ```
#### API reference #### API reference
- [elementHandle.textContent()](./api.md#elementhandletextcontent) - [elementHandle.textContent()](api/class-elementhandle.md#elementhandletextcontent)
- [elementHandle.innerText()](./api.md#elementhandleinnertext) - [elementHandle.innerText()](api/class-elementhandle.md#elementhandleinnertext)
- [elementHandle.innerHTML()](./api.md#elementhandleinnerhtml) - [elementHandle.innerHTML()](api/class-elementhandle.md#elementhandleinnerhtml)
- [elementHandle.getAttribute(name)](./api.md#elementhandlegetattributename) - [elementHandle.getAttribute(name)](api/class-elementhandle.md#elementhandlegetattributename)
- [elementHandle.boundingBox()](./api.md#elementhandleboundingbox) - [elementHandle.boundingBox()](api/class-elementhandle.md#elementhandleboundingbox)
<br/> <br/>
## Custom assertions ## Custom assertions
With Playwright, you can also write custom JavaScript to run in the context of With Playwright, you can also write custom JavaScript to run in the context of the browser. This is useful in situations where you want to assert for values that are not covered by the convenience APIs above.
the browser. This is useful in situations where you want to assert for values
that are not covered by the convenience APIs above.
The following APIs do not auto-wait for the element. It is recommended to use The following APIs do not auto-wait for the element. It is recommended to use [page.waitForSelector(selector[, options])](api/class-page.md#pagewaitforselectorselector-options) or [frame.waitForSelector(selector[, options])](api/class-frame.md#framewaitforselectorselector-options).
[page.waitForSelector(selector[, options])](./api.md#pagewaitforselectorselector-options)
or
[frame.waitForSelector(selector[, options])](./api.md#framewaitforselectorselector-options).
```js ```js
// Assert local storage value // Assert local storage value
@ -121,53 +99,53 @@ assert(length === 3);
``` ```
#### API reference #### API reference
- [page.evaluate(pageFunction[, arg])](./api.md#pageevaluatepagefunction-arg) - [page.evaluate(pageFunction[, arg])](api/class-page.md#pageevaluatepagefunction-arg)
- [page.$eval(selector, pageFunction[, arg])](./api.md#pageevalselector-pagefunction-arg) - [page.$eval(selector, pageFunction[, arg])](api/class-page.md#pageevalselector-pagefunction-arg)
- [page.$$eval(selector, pageFunction[, arg])](./api.md#pageevalselector-pagefunction-arg-1) - [page.$$eval(selector, pageFunction[, arg])](api/class-page.md#pageevalselector-pagefunction-arg-1)
- [frame.evaluate(pageFunction[, arg])](./api.md#frameevaluatepagefunction-arg) - [frame.evaluate(pageFunction[, arg])](api/class-frame.md#frameevaluatepagefunction-arg)
- [frame.$eval(selector, pageFunction[, arg])](./api.md#frameevalselector-pagefunction-arg) - [frame.$eval(selector, pageFunction[, arg])](api/class-frame.md#frameevalselector-pagefunction-arg)
- [frame.$$eval(selector, pageFunction[, arg])](./api.md#frameevalselector-pagefunction-arg-1) - [frame.$$eval(selector, pageFunction[, arg])](api/class-frame.md#frameevalselector-pagefunction-arg-1)
- [elementHandle.$eval(selector, pageFunction[, arg])](./api.md#elementhandleevalselector-pagefunction-arg) - [elementHandle.$eval(selector, pageFunction[, arg])](api/class-elementhandle.md#elementhandleevalselector-pagefunction-arg)
- [elementHandle.$$eval(selector, pageFunction[, arg])](./api.md#elementhandleevalselector-pagefunction-arg-1) - [elementHandle.$$eval(selector, pageFunction[, arg])](api/class-elementhandle.md#elementhandleevalselector-pagefunction-arg-1)
- [EvaluationArgument] - [EvaluationArgument]
[Playwright]: api.md#class-playwright "Playwright" [Playwright]: api/class-playwright.md "Playwright"
[Browser]: api.md#class-browser "Browser" [Browser]: api/class-browser.md "Browser"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api.md#class-page "Page" [Page]: api/class-page.md "Page"
[Frame]: api.md#class-frame "Frame" [Frame]: api/class-frame.md "Frame"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api.md#class-dialog "Dialog" [Dialog]: api/class-dialog.md "Dialog"
[Download]: api.md#class-download "Download" [Download]: api/class-download.md "Download"
[Video]: api.md#class-video "Video" [Video]: api/class-video.md "Video"
[FileChooser]: api.md#class-filechooser "FileChooser" [FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api.md#class-keyboard "Keyboard" [Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api.md#class-mouse "Mouse" [Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api.md#class-request "Request" [Request]: api/class-request.md "Request"
[Response]: api.md#class-response "Response" [Response]: api/class-response.md "Response"
[Selectors]: api.md#class-selectors "Selectors" [Selectors]: api/class-selectors.md "Selectors"
[Route]: api.md#class-route "Route" [Route]: api/class-route.md "Route"
[WebSocket]: api.md#class-websocket "WebSocket" [WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api.md#class-accessibility "Accessibility" [Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api.md#class-worker "Worker" [Worker]: api/class-worker.md "Worker"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api.md#class-browsertype "BrowserType" [BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api.md#class-logger "Logger" [Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api.md#class-cdpsession "CDPSession" [CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -1,42 +1,23 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: auth
# Authentication title: "Authentication"
---
Playwright can be used to automate scenarios that require authentication. Playwright can be used to automate scenarios that require authentication.
Tests written with Playwright execute in isolated clean-slate environments Tests written with Playwright execute in isolated clean-slate environments called [browser contexts](./core-concepts.md#browser-contexts). This isolation model improves reproducibility and prevents cascading test failures. New browser contexts can load existing authentication state. This eliminates the need to login in every context and speeds up test execution.
called [browser contexts](./core-concepts.md#browser-contexts). This isolation
model improves reproducibility and prevents cascading test failures. New browser
contexts can load existing authentication state. This eliminates the need to
login in every context and speeds up test execution.
> Note: This guide covers cookie/token-based authentication (logging in via the > Note: This guide covers cookie/token-based authentication (logging in via the app UI). For [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication) use [`browser.newContext`](./network.md#http-authentication).
app UI). For
[HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication)
use [`browser.newContext`](./network.md#http-authentication).
<!-- GEN:toc -->
- [Automate logging in](#automate-logging-in) - [Automate logging in](#automate-logging-in)
- [Reuse authentication state](#reuse-authentication-state) - [Reuse authentication state](#reuse-authentication-state)
* [Cookies](#cookies)
* [Local storage](#local-storage)
* [Session storage](#session-storage)
* [Lifecycle](#lifecycle)
* [Example](#example)
* [API reference](#api-reference)
- [Multi-factor authentication](#multi-factor-authentication) - [Multi-factor authentication](#multi-factor-authentication)
* [Persistent authentication](#persistent-authentication)
* [Lifecycle](#lifecycle-1)
* [API reference](#api-reference-1)
<!-- GEN:stop -->
## Automate logging in ## Automate logging in
The Playwright API can automate interaction with a login form. See The Playwright API can automate interaction with a login form. See [Input guide](./input.md) for more details.
[Input guide](./input.md) for more details.
The following example automates login on GitHub. Once these steps are executed, The following example automates login on GitHub. Once these steps are executed, the browser context will be authenticated.
the browser context will be authenticated.
```js ```js
const page = await context.newPage(); const page = await context.newPage();
@ -50,25 +31,15 @@ await page.click('text=Submit');
// Verify app is logged in // Verify app is logged in
``` ```
These steps can be executed for every browser context. However, redoing login These steps can be executed for every browser context. However, redoing login for every test can slow down test execution. To prevent that, we will reuse existing authentication state in new browser contexts.
for every test can slow down test execution. To prevent that, we will reuse
existing authentication state in new browser contexts.
## Reuse authentication state ## Reuse authentication state
Web apps use cookie-based or token-based authentication, where authenticated Web apps use cookie-based or token-based authentication, where authenticated state is stored as [cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies) or in [local storage](https://developer.mozilla.org/en-US/docs/Web/API/Storage). The Playwright API can be used to retrieve this state from authenticated contexts and then load it into new contexts.
state is stored as
[cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies) or in
[local storage](https://developer.mozilla.org/en-US/docs/Web/API/Storage). The
Playwright API can be used to retrieve this state from authenticated contexts
and then load it into new contexts.
Cookies and local storage state can be used across different browsers. They Cookies and local storage state can be used across different browsers. They depend on your application's authentication model: some apps might require both cookies and local storage.
depend on your application's authentication model: some apps might require both
cookies and local storage.
The following code snippets retrieve state from an authenticated page/context The following code snippets retrieve state from an authenticated page/context and load them into a new context.
and load them into a new context.
### Cookies ### Cookies
@ -84,9 +55,7 @@ await context.addCookies(deserializedCookies);
### Local storage ### Local storage
Local storage Local storage ([`window.localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)) is specific to a particular domain.
([`window.localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage))
is specific to a particular domain.
```js ```js
// Get local storage and store as env variable // Get local storage and store as env variable
@ -107,9 +76,7 @@ await context.addInitScript(storage => {
### Session storage ### Session storage
Session storage Session storage ([`window.sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage)) is specific to a particular domain.
([`window.sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage))
is specific to a particular domain.
```js ```js
// Get session storage and store as env variable // Get session storage and store as env variable
@ -130,45 +97,34 @@ await context.addInitScript(storage => {
### Lifecycle ### Lifecycle
Logging in via the UI and then reusing authentication state can be combined to Logging in via the UI and then reusing authentication state can be combined to implement **login once and run multiple scenarios**. The lifecycle looks like:
implement **login once and run multiple scenarios**. The lifecycle looks like:
1. Run tests (for example, with `npm run test`). 1. Run tests (for example, with `npm run test`).
1. Login via UI and retrieve authentication state. 1. Login via UI and retrieve authentication state.
* In Jest, this can be executed in * In Jest, this can be executed in [`globalSetup`](https://jestjs.io/docs/en/configuration#globalsetup-string).
[`globalSetup`](https://jestjs.io/docs/en/configuration#globalsetup-string). 1. In each test, load authentication state in `beforeEach` or `beforeAll` step.
1. In each test, load authentication state in `beforeEach` or `beforeAll`
step.
This approach will also **work in CI environments**, since it does not rely on This approach will also **work in CI environments**, since it does not rely on any external state.
any external state.
### Example ### Example
[This example script](examples/authentication.js) logs in on GitHub.com with [This example script](examples/authentication.js) logs in on GitHub.com with Chromium, and then reuses the logged in cookie state in WebKit.
Chromium, and then reuses the logged in cookie state in WebKit.
### API reference ### API reference
- [BrowserContext] - [BrowserContext]
- [browserContext.cookies([urls])](./api.md#browsercontextcookiesurls) - [browserContext.cookies([urls])](api/class-browsercontext.md#browsercontextcookiesurls)
- [browserContext.addCookies(cookies)](./api.md#browsercontextaddcookiescookies) - [browserContext.addCookies(cookies)](api/class-browsercontext.md#browsercontextaddcookiescookies)
- [page.evaluate(pageFunction[, arg])](./api.md#pageevaluatepagefunction-arg) - [page.evaluate(pageFunction[, arg])](api/class-page.md#pageevaluatepagefunction-arg)
- [browserContext.addInitScript(script[, arg])](./api.md#browsercontextaddinitscriptscript-arg) - [browserContext.addInitScript(script[, arg])](api/class-browsercontext.md#browsercontextaddinitscriptscript-arg)
## Multi-factor authentication ## Multi-factor authentication
Accounts with multi-factor authentication (MFA) cannot be fully automated, and Accounts with multi-factor authentication (MFA) cannot be fully automated, and need manual intervention. Persistent authentication can be used to partially automate MFA scenarios.
need manual intervention. Persistent authentication can be used to partially
automate MFA scenarios.
### Persistent authentication ### Persistent authentication
Web browsers use a directory on disk to store user history, cookies, IndexedDB Web browsers use a directory on disk to store user history, cookies, IndexedDB and other local state. This disk location is called the [User data directory](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md).
and other local state. This disk location is called the
[User data directory](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md).
Note that persistent authentication is not suited for CI environments since it Note that persistent authentication is not suited for CI environments since it relies on a disk location. User data directories are specific to browser types and cannot be shared across browser types.
relies on a disk location. User data directories are specific to browser types
and cannot be shared across browser types.
User data directories can be used with the `launchPersistentContext` API. User data directories can be used with the `launchPersistentContext` API.
@ -181,51 +137,49 @@ const context = await chromium.launchPersistentContext(userDataDir, { headless:
``` ```
### Lifecycle ### Lifecycle
1. Create a user data directory on disk 2. Launch a persistent context with 1. Create a user data directory on disk 2. Launch a persistent context with the user data directory and login the MFA account. 3. Reuse user data directory to run automation scenarios.
the user data directory and login the MFA account. 3. Reuse user data
directory to run automation scenarios.
### API reference ### API reference
- [BrowserContext] - [BrowserContext]
- [browserType.launchPersistentContext(userDataDir[, options])](./api.md#browsertypelaunchpersistentcontextuserdatadir-options) - [browserType.launchPersistentContext(userDataDir[, options])](api/class-browsertype.md#browsertypelaunchpersistentcontextuserdatadir-options)
[Playwright]: api.md#class-playwright "Playwright" [Playwright]: api/class-playwright.md "Playwright"
[Browser]: api.md#class-browser "Browser" [Browser]: api/class-browser.md "Browser"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api.md#class-page "Page" [Page]: api/class-page.md "Page"
[Frame]: api.md#class-frame "Frame" [Frame]: api/class-frame.md "Frame"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api.md#class-dialog "Dialog" [Dialog]: api/class-dialog.md "Dialog"
[Download]: api.md#class-download "Download" [Download]: api/class-download.md "Download"
[Video]: api.md#class-video "Video" [Video]: api/class-video.md "Video"
[FileChooser]: api.md#class-filechooser "FileChooser" [FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api.md#class-keyboard "Keyboard" [Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api.md#class-mouse "Mouse" [Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api.md#class-request "Request" [Request]: api/class-request.md "Request"
[Response]: api.md#class-response "Response" [Response]: api/class-response.md "Response"
[Selectors]: api.md#class-selectors "Selectors" [Selectors]: api/class-selectors.md "Selectors"
[Route]: api.md#class-route "Route" [Route]: api/class-route.md "Route"
[WebSocket]: api.md#class-websocket "WebSocket" [WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api.md#class-accessibility "Accessibility" [Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api.md#class-worker "Worker" [Worker]: api/class-worker.md "Worker"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api.md#class-browsertype "BrowserType" [BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api.md#class-logger "Logger" [Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api.md#class-cdpsession "CDPSession" [CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -1,46 +1,28 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: ci
title: "Continuous Integration"
---
# Continuous Integration Playwright tests can be executed in CI environments. We have created sample configurations for common CI providers.
Playwright tests can be executed in CI environments. We have created sample
configurations for common CI providers.
<!-- GEN:toc -->
- [Introduction](#introduction) - [Introduction](#introduction)
- [CI configurations](#ci-configurations) - [CI configurations](#ci-configurations)
* [GitHub Actions](#github-actions)
* [Docker](#docker)
* [Azure Pipelines](#azure-pipelines)
* [Travis CI](#travis-ci)
* [CircleCI](#circleci)
* [Jenkins](#jenkins)
* [Bitbucket Pipelines](#bitbucket-pipelines)
* [GitLab CI](#gitlab-ci)
- [Caching browsers](#caching-browsers) - [Caching browsers](#caching-browsers)
- [Exception: `node_modules` are cached](#exception-node_modules-are-cached)
- [Directories to cache](#directories-to-cache)
- [Debugging browser launches](#debugging-browser-launches) - [Debugging browser launches](#debugging-browser-launches)
- [Running headful](#running-headful) - [Running headful](#running-headful)
<!-- GEN:stop -->
## Introduction ## Introduction
3 steps to get your tests running on CI: 3 steps to get your tests running on CI:
1. **Ensure CI agent can run browsers**: Use 1. **Ensure CI agent can run browsers**: Use [our Docker image](docker/README.md) in Linux agents. Windows and macOS agents do not require any additional dependencies.
[our Docker image](docker/README.md) in Linux agents. Windows and macOS 1. **Install Playwright**: In most projects, this would be done with `npm ci` (or `npm install`). Playwright would install the relevant browsers automatically.
agents do not require any additional dependencies.
1. **Install Playwright**: In most projects, this would be done with `npm ci`
(or `npm install`). Playwright would install the relevant browsers
automatically.
1. **Run your tests**: Use `npm test` or equivalent to execute your tests. 1. **Run your tests**: Use `npm test` or equivalent to execute your tests.
## CI configurations ## CI configurations
### GitHub Actions ### GitHub Actions
The The [Playwright GitHub Action](https://github.com/microsoft/playwright-github-action) can be used to run Playwright tests on GitHub Actions.
[Playwright GitHub Action](https://github.com/microsoft/playwright-github-action)
can be used to run Playwright tests on GitHub Actions.
```yml ```yml
steps: steps:
@ -49,23 +31,14 @@ steps:
run: npm test run: npm test
``` ```
We run [our tests](/.github/workflows/tests.yml) on GitHub Actions, across a We run [our tests](/.github/workflows/tests.yml) on GitHub Actions, across a matrix of 3 platforms (Windows, Linux, macOS) and 3 browsers (Chromium, Firefox, WebKit).
matrix of 3 platforms (Windows, Linux, macOS) and 3 browsers (Chromium, Firefox,
WebKit).
### Docker ### Docker
We have a [pre-built Docker image](docker/README.md) which can either be used We have a [pre-built Docker image](docker/README.md) which can either be used directly, or as a reference to update your existing Docker definitions.
directly, or as a reference to update your existing Docker definitions.
Suggested configuration Suggested configuration
1. By default, Docker runs a container with a `/dev/shm` shared memory space 1. By default, Docker runs a container with a `/dev/shm` shared memory space 64MB. This is [typically too small](https://github.com/c0b/chrome-in-docker/issues/1) for Chromium and will cause Chromium to crash when rendering large pages. To fix, run the container with `docker run --shm-size=1gb` to increase the size of `/dev/shm`. Since Chromium 65, this is no longer necessary. Instead, launch the browser with the `--disable-dev-shm-usage` flag:
64MB. This is
[typically too small](https://github.com/c0b/chrome-in-docker/issues/1)
for Chromium and will cause Chromium to crash when rendering large pages.
To fix, run the container with `docker run --shm-size=1gb` to increase the
size of `/dev/shm`. Since Chromium 65, this is no longer necessary.
Instead, launch the browser with the `--disable-dev-shm-usage` flag:
```js ```js
const browser = await playwright.chromium.launch({ const browser = await playwright.chromium.launch({
@ -73,29 +46,16 @@ Suggested configuration
}); });
``` ```
This will write shared memory files into `/tmp` instead of `/dev/shm`. See This will write shared memory files into `/tmp` instead of `/dev/shm`. See [crbug.com/736452](https://bugs.chromium.org/p/chromium/issues/detail?id=736452) for more details.
[crbug.com/736452](https://bugs.chromium.org/p/chromium/issues/detail?id=736452) 1. Using `--ipc=host` is also recommended when using Chromium—without it Chromium can run out of memory and crash. Learn more about this option in [Docker docs](https://docs.docker.com/engine/reference/run/#ipc-settings---ipc).
for more details. 1. Seeing other weird errors when launching Chromium? Try running your container with `docker run --cap-add=SYS_ADMIN` when developing locally.
1. Using `--ipc=host` is also recommended when using Chromium—without it 1. [dumb-init](https://github.com/Yelp/dumb-init) is worth checking out if you're experiencing a lot of zombies Chromium processes sticking around. There's special treatment for processes with PID=1, which makes it hard to terminate Chromium properly in some cases (e.g. in Docker).
Chromium can run out of memory and crash. Learn more about this option in
[Docker docs](https://docs.docker.com/engine/reference/run/#ipc-settings---ipc).
1. Seeing other weird errors when launching Chromium? Try running your
container with `docker run --cap-add=SYS_ADMIN` when developing locally.
1. [dumb-init](https://github.com/Yelp/dumb-init) is worth checking out if
you're experiencing a lot of zombies Chromium processes sticking around.
There's special treatment for processes with PID=1, which makes it hard to
terminate Chromium properly in some cases (e.g. in Docker).
### Azure Pipelines ### Azure Pipelines
For Windows or macOS agents, no additional configuration required, just install For Windows or macOS agents, no additional configuration required, just install Playwright and run your tests.
Playwright and run your tests.
For Linux agents, you can use [our Docker container](docker/README.md) with For Linux agents, you can use [our Docker container](docker/README.md) with Azure Pipelines support for [running containerized jobs](https://docs.microsoft.com/en-us/azure/devops/pipelines/process/container-phases?view=azure-devops). Alternatively, you can refer to the [Dockerfile](docker/README.md) to see additional dependencies that need to be installed on a Ubuntu agent.
Azure Pipelines support for
[running containerized jobs](https://docs.microsoft.com/en-us/azure/devops/pipelines/process/container-phases?view=azure-devops).
Alternatively, you can refer to the [Dockerfile](docker/README.md) to see
additional dependencies that need to be installed on a Ubuntu agent.
```yml ```yml
pool: pool:
@ -113,15 +73,9 @@ steps:
We run our tests on Travis CI over a Linux agent (Ubuntu 18.04). We run our tests on Travis CI over a Linux agent (Ubuntu 18.04).
Suggested configuration Suggested configuration
1. [User namespace cloning](http://man7.org/linux/man-pages/man7/user_namespaces.7.html) 1. [User namespace cloning](http://man7.org/linux/man-pages/man7/user_namespaces.7.html) should be enabled to support proper sandboxing
should be enabled to support proper sandboxing 1. [xvfb](https://en.wikipedia.org/wiki/Xvfb) should be launched in order to run Chromium in non-headless mode (e.g. to test Chrome Extensions)
1. [xvfb](https://en.wikipedia.org/wiki/Xvfb) should be launched in order to 1. If your project does not have `package-lock.json`, Travis would be auto-caching `node_modules` directory. If you run `npm install` (instead of `npm ci`), it is possible that the browser binaries are not downloaded. Fix this with [these steps](#exception-node_modules-are-cached) outlined below.
run Chromium in non-headless mode (e.g. to test Chrome Extensions)
1. If your project does not have `package-lock.json`, Travis would be
auto-caching `node_modules` directory. If you run `npm install` (instead
of `npm ci`), it is possible that the browser binaries are not downloaded.
Fix this with [these steps](#exception-node_modules-are-cached) outlined
below.
To sum up, your `.travis.yml` might look like this: To sum up, your `.travis.yml` might look like this:
@ -168,9 +122,7 @@ before_install:
### CircleCI ### CircleCI
We run our tests on CircleCI, with our We run our tests on CircleCI, with our [pre-built Docker image](docker/README.md). Running Playwright smoothly on CircleCI requires the following steps:
[pre-built Docker image](docker/README.md). Running Playwright smoothly on
CircleCI requires the following steps:
1. Use the pre-built [Docker image](docker/README.md) in your config like so: 1. Use the pre-built [Docker image](docker/README.md) in your config like so:
```yaml ```yaml
@ -180,8 +132,7 @@ CircleCI requires the following steps:
NODE_ENV: development # Needed if playwright is in `devDependencies` NODE_ENV: development # Needed if playwright is in `devDependencies`
``` ```
1. If youre using Playwright through Jest, then you may encounter an error 1. If youre using Playwright through Jest, then you may encounter an error spawning child processes:
spawning child processes:
``` ```
[00:00.0] jest args: --e2e --spec --max-workers=36 [00:00.0] jest args: --e2e --spec --max-workers=36
@ -189,14 +140,11 @@ CircleCI requires the following steps:
at ChildProcess.spawn (internal/child_process.js:394:11) at ChildProcess.spawn (internal/child_process.js:394:11)
``` ```
This is likely caused by Jest autodetecting the number of processes on the This is likely caused by Jest autodetecting the number of processes on the entire machine (`36`) rather than the number allowed to your container (`2`). To fix this, set `jest --maxWorkers=2` in your test command.
entire machine (`36`) rather than the number allowed to your container
(`2`). To fix this, set `jest --maxWorkers=2` in your test command.
### Jenkins ### Jenkins
Jenkins supports Docker agents for pipelines. Use the Jenkins supports Docker agents for pipelines. Use the [Playwright Docker image](docker/README.md) to run tests on Jenkins.
[Playwright Docker image](docker/README.md) to run tests on Jenkins.
```groovy ```groovy
pipeline { pipeline {
@ -214,18 +162,13 @@ pipeline {
### Bitbucket Pipelines ### Bitbucket Pipelines
Bitbucket Pipelines can use public Bitbucket Pipelines can use public [Docker images as build environments](https://confluence.atlassian.com/bitbucket/use-docker-images-as-build-environments-792298897.html). To run Playwright tests on Bitbucket, use our public Docker image ([see Dockerfile](docker/README.md)).
[Docker images as build environments](https://confluence.atlassian.com/bitbucket/use-docker-images-as-build-environments-792298897.html).
To run Playwright tests on Bitbucket, use our public Docker image
([see Dockerfile](docker/README.md)).
```yml ```yml
image: mcr.microsoft.com/playwright:bionic image: mcr.microsoft.com/playwright:bionic
``` ```
While the Docker image supports sandboxing for Chromium, it does not work in the While the Docker image supports sandboxing for Chromium, it does not work in the Bitbucket Pipelines environment. To launch Chromium on Bitbucket Pipelines, use the `chromiumSandbox: false` launch argument.
Bitbucket Pipelines environment. To launch Chromium on Bitbucket Pipelines, use
the `chromiumSandbox: false` launch argument.
```js ```js
const { chromium } = require('playwright'); const { chromium } = require('playwright');
@ -234,8 +177,7 @@ const browser = await chromium.launch({ chromiumSandbox: false });
### GitLab CI ### GitLab CI
To run Playwright tests on GitLab, use our public Docker image To run Playwright tests on GitLab, use our public Docker image ([see Dockerfile](docker/README.md)).
([see Dockerfile](docker/README.md)).
```yml ```yml
stages: stages:
@ -251,55 +193,36 @@ tests:
## Caching browsers ## Caching browsers
By default, Playwright downloads browser binaries when the Playwright NPM By default, Playwright downloads browser binaries when the Playwright NPM package is installed. The NPM packages have a `postinstall` hook that downloads the browser binaries. This behavior can be [customized with environment variables](./installation.md).
package is installed. The NPM packages have a `postinstall` hook that downloads
the browser binaries. This behavior can be
[customized with environment variables](./installation.md).
Caching browsers on CI is **strictly optional**: The `postinstall` hooks should Caching browsers on CI is **strictly optional**: The `postinstall` hooks should execute and download the browser binaries on every run.
execute and download the browser binaries on every run.
#### Exception: `node_modules` are cached #### Exception: `node_modules` are cached
Most CI providers cache the Most CI providers cache the [npm-cache](https://docs.npmjs.com/cli-commands/cache.html) directory (located at `$HOME/.npm`). If your CI pipelines caches the `node_modules` directory and you run `npm install` (instead of `npm ci`), the default configuration
[npm-cache](https://docs.npmjs.com/cli-commands/cache.html) directory (located
at `$HOME/.npm`). If your CI pipelines caches the `node_modules` directory and
you run `npm install` (instead of `npm ci`), the default configuration
**will not work**. This is because the `npm install` step will find the **will not work**. This is because the `npm install` step will find the Playwright NPM package on disk and not execute the `postinstall` step.
Playwright NPM package on disk and not execute the `postinstall` step.
> Travis CI automatically caches `node_modules` if your repo does not have a > Travis CI automatically caches `node_modules` if your repo does not have a `package-lock.json` file.
`package-lock.json` file.
This behavior can be fixed with one of the following approaches: This behavior can be fixed with one of the following approaches:
1. Move to caching `$HOME/.npm` or the npm-cache directory. (This is the 1. Move to caching `$HOME/.npm` or the npm-cache directory. (This is the default behavior in most CI providers.)
default behavior in most CI providers.) 1. Set `PLAYWRIGHT_BROWSERS_PATH=0` as the environment variable before running `npm install`. This will download the browser binaries in the `node_modules` directory and cache them with the package code. See [installation docs](./installation.md).
1. Set `PLAYWRIGHT_BROWSERS_PATH=0` as the environment variable before 1. Use `npm ci` (instead of `npm install`) which forces a clean install: by removing the existing `node_modules` directory. See [npm docs](https://docs.npmjs.com/cli/ci.html).
running `npm install`. This will download the browser binaries in the
`node_modules` directory and cache them with the package code. See
[installation docs](./installation.md).
1. Use `npm ci` (instead of `npm install`) which forces a clean install: by
removing the existing `node_modules` directory. See
[npm docs](https://docs.npmjs.com/cli/ci.html).
1. Cache the browser binaries, with the steps below. 1. Cache the browser binaries, with the steps below.
#### Directories to cache #### Directories to cache
With the default behavior, Playwright downloads the browser binaries in the With the default behavior, Playwright downloads the browser binaries in the following directories:
following directories:
- `%USERPROFILE%\AppData\Local\ms-playwright` on Windows - `%USERPROFILE%\AppData\Local\ms-playwright` on Windows
- `~/Library/Caches/ms-playwright` on MacOS - `~/Library/Caches/ms-playwright` on MacOS
- `~/.cache/ms-playwright` on Linux - `~/.cache/ms-playwright` on Linux
To cache the browser downloads between CI runs, cache this location in your CI To cache the browser downloads between CI runs, cache this location in your CI configuration, against a hash of the Playwright version.
configuration, against a hash of the Playwright version.
## Debugging browser launches ## Debugging browser launches
Playwright supports the `DEBUG` environment variable to output debug logs during Playwright supports the `DEBUG` environment variable to output debug logs during execution. Setting it to `pw:browser*` is helpful while debugging `Error: Failed to launch browser` errors.
execution. Setting it to `pw:browser*` is helpful while debugging `Error: Failed
to launch browser` errors.
``` ```
DEBUG=pw:browser* npm run test DEBUG=pw:browser* npm run test
@ -307,8 +230,7 @@ DEBUG=pw:browser* npm run test
## Running headful ## Running headful
By default, Playwright launches browsers in headless mode. This can be changed By default, Playwright launches browsers in headless mode. This can be changed by passing a flag when the browser is launched.
by passing a flag when the browser is launched.
```js ```js
// Works across chromium, firefox and webkit // Works across chromium, firefox and webkit
@ -316,54 +238,50 @@ const { chromium } = require('playwright');
const browser = await chromium.launch({ headless: false }); const browser = await chromium.launch({ headless: false });
``` ```
On Linux agents, headful execution requires On Linux agents, headful execution requires [Xvfb](https://en.wikipedia.org/wiki/Xvfb) to be installed. Our [Docker image](docker/README.md) and GitHub Action have Xvfb pre-installed. To run browsers in headful mode with Xvfb, add `xvfb-run` before the Node.js command.
[Xvfb](https://en.wikipedia.org/wiki/Xvfb) to be installed. Our
[Docker image](docker/README.md) and GitHub Action have Xvfb pre-installed. To
run browsers in headful mode with Xvfb, add `xvfb-run` before the Node.js
command.
``` ```
xvfb-run node index.js xvfb-run node index.js
``` ```
[Playwright]: api.md#class-playwright "Playwright" [Playwright]: api/class-playwright.md "Playwright"
[Browser]: api.md#class-browser "Browser" [Browser]: api/class-browser.md "Browser"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api.md#class-page "Page" [Page]: api/class-page.md "Page"
[Frame]: api.md#class-frame "Frame" [Frame]: api/class-frame.md "Frame"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api.md#class-dialog "Dialog" [Dialog]: api/class-dialog.md "Dialog"
[Download]: api.md#class-download "Download" [Download]: api/class-download.md "Download"
[Video]: api.md#class-video "Video" [Video]: api/class-video.md "Video"
[FileChooser]: api.md#class-filechooser "FileChooser" [FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api.md#class-keyboard "Keyboard" [Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api.md#class-mouse "Mouse" [Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api.md#class-request "Request" [Request]: api/class-request.md "Request"
[Response]: api.md#class-response "Response" [Response]: api/class-response.md "Response"
[Selectors]: api.md#class-selectors "Selectors" [Selectors]: api/class-selectors.md "Selectors"
[Route]: api.md#class-route "Route" [Route]: api/class-route.md "Route"
[WebSocket]: api.md#class-websocket "WebSocket" [WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api.md#class-accessibility "Accessibility" [Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api.md#class-worker "Worker" [Worker]: api/class-worker.md "Worker"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api.md#class-browsertype "BrowserType" [BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api.md#class-logger "Logger" [Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api.md#class-cdpsession "CDPSession" [CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

135
docs/class-accessibility.md Normal file
View file

@ -0,0 +1,135 @@
---
id: class-accessibility
title: "class: Accessibility"
---
The Accessibility class provides methods for inspecting Chromium's accessibility tree. The accessibility tree is used by assistive technology such as [screen readers](https://en.wikipedia.org/wiki/Screen_reader) or [switches](https://en.wikipedia.org/wiki/Switch_access).
Accessibility is a very platform-specific thing. On different platforms, there are different screen readers that might have wildly different output.
Blink - Chromium's rendering engine - has a concept of "accessibility tree", which is then translated into different platform-specific APIs. Accessibility namespace gives users access to the Blink Accessibility Tree.
Most of the accessibility tree gets filtered out when converting from Blink AX Tree to Platform-specific AX-Tree or by assistive technologies themselves. By default, Playwright tries to approximate this filtering, exposing only the "interesting" nodes of the tree.
- [accessibility.snapshot([options])](api/class-accessibility.md#accessibilitysnapshotoptions)
#### accessibility.snapshot([options])
- `options` <[Object]>
- `interestingOnly` <[boolean]> Prune uninteresting nodes from the tree. Defaults to `true`.
- `root` <[ElementHandle]> The root DOM element for the snapshot. Defaults to the whole page.
- returns: <[Promise]<[null]|[Object]>>
- `role` <[string]> The [role](https://www.w3.org/TR/wai-aria/#usage_intro).
- `name` <[string]> A human readable name for the node.
- `value` <[string]|[number]> The current value of the node, if applicable.
- `description` <[string]> An additional human readable description of the node, if applicable.
- `keyshortcuts` <[string]> Keyboard shortcuts associated with this node, if applicable.
- `roledescription` <[string]> A human readable alternative to the role, if applicable.
- `valuetext` <[string]> A description of the current value, if applicable.
- `disabled` <[boolean]> Whether the node is disabled, if applicable.
- `expanded` <[boolean]> Whether the node is expanded or collapsed, if applicable.
- `focused` <[boolean]> Whether the node is focused, if applicable.
- `modal` <[boolean]> Whether the node is [modal](https://en.wikipedia.org/wiki/Modal_window), if applicable.
- `multiline` <[boolean]> Whether the node text input supports multiline, if applicable.
- `multiselectable` <[boolean]> Whether more than one child can be selected, if applicable.
- `readonly` <[boolean]> Whether the node is read only, if applicable.
- `required` <[boolean]> Whether the node is required, if applicable.
- `selected` <[boolean]> Whether the node is selected in its parent node, if applicable.
- `checked` <boolean|"mixed"> Whether the checkbox is checked, or "mixed", if applicable.
- `pressed` <boolean|"mixed"> Whether the toggle button is checked, or "mixed", if applicable.
- `level` <[number]> The level of a heading, if applicable.
- `valuemin` <[number]> The minimum value in a node, if applicable.
- `valuemax` <[number]> The maximum value in a node, if applicable.
- `autocomplete` <[string]> What kind of autocomplete is supported by a control, if applicable.
- `haspopup` <[string]> What kind of popup is currently being shown for a node, if applicable.
- `invalid` <[string]> Whether and in what way this node's value is invalid, if applicable.
- `orientation` <[string]> Whether the node is oriented horizontally or vertically, if applicable.
- `children` <[Array]<[Object]>> Child nodes, if any, if applicable.
Captures the current state of the accessibility tree. The returned object represents the root accessible node of the page.
> **NOTE** The Chromium accessibility tree contains nodes that go unused on most platforms and by most screen readers. Playwright will discard them as well for an easier to process tree, unless `interestingOnly` is set to `false`.
An example of dumping the entire accessibility tree:
```js
const snapshot = await page.accessibility.snapshot();
console.log(snapshot);
```
An example of logging the focused node's name:
```js
const snapshot = await page.accessibility.snapshot();
const node = findFocusedNode(snapshot);
console.log(node && node.name);
function findFocusedNode(node) {
if (node.focused)
return node;
for (const child of node.children || []) {
const foundNode = findFocusedNode(child);
return foundNode;
}
return null;
}
```
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

268
docs/class-browser.md Normal file
View file

@ -0,0 +1,268 @@
---
id: class-browser
title: "class: Browser"
---
* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
A Browser is created when Playwright connects to a browser instance, either through [browserType.launch([options])](api/class-browsertype.md#browsertypelaunchoptions) or [browserType.connect(params)](api/class-browsertype.md#browsertypeconnectparams).
An example of using a [Browser] to create a [Page]:
```js
const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
(async () => {
const browser = await firefox.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
await browser.close();
})();
```
See [ChromiumBrowser], [FirefoxBrowser] and [WebKitBrowser] for browser-specific features. Note that [browserType.connect(params)](api/class-browsertype.md#browsertypeconnectparams) and [browserType.launch([options])](api/class-browsertype.md#browsertypelaunchoptions) always return a specific browser instance, based on the browser being connected to or launched.
- [browser.on('disconnected')](api/class-browser.md#browserondisconnected)
- [browser.close()](api/class-browser.md#browserclose)
- [browser.contexts()](api/class-browser.md#browsercontexts)
- [browser.isConnected()](api/class-browser.md#browserisconnected)
- [browser.newContext([options])](api/class-browser.md#browsernewcontextoptions)
- [browser.newPage([options])](api/class-browser.md#browsernewpageoptions)
- [browser.version()](api/class-browser.md#browserversion)
#### browser.on('disconnected')
Emitted when Browser gets disconnected from the browser application. This might happen because of one of the following:
* Browser application is closed or crashed.
* The [browser.close()](api/class-browser.md#browserclose) method was called.
#### browser.close()
- returns: <[Promise]>
In case this browser is obtained using [browserType.launch([options])](api/class-browsertype.md#browsertypelaunchoptions), closes the browser and all of its pages (if any were opened).
In case this browser is obtained using [browserType.connect(params)](api/class-browsertype.md#browsertypeconnectparams), clears all created contexts belonging to this browser and disconnects from the browser server.
The [Browser] object itself is considered to be disposed and cannot be used anymore.
#### browser.contexts()
- returns: <[Array]<[BrowserContext]>>
Returns an array of all open browser contexts. In a newly created browser, this will return zero browser contexts.
```js
const browser = await pw.webkit.launch();
console.log(browser.contexts().length); // prints `0`
const context = await browser.newContext();
console.log(browser.contexts().length); // prints `1`
```
#### browser.isConnected()
- returns: <[boolean]>
Indicates that the browser is connected.
#### browser.newContext([options])
- `options` <[Object]>
- `acceptDownloads` <[boolean]> Whether to automatically download all the attachments. Defaults to `false` where all the downloads are canceled.
- `bypassCSP` <[boolean]> Toggles bypassing page's Content-Security-Policy.
- `colorScheme` <"light"|"dark"|"no-preference"> Emulates `'prefers-colors-scheme'` media feature, supported values are `'light'`, `'dark'`, `'no-preference'`. See [page.emulateMedia(params)](api/class-page.md#pageemulatemediaparams) for more details. Defaults to '`light`'.
- `deviceScaleFactor` <[number]> Specify device scale factor (can be thought of as dpr). Defaults to `1`.
- `extraHTTPHeaders` <[Object]<[string], [string]>> An object containing additional HTTP headers to be sent with every request. All header values must be strings.
- `geolocation` <[Object]>
- `latitude` <[number]> Latitude between -90 and 90.
- `longitude` <[number]> Longitude between -180 and 180.
- `accuracy` <[number]> Non-negative accuracy value. Defaults to `0`.
- `hasTouch` <[boolean]> Specifies if viewport supports touch events. Defaults to false.
- `httpCredentials` <[Object]> Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
- `username` <[string]>
- `password` <[string]>
- `ignoreHTTPSErrors` <[boolean]> Whether to ignore HTTPS errors during navigation. Defaults to `false`.
- `isMobile` <[boolean]> Whether the `meta viewport` tag is taken into account and touch events are enabled. Defaults to `false`. Not supported in Firefox.
- `javaScriptEnabled` <[boolean]> Whether or not to enable JavaScript in the context. Defaults to `true`.
- `locale` <[string]> Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value, `Accept-Language` request header value as well as number and date formatting rules.
- `logger` <[Logger]> Logger sink for Playwright logging.
- `offline` <[boolean]> Whether to emulate network being offline. Defaults to `false`.
- `permissions` <[Array]<[string]>> A list of permissions to grant to all pages in this context. See [browserContext.grantPermissions(permissions[, options])](api/class-browsercontext.md#browsercontextgrantpermissionspermissions-options) for more details.
- `proxy` <[Object]> Network proxy settings to use with this context. Note that browser needs to be launched with the global proxy for this option to work. If all contexts override the proxy, global proxy will be never used and can be any string, for example `launch({ proxy: { server: 'per-context' } })`.
- `server` <[string]> Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example `http://myproxy.com:3128` or `socks5://myproxy.com:3128`. Short form `myproxy.com:3128` is considered an HTTP proxy.
- `bypass` <[string]> Optional coma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.
- `username` <[string]> Optional username to use if HTTP proxy requires authentication.
- `password` <[string]> Optional password to use if HTTP proxy requires authentication.
- `recordHar` <[Object]> Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into `recordHar.path` file. If not specified, the HAR is not recorded. Make sure to await [browserContext.close()](api/class-browsercontext.md#browsercontextclose) for the HAR to be saved.
- `omitContent` <[boolean]> Optional setting to control whether to omit request content from the HAR. Defaults to `false`.
- `path` <[string]> Path on the filesystem to write the HAR file to.
- `recordVideo` <[Object]> Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded. Make sure to await [browserContext.close()](api/class-browsercontext.md#browsercontextclose) for videos to be saved.
- `dir` <[string]> Path to the directory to put videos into.
- `size` <[Object]> Optional dimensions of the recorded videos. If not specified the size will be equal to `viewport`. If `viewport` is not configured explicitly the video size defaults to 1280x720. Actual picture of each page will be scaled down if necessary to fit the specified size.
- `width` <[number]> Video frame width.
- `height` <[number]> Video frame height.
- `storageState` <[string]|[Object]> Populates context with given storage state. This method can be used to initialize context with logged-in information obtained via [browserContext.storageState([options])](api/class-browsercontext.md#browsercontextstoragestateoptions). Either a path to the file with saved storage, or an object with the following fields:
- `cookies` <[Array]<[Object]>> Optional cookies to set for context
- `name` <[string]> **required**
- `value` <[string]> **required**
- `url` <[string]> Optional either url or domain / path are required
- `domain` <[string]> Optional either url or domain / path are required
- `path` <[string]> Optional either url or domain / path are required
- `expires` <[number]> Optional Unix time in seconds.
- `httpOnly` <[boolean]> Optional httpOnly flag
- `secure` <[boolean]> Optional secure flag
- `sameSite` <"Strict"|"Lax"|"None"> Optional sameSite flag
- `origins` <[Array]<[Object]>> Optional localStorage to set for context
- `origin` <[string]>
- `localStorage` <[Array]<[Object]>>
- `name` <[string]>
- `value` <[string]>
- `timezoneId` <[string]> Changes the timezone of the context. See [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1) for a list of supported timezone IDs.
- `userAgent` <[string]> Specific user agent to use in this context.
- `videoSize` <[Object]> **NOTE** Use `recordVideo` instead, it takes precedence over `videoSize`. Specifies dimensions of the automatically recorded video. Can only be used if `videosPath` is set. If not specified the size will be equal to `viewport`. If `viewport` is not configured explicitly the video size defaults to 1280x720. Actual picture of the page will be scaled down if necessary to fit specified size.
- `width` <[number]> Video frame width.
- `height` <[number]> Video frame height.
- `videosPath` <[string]> **NOTE** Use `recordVideo` instead, it takes precedence over `videosPath`. Enables video recording for all pages to `videosPath` directory. If not specified, videos are not recorded. Make sure to await [browserContext.close()](api/class-browsercontext.md#browsercontextclose) for videos to be saved.
- `viewport` <[null]|[Object]> Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `null` disables the default viewport.
- `width` <[number]> page width in pixels.
- `height` <[number]> page height in pixels.
- returns: <[Promise]<[BrowserContext]>>
Creates a new browser context. It won't share cookies/cache with other browser contexts.
```js
(async () => {
const browser = await playwright.firefox.launch(); // Or 'chromium' or 'webkit'.
// Create a new incognito browser context.
const context = await browser.newContext();
// Create a new page in a pristine context.
const page = await context.newPage();
await page.goto('https://example.com');
})();
```
#### browser.newPage([options])
- `options` <[Object]>
- `acceptDownloads` <[boolean]> Whether to automatically download all the attachments. Defaults to `false` where all the downloads are canceled.
- `bypassCSP` <[boolean]> Toggles bypassing page's Content-Security-Policy.
- `colorScheme` <"light"|"dark"|"no-preference"> Emulates `'prefers-colors-scheme'` media feature, supported values are `'light'`, `'dark'`, `'no-preference'`. See [page.emulateMedia(params)](api/class-page.md#pageemulatemediaparams) for more details. Defaults to '`light`'.
- `deviceScaleFactor` <[number]> Specify device scale factor (can be thought of as dpr). Defaults to `1`.
- `extraHTTPHeaders` <[Object]<[string], [string]>> An object containing additional HTTP headers to be sent with every request. All header values must be strings.
- `geolocation` <[Object]>
- `latitude` <[number]> Latitude between -90 and 90.
- `longitude` <[number]> Longitude between -180 and 180.
- `accuracy` <[number]> Non-negative accuracy value. Defaults to `0`.
- `hasTouch` <[boolean]> Specifies if viewport supports touch events. Defaults to false.
- `httpCredentials` <[Object]> Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
- `username` <[string]>
- `password` <[string]>
- `ignoreHTTPSErrors` <[boolean]> Whether to ignore HTTPS errors during navigation. Defaults to `false`.
- `isMobile` <[boolean]> Whether the `meta viewport` tag is taken into account and touch events are enabled. Defaults to `false`. Not supported in Firefox.
- `javaScriptEnabled` <[boolean]> Whether or not to enable JavaScript in the context. Defaults to `true`.
- `locale` <[string]> Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value, `Accept-Language` request header value as well as number and date formatting rules.
- `logger` <[Logger]> Logger sink for Playwright logging.
- `offline` <[boolean]> Whether to emulate network being offline. Defaults to `false`.
- `permissions` <[Array]<[string]>> A list of permissions to grant to all pages in this context. See [browserContext.grantPermissions(permissions[, options])](api/class-browsercontext.md#browsercontextgrantpermissionspermissions-options) for more details.
- `proxy` <[Object]> Network proxy settings to use with this context. Note that browser needs to be launched with the global proxy for this option to work. If all contexts override the proxy, global proxy will be never used and can be any string, for example `launch({ proxy: { server: 'per-context' } })`.
- `server` <[string]> Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example `http://myproxy.com:3128` or `socks5://myproxy.com:3128`. Short form `myproxy.com:3128` is considered an HTTP proxy.
- `bypass` <[string]> Optional coma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.
- `username` <[string]> Optional username to use if HTTP proxy requires authentication.
- `password` <[string]> Optional password to use if HTTP proxy requires authentication.
- `recordHar` <[Object]> Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into `recordHar.path` file. If not specified, the HAR is not recorded. Make sure to await [browserContext.close()](api/class-browsercontext.md#browsercontextclose) for the HAR to be saved.
- `omitContent` <[boolean]> Optional setting to control whether to omit request content from the HAR. Defaults to `false`.
- `path` <[string]> Path on the filesystem to write the HAR file to.
- `recordVideo` <[Object]> Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded. Make sure to await [browserContext.close()](api/class-browsercontext.md#browsercontextclose) for videos to be saved.
- `dir` <[string]> Path to the directory to put videos into.
- `size` <[Object]> Optional dimensions of the recorded videos. If not specified the size will be equal to `viewport`. If `viewport` is not configured explicitly the video size defaults to 1280x720. Actual picture of each page will be scaled down if necessary to fit the specified size.
- `width` <[number]> Video frame width.
- `height` <[number]> Video frame height.
- `storageState` <[string]|[Object]> Populates context with given storage state. This method can be used to initialize context with logged-in information obtained via [browserContext.storageState([options])](api/class-browsercontext.md#browsercontextstoragestateoptions). Either a path to the file with saved storage, or an object with the following fields:
- `cookies` <[Array]<[Object]>> Optional cookies to set for context
- `name` <[string]> **required**
- `value` <[string]> **required**
- `url` <[string]> Optional either url or domain / path are required
- `domain` <[string]> Optional either url or domain / path are required
- `path` <[string]> Optional either url or domain / path are required
- `expires` <[number]> Optional Unix time in seconds.
- `httpOnly` <[boolean]> Optional httpOnly flag
- `secure` <[boolean]> Optional secure flag
- `sameSite` <"Strict"|"Lax"|"None"> Optional sameSite flag
- `origins` <[Array]<[Object]>> Optional localStorage to set for context
- `origin` <[string]>
- `localStorage` <[Array]<[Object]>>
- `name` <[string]>
- `value` <[string]>
- `timezoneId` <[string]> Changes the timezone of the context. See [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1) for a list of supported timezone IDs.
- `userAgent` <[string]> Specific user agent to use in this context.
- `videoSize` <[Object]> **NOTE** Use `recordVideo` instead, it takes precedence over `videoSize`. Specifies dimensions of the automatically recorded video. Can only be used if `videosPath` is set. If not specified the size will be equal to `viewport`. If `viewport` is not configured explicitly the video size defaults to 1280x720. Actual picture of the page will be scaled down if necessary to fit specified size.
- `width` <[number]> Video frame width.
- `height` <[number]> Video frame height.
- `videosPath` <[string]> **NOTE** Use `recordVideo` instead, it takes precedence over `videosPath`. Enables video recording for all pages to `videosPath` directory. If not specified, videos are not recorded. Make sure to await [browserContext.close()](api/class-browsercontext.md#browsercontextclose) for videos to be saved.
- `viewport` <[null]|[Object]> Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `null` disables the default viewport.
- `width` <[number]> page width in pixels.
- `height` <[number]> page height in pixels.
- returns: <[Promise]<[Page]>>
Creates a new page in a new browser context. Closing this page will close the context as well.
This is a convenience API that should only be used for the single-page scenarios and short snippets. Production code and testing frameworks should explicitly create [browser.newContext([options])](api/class-browser.md#browsernewcontextoptions) followed by the [browserContext.newPage()](api/class-browsercontext.md#browsercontextnewpage) to control their exact life times.
#### browser.version()
- returns: <[string]>
Returns the browser version.
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

View file

@ -0,0 +1,471 @@
---
id: class-browsercontext
title: "class: BrowserContext"
---
* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
BrowserContexts provide a way to operate multiple independent browser sessions.
If a page opens another page, e.g. with a `window.open` call, the popup will belong to the parent page's browser context.
Playwright allows creation of "incognito" browser contexts with `browser.newContext()` method. "Incognito" browser contexts don't write any browsing data to disk.
```js
// Create a new incognito browser context
const context = await browser.newContext();
// Create a new page inside context.
const page = await context.newPage();
await page.goto('https://example.com');
// Dispose context once it's no longer needed.
await context.close();
```
- [browserContext.on('close')](api/class-browsercontext.md#browsercontextonclose)
- [browserContext.on('page')](api/class-browsercontext.md#browsercontextonpage)
- [browserContext.addCookies(cookies)](api/class-browsercontext.md#browsercontextaddcookiescookies)
- [browserContext.addInitScript(script[, arg])](api/class-browsercontext.md#browsercontextaddinitscriptscript-arg)
- [browserContext.browser()](api/class-browsercontext.md#browsercontextbrowser)
- [browserContext.clearCookies()](api/class-browsercontext.md#browsercontextclearcookies)
- [browserContext.clearPermissions()](api/class-browsercontext.md#browsercontextclearpermissions)
- [browserContext.close()](api/class-browsercontext.md#browsercontextclose)
- [browserContext.cookies([urls])](api/class-browsercontext.md#browsercontextcookiesurls)
- [browserContext.exposeBinding(name, playwrightBinding[, options])](api/class-browsercontext.md#browsercontextexposebindingname-playwrightbinding-options)
- [browserContext.exposeFunction(name, playwrightFunction)](api/class-browsercontext.md#browsercontextexposefunctionname-playwrightfunction)
- [browserContext.grantPermissions(permissions[, options])](api/class-browsercontext.md#browsercontextgrantpermissionspermissions-options)
- [browserContext.newPage()](api/class-browsercontext.md#browsercontextnewpage)
- [browserContext.pages()](api/class-browsercontext.md#browsercontextpages)
- [browserContext.route(url, handler)](api/class-browsercontext.md#browsercontextrouteurl-handler)
- [browserContext.setDefaultNavigationTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaultnavigationtimeouttimeout)
- [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout)
- [browserContext.setExtraHTTPHeaders(headers)](api/class-browsercontext.md#browsercontextsetextrahttpheadersheaders)
- [browserContext.setGeolocation(geolocation)](api/class-browsercontext.md#browsercontextsetgeolocationgeolocation)
- [browserContext.setHTTPCredentials(httpCredentials)](api/class-browsercontext.md#browsercontextsethttpcredentialshttpcredentials)
- [browserContext.setOffline(offline)](api/class-browsercontext.md#browsercontextsetofflineoffline)
- [browserContext.storageState([options])](api/class-browsercontext.md#browsercontextstoragestateoptions)
- [browserContext.unroute(url[, handler])](api/class-browsercontext.md#browsercontextunrouteurl-handler)
- [browserContext.waitForEvent(event[, optionsOrPredicate])](api/class-browsercontext.md#browsercontextwaitforeventevent-optionsorpredicate)
#### browserContext.on('close')
Emitted when Browser context gets closed. This might happen because of one of the following:
* Browser context is closed.
* Browser application is closed or crashed.
* The [browser.close()](api/class-browser.md#browserclose) method was called.
#### browserContext.on('page')
- type: <[Page]>
The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event will also fire for popup pages. See also [page.on('popup')](api/class-page.md#pageonpopup) to receive events about popups relevant to a specific page.
The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a popup with `window.open('http://example.com')`, this event will fire when the network request to "http://example.com" is done and its response has started loading in the popup.
```js
const [page] = await Promise.all([
context.waitForEvent('page'),
page.click('a[target=_blank]'),
]);
console.log(await page.evaluate('location.href'));
```
> **NOTE** Use [page.waitForLoadState([state, options])](api/class-page.md#pagewaitforloadstatestate-options) to wait until the page gets to a particular state (you should not need it in most cases).
#### browserContext.addCookies(cookies)
- `cookies` <[Array]<[Object]>>
- `name` <[string]> **required**
- `value` <[string]> **required**
- `url` <[string]> either url or domain / path are required. Optional.
- `domain` <[string]> either url or domain / path are required Optional.
- `path` <[string]> either url or domain / path are required Optional.
- `expires` <[number]> Unix time in seconds. Optional.
- `httpOnly` <[boolean]> Optional.
- `secure` <[boolean]> Optional.
- `sameSite` <"Strict"|"Lax"|"None"> Optional.
- returns: <[Promise]>
Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies can be obtained via [browserContext.cookies([urls])](api/class-browsercontext.md#browsercontextcookiesurls).
```js
await browserContext.addCookies([cookieObject1, cookieObject2]);
```
#### browserContext.addInitScript(script[, arg])
- `script` <[function]|[string]|[Object]> Script to be evaluated in all pages in the browser context.
- `path` <[string]> Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working directory. Optional.
- `content` <[string]> Raw script content. Optional.
- `arg` <[Serializable]> Optional argument to pass to `script` (only supported when passing a function).
- returns: <[Promise]>
Adds a script which would be evaluated in one of the following scenarios:
* Whenever a page is created in the browser context or is navigated.
* Whenever a child frame is attached or navigated in any page in the browser context. In this case, the script is evaluated in the context of the newly attached frame.
The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed `Math.random`.
An example of overriding `Math.random` before the page loads:
```js
// preload.js
Math.random = () => 42;
```
```js
// In your playwright script, assuming the preload.js file is in same directory.
await browserContext.addInitScript({
path: 'preload.js'
});
```
> **NOTE** The order of evaluation of multiple scripts installed via [browserContext.addInitScript(script[, arg])](api/class-browsercontext.md#browsercontextaddinitscriptscript-arg) and [page.addInitScript(script[, arg])](api/class-page.md#pageaddinitscriptscript-arg) is not defined.
#### browserContext.browser()
- returns: <[null]|[Browser]>
Returns the browser instance of the context. If it was launched as a persistent context null gets returned.
#### browserContext.clearCookies()
- returns: <[Promise]>
Clears context cookies.
#### browserContext.clearPermissions()
- returns: <[Promise]>
Clears all permission overrides for the browser context.
```js
const context = await browser.newContext();
await context.grantPermissions(['clipboard-read']);
// do stuff ..
context.clearPermissions();
```
#### browserContext.close()
- returns: <[Promise]>
Closes the browser context. All the pages that belong to the browser context will be closed.
> **NOTE** the default browser context cannot be closed.
#### browserContext.cookies([urls])
- `urls` <[string]|[Array]<[string]>> Optional list of URLs.
- returns: <[Promise]<[Array]<[Object]>>>
- `name` <[string]>
- `value` <[string]>
- `domain` <[string]>
- `path` <[string]>
- `expires` <[number]> Unix time in seconds.
- `httpOnly` <[boolean]>
- `secure` <[boolean]>
- `sameSite` <"Strict"|"Lax"|"None">
If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs are returned.
#### browserContext.exposeBinding(name, playwrightBinding[, options])
- `name` <[string]> Name of the function on the window object.
- `playwrightBinding` <[function]> Callback function that will be called in the Playwright's context.
- `options` <[Object]>
- `handle` <[boolean]> Whether to pass the argument as a handle, instead of passing by value. When passing a handle, only one argument is supported. When passing by value, multiple arguments are supported.
- returns: <[Promise]>
The method adds a function called `name` on the `window` object of every frame in every page in the context. When called, the function executes `playwrightBinding` and returns a [Promise] which resolves to the return value of `playwrightBinding`. If the `playwrightBinding` returns a [Promise], it will be awaited.
The first argument of the `playwrightBinding` function contains information about the caller: `{ browserContext: BrowserContext, page: Page, frame: Frame }`.
See [page.exposeBinding(name, playwrightBinding[, options])](api/class-page.md#pageexposebindingname-playwrightbinding-options) for page-only version.
An example of exposing page URL to all frames in all pages in the context:
```js
const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
(async () => {
const browser = await webkit.launch({ headless: false });
const context = await browser.newContext();
await context.exposeBinding('pageURL', ({ page }) => page.url());
const page = await context.newPage();
await page.setContent(`
<script>
async function onClick() {
document.querySelector('div').textContent = await window.pageURL();
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
`);
await page.click('button');
})();
```
An example of passing an element handle:
```js
await context.exposeBinding('clicked', async (source, element) => {
console.log(await element.textContent());
}, { handle: true });
await page.setContent(`
<script>
document.addEventListener('click', event => window.clicked(event.target));
</script>
<div>Click me</div>
<div>Or click me</div>
`);
```
#### browserContext.exposeFunction(name, playwrightFunction)
- `name` <[string]> Name of the function on the window object.
- `playwrightFunction` <[function]> Callback function that will be called in the Playwright's context.
- returns: <[Promise]>
The method adds a function called `name` on the `window` object of every frame in every page in the context. When called, the function executes `playwrightFunction` and returns a [Promise] which resolves to the return value of `playwrightFunction`.
If the `playwrightFunction` returns a [Promise], it will be awaited.
See [page.exposeFunction(name, playwrightFunction)](api/class-page.md#pageexposefunctionname-playwrightfunction) for page-only version.
An example of adding an `md5` function to all pages in the context:
```js
const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
const crypto = require('crypto');
(async () => {
const browser = await webkit.launch({ headless: false });
const context = await browser.newContext();
await context.exposeFunction('md5', text => crypto.createHash('md5').update(text).digest('hex'));
const page = await context.newPage();
await page.setContent(`
<script>
async function onClick() {
document.querySelector('div').textContent = await window.md5('PLAYWRIGHT');
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
`);
await page.click('button');
})();
```
#### browserContext.grantPermissions(permissions[, options])
- `permissions` <[Array]<[string]>> A permission or an array of permissions to grant. Permissions can be one of the following values:
* `'geolocation'`
* `'midi'`
* `'midi-sysex'` (system-exclusive midi)
* `'notifications'`
* `'push'`
* `'camera'`
* `'microphone'`
* `'background-sync'`
* `'ambient-light-sensor'`
* `'accelerometer'`
* `'gyroscope'`
* `'magnetometer'`
* `'accessibility-events'`
* `'clipboard-read'`
* `'clipboard-write'`
* `'payment-handler'`
- `options` <[Object]>
- `origin` <[string]> The [origin] to grant permissions to, e.g. "https://example.com".
- returns: <[Promise]>
Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if specified.
#### browserContext.newPage()
- returns: <[Promise]<[Page]>>
Creates a new page in the browser context.
#### browserContext.pages()
- returns: <[Array]<[Page]>>
Returns all open pages in the context. Non visible pages, such as `"background_page"`, will not be listed here. You can find them using [chromiumBrowserContext.backgroundPages()](api/class-chromiumbrowsercontext.md#chromiumbrowsercontextbackgroundpages).
#### browserContext.route(url, handler)
- `url` <[string]|[RegExp]|[function]\([URL]\):[boolean]> A glob pattern, regex pattern or predicate receiving [URL] to match while routing.
- `handler` <[function]\([Route], [Request]\)> handler function to route the request.
- returns: <[Promise]>
Routing provides the capability to modify network requests that are made by any page in the browser context. Once route is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
An example of a naïve handler that aborts all image requests:
```js
const context = await browser.newContext();
await context.route('**/*.{png,jpg,jpeg}', route => route.abort());
const page = await context.newPage();
await page.goto('https://example.com');
await browser.close();
```
or the same snippet using a regex pattern instead:
```js
const context = await browser.newContext();
await context.route(/(\.png$)|(\.jpg$)/, route => route.abort());
const page = await context.newPage();
await page.goto('https://example.com');
await browser.close();
```
Page routes (set up with [page.route(url, handler)](api/class-page.md#pagerouteurl-handler)) take precedence over browser context routes when request matches both handlers.
> **NOTE** Enabling routing disables http cache.
#### browserContext.setDefaultNavigationTimeout(timeout)
- `timeout` <[number]> Maximum navigation time in milliseconds
This setting will change the default maximum navigation time for the following methods and related shortcuts:
* [page.goBack([options])](api/class-page.md#pagegobackoptions)
* [page.goForward([options])](api/class-page.md#pagegoforwardoptions)
* [page.goto(url[, options])](api/class-page.md#pagegotourl-options)
* [page.reload([options])](api/class-page.md#pagereloadoptions)
* [page.setContent(html[, options])](api/class-page.md#pagesetcontenthtml-options)
* [page.waitForNavigation([options])](api/class-page.md#pagewaitfornavigationoptions)
> **NOTE** [page.setDefaultNavigationTimeout(timeout)](api/class-page.md#pagesetdefaultnavigationtimeouttimeout) and [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) take priority over [browserContext.setDefaultNavigationTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaultnavigationtimeouttimeout).
#### browserContext.setDefaultTimeout(timeout)
- `timeout` <[number]> Maximum time in milliseconds
This setting will change the default maximum time for all the methods accepting `timeout` option.
> **NOTE** [page.setDefaultNavigationTimeout(timeout)](api/class-page.md#pagesetdefaultnavigationtimeouttimeout), [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) and [browserContext.setDefaultNavigationTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaultnavigationtimeouttimeout) take priority over [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout).
#### browserContext.setExtraHTTPHeaders(headers)
- `headers` <[Object]<[string], [string]>> An object containing additional HTTP headers to be sent with every request. All header values must be strings.
- returns: <[Promise]>
The extra HTTP headers will be sent with every request initiated by any page in the context. These headers are merged with page-specific extra HTTP headers set with [page.setExtraHTTPHeaders(headers)](api/class-page.md#pagesetextrahttpheadersheaders). If page overrides a particular header, page-specific header value will be used instead of the browser context header value.
> **NOTE** `browserContext.setExtraHTTPHeaders` does not guarantee the order of headers in the outgoing requests.
#### browserContext.setGeolocation(geolocation)
- `geolocation` <[null]|[Object]>
- `latitude` <[number]> Latitude between -90 and 90. **required**
- `longitude` <[number]> Longitude between -180 and 180. **required**
- `accuracy` <[number]> Non-negative accuracy value. Defaults to `0`.
- returns: <[Promise]>
Sets the context's geolocation. Passing `null` or `undefined` emulates position unavailable.
```js
await browserContext.setGeolocation({latitude: 59.95, longitude: 30.31667});
```
> **NOTE** Consider using [browserContext.grantPermissions(permissions[, options])](api/class-browsercontext.md#browsercontextgrantpermissionspermissions-options) to grant permissions for the browser context pages to read its geolocation.
#### browserContext.setHTTPCredentials(httpCredentials)
- `httpCredentials` <[null]|[Object]>
- `username` <[string]> **required**
- `password` <[string]> **required**
- returns: <[Promise]>
Provide credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
> **NOTE** Browsers may cache credentials after successful authentication. Passing different credentials or passing `null` to disable authentication will be unreliable. To remove or replace credentials, create a new browser context instead.
#### browserContext.setOffline(offline)
- `offline` <[boolean]> Whether to emulate network being offline for the browser context.
- returns: <[Promise]>
#### browserContext.storageState([options])
- `options` <[Object]>
- `path` <[string]> The file path to save the storage state to. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). If no path is provided, storage state is still returned, but won't be saved to the disk.
- returns: <[Promise]<[Object]>>
- `cookies` <[Array]<[Object]>>
- `name` <[string]>
- `value` <[string]>
- `domain` <[string]>
- `path` <[string]>
- `expires` <[number]> Unix time in seconds.
- `httpOnly` <[boolean]>
- `secure` <[boolean]>
- `sameSite` <"Strict"|"Lax"|"None">
- `origins` <[Array]<[Object]>>
- `origin` <[string]>
- `localStorage` <[Array]<[Object]>>
- `name` <[string]>
- `value` <[string]>
Returns storage state for this browser context, contains current cookies and local storage snapshot.
#### browserContext.unroute(url[, handler])
- `url` <[string]|[RegExp]|[function]\([URL]\):[boolean]> A glob pattern, regex pattern or predicate receiving [URL] used to register a routing with [browserContext.route(url, handler)](api/class-browsercontext.md#browsercontextrouteurl-handler).
- `handler` <[function]\([Route], [Request]\)> Optional handler function used to register a routing with [browserContext.route(url, handler)](api/class-browsercontext.md#browsercontextrouteurl-handler).
- returns: <[Promise]>
Removes a route created with [browserContext.route(url, handler)](api/class-browsercontext.md#browsercontextrouteurl-handler). When `handler` is not specified, removes all routes for the `url`.
#### browserContext.waitForEvent(event[, optionsOrPredicate])
- `event` <[string]> Event name, same one would pass into `browserContext.on(event)`.
- `optionsOrPredicate` <[Function]|[Object]> Either a predicate that receives an event or an options object. Optional.
- `predicate` <[Function]> receives the event data and resolves to truthy value when the waiting should resolve.
- `timeout` <[number]> maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout).
- returns: <[Promise]<[Object]>>
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.
```js
const context = await browser.newContext();
await context.grantPermissions(['geolocation']);
```
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

View file

@ -0,0 +1,95 @@
---
id: class-browserserver
title: "class: BrowserServer"
---
- [browserServer.on('close')](api/class-browserserver.md#browserserveronclose)
- [browserServer.close()](api/class-browserserver.md#browserserverclose)
- [browserServer.kill()](api/class-browserserver.md#browserserverkill)
- [browserServer.process()](api/class-browserserver.md#browserserverprocess)
- [browserServer.wsEndpoint()](api/class-browserserver.md#browserserverwsendpoint)
#### browserServer.on('close')
Emitted when the browser server closes.
#### browserServer.close()
- returns: <[Promise]>
Closes the browser gracefully and makes sure the process is terminated.
#### browserServer.kill()
- returns: <[Promise]>
Kills the browser process and waits for the process to exit.
#### browserServer.process()
- returns: <[ChildProcess]>
Spawned browser application process.
#### browserServer.wsEndpoint()
- returns: <[string]>
Browser websocket url.
Browser websocket endpoint which can be used as an argument to [browserType.connect(params)](api/class-browsertype.md#browsertypeconnectparams) to establish connection to the browser.
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

251
docs/class-browsertype.md Normal file
View file

@ -0,0 +1,251 @@
---
id: class-browsertype
title: "class: BrowserType"
---
BrowserType provides methods to launch a specific browser instance or connect to an existing one. The following is a typical example of using Playwright to drive automation:
```js
const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
// other actions...
await browser.close();
})();
```
- [browserType.connect(params)](api/class-browsertype.md#browsertypeconnectparams)
- [browserType.executablePath()](api/class-browsertype.md#browsertypeexecutablepath)
- [browserType.launch([options])](api/class-browsertype.md#browsertypelaunchoptions)
- [browserType.launchPersistentContext(userDataDir[, options])](api/class-browsertype.md#browsertypelaunchpersistentcontextuserdatadir-options)
- [browserType.launchServer([options])](api/class-browsertype.md#browsertypelaunchserveroptions)
- [browserType.name()](api/class-browsertype.md#browsertypename)
#### browserType.connect(params)
- `params` <[Object]>
- `wsEndpoint` <[string]> A browser websocket endpoint to connect to. **required**
- `slowMo` <[number]> Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. Defaults to 0.
- `logger` <[Logger]> Logger sink for Playwright logging. Optional.
- `timeout` <[number]> Maximum time in milliseconds to wait for the connection to be established. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
- returns: <[Promise]<[Browser]>>
This methods attaches Playwright to an existing browser instance.
#### browserType.executablePath()
- returns: <[string]>
A path where Playwright expects to find a bundled browser executable.
#### browserType.launch([options])
- `options` <[Object]>
- `args` <[Array]<[string]>> Additional arguments to pass to the browser instance. The list of Chromium flags can be found [here](http://peter.sh/experiments/chromium-command-line-switches/).
- `chromiumSandbox` <[boolean]> Enable Chromium sandboxing. Defaults to `false`.
- `devtools` <[boolean]> **Chromium-only** Whether to auto-open a Developer Tools panel for each tab. If this option is `true`, the `headless` option will be set `false`.
- `downloadsPath` <[string]> If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and is deleted when browser is closed.
- `env` <[Object]<[string], [string]|[number]|[boolean]>> Specify environment variables that will be visible to the browser. Defaults to `process.env`.
- `executablePath` <[string]> Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium, Firefox or WebKit, use at your own risk.
- `firefoxUserPrefs` <[Object]<[string], [string]|[number]|[boolean]>> Firefox user preferences. Learn more about the Firefox user preferences at [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox).
- `handleSIGHUP` <[boolean]> Close the browser process on SIGHUP. Defaults to `true`.
- `handleSIGINT` <[boolean]> Close the browser process on Ctrl-C. Defaults to `true`.
- `handleSIGTERM` <[boolean]> Close the browser process on SIGTERM. Defaults to `true`.
- `headless` <[boolean]> Whether to run browser in headless mode. More details for [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode). Defaults to `true` unless the `devtools` option is `true`.
- `ignoreDefaultArgs` <[boolean]|[Array]<[string]>> If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. If an array is given, then filters out the given default arguments. Dangerous option; use with care. Defaults to `false`.
- `logger` <[Logger]> Logger sink for Playwright logging.
- `proxy` <[Object]> Network proxy settings.
- `server` <[string]> Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example `http://myproxy.com:3128` or `socks5://myproxy.com:3128`. Short form `myproxy.com:3128` is considered an HTTP proxy.
- `bypass` <[string]> Optional coma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.
- `username` <[string]> Optional username to use if HTTP proxy requires authentication.
- `password` <[string]> Optional password to use if HTTP proxy requires authentication.
- `slowMo` <[number]> Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on.
- `timeout` <[number]> Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
- returns: <[Promise]<[Browser]>>
Returns the browser instance.
You can use `ignoreDefaultArgs` to filter out `--mute-audio` from default arguments:
```js
const browser = await chromium.launch({ // Or 'firefox' or 'webkit'.
ignoreDefaultArgs: ['--mute-audio']
});
```
> **Chromium-only** Playwright can also be used to control the Chrome browser, but it works best with the version of Chromium it is bundled with. There is no guarantee it will work with any other version. Use `executablePath` option with extreme caution.
>
> If Google Chrome (rather than Chromium) is preferred, a [Chrome Canary](https://www.google.com/chrome/browser/canary.html) or [Dev Channel](https://www.chromium.org/getting-involved/dev-channel) build is suggested.
>
> In [browserType.launch([options])](api/class-browsertype.md#browsertypelaunchoptions) above, any mention of Chromium also applies to Chrome.
>
> See [`this article`](https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/) for a description of the differences between Chromium and Chrome. [`This article`](https://chromium.googlesource.com/chromium/src/+/lkgr/docs/chromium_browser_vs_google_chrome.md) describes some differences for Linux users.
#### browserType.launchPersistentContext(userDataDir[, options])
- `userDataDir` <[string]> Path to a User Data Directory, which stores browser session data like cookies and local storage. More details for [Chromium](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md) and [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options#User_Profile).
- `options` <[Object]>
- `acceptDownloads` <[boolean]> Whether to automatically download all the attachments. Defaults to `false` where all the downloads are canceled.
- `args` <[Array]<[string]>> Additional arguments to pass to the browser instance. The list of Chromium flags can be found [here](http://peter.sh/experiments/chromium-command-line-switches/).
- `bypassCSP` <[boolean]> Toggles bypassing page's Content-Security-Policy.
- `chromiumSandbox` <[boolean]> Enable Chromium sandboxing. Defaults to `true`.
- `colorScheme` <"light"|"dark"|"no-preference"> Emulates `'prefers-colors-scheme'` media feature, supported values are `'light'`, `'dark'`, `'no-preference'`. See [page.emulateMedia(params)](api/class-page.md#pageemulatemediaparams) for more details. Defaults to '`light`'.
- `deviceScaleFactor` <[number]> Specify device scale factor (can be thought of as dpr). Defaults to `1`.
- `devtools` <[boolean]> **Chromium-only** Whether to auto-open a Developer Tools panel for each tab. If this option is `true`, the `headless` option will be set `false`.
- `downloadsPath` <[string]> If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and is deleted when browser is closed.
- `env` <[Object]<[string], [string]|[number]|[boolean]>> Specify environment variables that will be visible to the browser. Defaults to `process.env`.
- `executablePath` <[string]> Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is resolved relative to the current working directory. **BEWARE**: Playwright is only guaranteed to work with the bundled Chromium, Firefox or WebKit, use at your own risk.
- `extraHTTPHeaders` <[Object]<[string], [string]>> An object containing additional HTTP headers to be sent with every request. All header values must be strings.
- `geolocation` <[Object]>
- `latitude` <[number]> Latitude between -90 and 90.
- `longitude` <[number]> Longitude between -180 and 180.
- `accuracy` <[number]> Non-negative accuracy value. Defaults to `0`.
- `handleSIGHUP` <[boolean]> Close the browser process on SIGHUP. Defaults to `true`.
- `handleSIGINT` <[boolean]> Close the browser process on Ctrl-C. Defaults to `true`.
- `handleSIGTERM` <[boolean]> Close the browser process on SIGTERM. Defaults to `true`.
- `hasTouch` <[boolean]> Specifies if viewport supports touch events. Defaults to false.
- `headless` <[boolean]> Whether to run browser in headless mode. More details for [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode). Defaults to `true` unless the `devtools` option is `true`.
- `httpCredentials` <[Object]> Credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
- `username` <[string]>
- `password` <[string]>
- `ignoreDefaultArgs` <[boolean]|[Array]<[string]>> If `true`, then do not use any of the default arguments. If an array is given, then filter out the given default arguments. Dangerous option; use with care. Defaults to `false`.
- `ignoreHTTPSErrors` <[boolean]> Whether to ignore HTTPS errors during navigation. Defaults to `false`.
- `isMobile` <[boolean]> Whether the `meta viewport` tag is taken into account and touch events are enabled. Defaults to `false`. Not supported in Firefox.
- `javaScriptEnabled` <[boolean]> Whether or not to enable JavaScript in the context. Defaults to `true`.
- `locale` <[string]> Specify user locale, for example `en-GB`, `de-DE`, etc. Locale will affect `navigator.language` value, `Accept-Language` request header value as well as number and date formatting rules.
- `logger` <[Logger]> Logger sink for Playwright logging.
- `offline` <[boolean]> Whether to emulate network being offline. Defaults to `false`.
- `permissions` <[Array]<[string]>> A list of permissions to grant to all pages in this context. See [browserContext.grantPermissions(permissions[, options])](api/class-browsercontext.md#browsercontextgrantpermissionspermissions-options) for more details.
- `proxy` <[Object]> Network proxy settings.
- `server` <[string]> Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example `http://myproxy.com:3128` or `socks5://myproxy.com:3128`. Short form `myproxy.com:3128` is considered an HTTP proxy.
- `bypass` <[string]> Optional coma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.
- `username` <[string]> Optional username to use if HTTP proxy requires authentication.
- `password` <[string]> Optional password to use if HTTP proxy requires authentication.
- `recordHar` <[Object]> Enables [HAR](http://www.softwareishard.com/blog/har-12-spec) recording for all pages into `recordHar.path` file. If not specified, the HAR is not recorded. Make sure to await [browserContext.close()](api/class-browsercontext.md#browsercontextclose) for the HAR to be saved.
- `omitContent` <[boolean]> Optional setting to control whether to omit request content from the HAR. Defaults to `false`.
- `path` <[string]> Path on the filesystem to write the HAR file to.
- `recordVideo` <[Object]> Enables video recording for all pages into `recordVideo.dir` directory. If not specified videos are not recorded. Make sure to await [browserContext.close()](api/class-browsercontext.md#browsercontextclose) for videos to be saved.
- `dir` <[string]> Path to the directory to put videos into.
- `size` <[Object]> Optional dimensions of the recorded videos. If not specified the size will be equal to `viewport`. If `viewport` is not configured explicitly the video size defaults to 1280x720. Actual picture of each page will be scaled down if necessary to fit the specified size.
- `width` <[number]> Video frame width.
- `height` <[number]> Video frame height.
- `slowMo` <[number]> Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. Defaults to 0.
- `timeout` <[number]> Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
- `timezoneId` <[string]> Changes the timezone of the context. See [ICU's metaZones.txt](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1) for a list of supported timezone IDs.
- `userAgent` <[string]> Specific user agent to use in this context.
- `videoSize` <[Object]> **NOTE** Use `recordVideo` instead, it takes precedence over `videoSize`. Specifies dimensions of the automatically recorded video. Can only be used if `videosPath` is set. If not specified the size will be equal to `viewport`. If `viewport` is not configured explicitly the video size defaults to 1280x720. Actual picture of the page will be scaled down if necessary to fit specified size.
- `width` <[number]> Video frame width.
- `height` <[number]> Video frame height.
- `videosPath` <[string]> **NOTE** Use `recordVideo` instead, it takes precedence over `videosPath`. Enables video recording for all pages to `videosPath` directory. If not specified, videos are not recorded. Make sure to await [browserContext.close()](api/class-browsercontext.md#browsercontextclose) for videos to be saved.
- `viewport` <[null]|[Object]> Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `null` disables the default viewport.
- `width` <[number]> page width in pixels.
- `height` <[number]> page height in pixels.
- returns: <[Promise]<[BrowserContext]>>
Returns the persistent browser context instance.
Launches browser that uses persistent storage located at `userDataDir` and returns the only context. Closing this context will automatically close the browser.
#### browserType.launchServer([options])
- `options` <[Object]>
- `args` <[Array]<[string]>> Additional arguments to pass to the browser instance. The list of Chromium flags can be found [here](http://peter.sh/experiments/chromium-command-line-switches/).
- `chromiumSandbox` <[boolean]> Enable Chromium sandboxing. Defaults to `true`.
- `devtools` <[boolean]> **Chromium-only** Whether to auto-open a Developer Tools panel for each tab. If this option is `true`, the `headless` option will be set `false`.
- `downloadsPath` <[string]> If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and is deleted when browser is closed.
- `env` <[Object]<[string], [string]|[number]|[boolean]>> Specify environment variables that will be visible to the browser. Defaults to `process.env`.
- `executablePath` <[string]> Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is resolved relative to the current working directory. **BEWARE**: Playwright is only guaranteed to work with the bundled Chromium, Firefox or WebKit, use at your own risk.
- `firefoxUserPrefs` <[Object]<[string], [string]|[number]|[boolean]>> Firefox user preferences. Learn more about the Firefox user preferences at [`about:config`](https://support.mozilla.org/en-US/kb/about-config-editor-firefox).
- `handleSIGHUP` <[boolean]> Close the browser process on SIGHUP. Defaults to `true`.
- `handleSIGINT` <[boolean]> Close the browser process on Ctrl-C. Defaults to `true`.
- `handleSIGTERM` <[boolean]> Close the browser process on SIGTERM. Defaults to `true`.
- `headless` <[boolean]> Whether to run browser in headless mode. More details for [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode). Defaults to `true` unless the `devtools` option is `true`.
- `ignoreDefaultArgs` <[boolean]|[Array]<[string]>> If `true`, then do not use any of the default arguments. If an array is given, then filter out the given default arguments. Dangerous option; use with care. Defaults to `false`.
- `logger` <[Logger]> Logger sink for Playwright logging.
- `port` <[number]> Port to use for the web socket. Defaults to 0 that picks any available port.
- `proxy` <[Object]> Network proxy settings.
- `server` <[string]> Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example `http://myproxy.com:3128` or `socks5://myproxy.com:3128`. Short form `myproxy.com:3128` is considered an HTTP proxy.
- `bypass` <[string]> Optional coma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`.
- `username` <[string]> Optional username to use if HTTP proxy requires authentication.
- `password` <[string]> Optional password to use if HTTP proxy requires authentication.
- `timeout` <[number]> Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
- returns: <[Promise]<[BrowserServer]>>
Returns the browser app instance.
Launches browser server that client can connect to. An example of launching a browser executable and connecting to it later:
```js
const { chromium } = require('playwright'); // Or 'webkit' or 'firefox'.
(async () => {
const browserServer = await chromium.launchServer();
const wsEndpoint = browserServer.wsEndpoint();
// Use web socket endpoint later to establish a connection.
const browser = await chromium.connect({ wsEndpoint });
// Close browser instance.
await browserServer.close();
})();
```
#### browserType.name()
- returns: <[string]>
Returns browser name. For example: `'chromium'`, `'webkit'` or `'firefox'`.
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

96
docs/class-cdpsession.md Normal file
View file

@ -0,0 +1,96 @@
---
id: class-cdpsession
title: "class: CDPSession"
---
* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
The `CDPSession` instances are used to talk raw Chrome Devtools Protocol:
* protocol methods can be called with `session.send` method.
* protocol events can be subscribed to with `session.on` method.
Useful links:
* Documentation on DevTools Protocol can be found here: [DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/).
* Getting Started with DevTools Protocol: https://github.com/aslushnikov/getting-started-with-cdp/blob/master/README.md
```js
const client = await page.context().newCDPSession(page);
await client.send('Animation.enable');
client.on('Animation.animationCreated', () => console.log('Animation created!'));
const response = await client.send('Animation.getPlaybackRate');
console.log('playback rate is ' + response.playbackRate);
await client.send('Animation.setPlaybackRate', {
playbackRate: response.playbackRate / 2
});
```
- [cdpSession.detach()](api/class-cdpsession.md#cdpsessiondetach)
- [cdpSession.send(method[, params])](api/class-cdpsession.md#cdpsessionsendmethod-params)
#### cdpSession.detach()
- returns: <[Promise]>
Detaches the CDPSession from the target. Once detached, the CDPSession object won't emit any events and can't be used to send messages.
#### cdpSession.send(method[, params])
- `method` <[string]> protocol method name
- `params` <[Object]> Optional method parameters
- returns: <[Promise]<[Object]>>
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

View file

@ -0,0 +1,103 @@
---
id: class-chromiumbrowser
title: "class: ChromiumBrowser"
---
* extends: [Browser]
Chromium-specific features including Tracing, service worker support, etc. You can use [chromiumBrowser.startTracing([page, options])](api/class-chromiumbrowser.md#chromiumbrowserstarttracingpage-options) and [chromiumBrowser.stopTracing()](api/class-chromiumbrowser.md#chromiumbrowserstoptracing) to create a trace file which can be opened in Chrome DevTools or [timeline viewer](https://chromedevtools.github.io/timeline-viewer/).
```js
await browser.startTracing(page, {path: 'trace.json'});
await page.goto('https://www.google.com');
await browser.stopTracing();
```
- [chromiumBrowser.newBrowserCDPSession()](api/class-chromiumbrowser.md#chromiumbrowsernewbrowsercdpsession)
- [chromiumBrowser.startTracing([page, options])](api/class-chromiumbrowser.md#chromiumbrowserstarttracingpage-options)
- [chromiumBrowser.stopTracing()](api/class-chromiumbrowser.md#chromiumbrowserstoptracing)
- [browser.on('disconnected')](api/class-browser.md#browserondisconnected)
- [browser.close()](api/class-browser.md#browserclose)
- [browser.contexts()](api/class-browser.md#browsercontexts)
- [browser.isConnected()](api/class-browser.md#browserisconnected)
- [browser.newContext([options])](api/class-browser.md#browsernewcontextoptions)
- [browser.newPage([options])](api/class-browser.md#browsernewpageoptions)
- [browser.version()](api/class-browser.md#browserversion)
#### chromiumBrowser.newBrowserCDPSession()
- returns: <[Promise]<[CDPSession]>>
Returns the newly created browser session.
#### chromiumBrowser.startTracing([page, options])
- `page` <[Page]> Optional, if specified, tracing includes screenshots of the given page.
- `options` <[Object]>
- `categories` <[Array]<[string]>> specify custom categories to use instead of default.
- `path` <[string]> A path to write the trace file to.
- `screenshots` <[boolean]> captures screenshots in the trace.
- returns: <[Promise]>
Only one trace can be active at a time per browser.
#### chromiumBrowser.stopTracing()
- returns: <[Promise]<[Buffer]>>
Returns the buffer with trace data.
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

View file

@ -0,0 +1,128 @@
---
id: class-chromiumbrowsercontext
title: "class: ChromiumBrowserContext"
---
* extends: [BrowserContext]
Chromium-specific features including background pages, service worker support, etc.
```js
const backgroundPage = await context.waitForEvent('backgroundpage');
```
- [chromiumBrowserContext.on('backgroundpage')](api/class-chromiumbrowsercontext.md#chromiumbrowsercontextonbackgroundpage)
- [chromiumBrowserContext.on('serviceworker')](api/class-chromiumbrowsercontext.md#chromiumbrowsercontextonserviceworker)
- [chromiumBrowserContext.backgroundPages()](api/class-chromiumbrowsercontext.md#chromiumbrowsercontextbackgroundpages)
- [chromiumBrowserContext.newCDPSession(page)](api/class-chromiumbrowsercontext.md#chromiumbrowsercontextnewcdpsessionpage)
- [chromiumBrowserContext.serviceWorkers()](api/class-chromiumbrowsercontext.md#chromiumbrowsercontextserviceworkers)
- [browserContext.on('close')](api/class-browsercontext.md#browsercontextonclose)
- [browserContext.on('page')](api/class-browsercontext.md#browsercontextonpage)
- [browserContext.addCookies(cookies)](api/class-browsercontext.md#browsercontextaddcookiescookies)
- [browserContext.addInitScript(script[, arg])](api/class-browsercontext.md#browsercontextaddinitscriptscript-arg)
- [browserContext.browser()](api/class-browsercontext.md#browsercontextbrowser)
- [browserContext.clearCookies()](api/class-browsercontext.md#browsercontextclearcookies)
- [browserContext.clearPermissions()](api/class-browsercontext.md#browsercontextclearpermissions)
- [browserContext.close()](api/class-browsercontext.md#browsercontextclose)
- [browserContext.cookies([urls])](api/class-browsercontext.md#browsercontextcookiesurls)
- [browserContext.exposeBinding(name, playwrightBinding[, options])](api/class-browsercontext.md#browsercontextexposebindingname-playwrightbinding-options)
- [browserContext.exposeFunction(name, playwrightFunction)](api/class-browsercontext.md#browsercontextexposefunctionname-playwrightfunction)
- [browserContext.grantPermissions(permissions[, options])](api/class-browsercontext.md#browsercontextgrantpermissionspermissions-options)
- [browserContext.newPage()](api/class-browsercontext.md#browsercontextnewpage)
- [browserContext.pages()](api/class-browsercontext.md#browsercontextpages)
- [browserContext.route(url, handler)](api/class-browsercontext.md#browsercontextrouteurl-handler)
- [browserContext.setDefaultNavigationTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaultnavigationtimeouttimeout)
- [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout)
- [browserContext.setExtraHTTPHeaders(headers)](api/class-browsercontext.md#browsercontextsetextrahttpheadersheaders)
- [browserContext.setGeolocation(geolocation)](api/class-browsercontext.md#browsercontextsetgeolocationgeolocation)
- [browserContext.setHTTPCredentials(httpCredentials)](api/class-browsercontext.md#browsercontextsethttpcredentialshttpcredentials)
- [browserContext.setOffline(offline)](api/class-browsercontext.md#browsercontextsetofflineoffline)
- [browserContext.storageState([options])](api/class-browsercontext.md#browsercontextstoragestateoptions)
- [browserContext.unroute(url[, handler])](api/class-browsercontext.md#browsercontextunrouteurl-handler)
- [browserContext.waitForEvent(event[, optionsOrPredicate])](api/class-browsercontext.md#browsercontextwaitforeventevent-optionsorpredicate)
#### chromiumBrowserContext.on('backgroundpage')
- type: <[Page]>
Emitted when new background page is created in the context.
> **NOTE** Only works with persistent context.
#### chromiumBrowserContext.on('serviceworker')
- type: <[Worker]>
Emitted when new service worker is created in the context.
#### chromiumBrowserContext.backgroundPages()
- returns: <[Array]<[Page]>>
All existing background pages in the context.
#### chromiumBrowserContext.newCDPSession(page)
- `page` <[Page]> Page to create new session for.
- returns: <[Promise]<[CDPSession]>>
Returns the newly created session.
#### chromiumBrowserContext.serviceWorkers()
- returns: <[Array]<[Worker]>>
All existing service workers in the context.
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

View file

@ -0,0 +1,138 @@
---
id: class-chromiumcoverage
title: "class: ChromiumCoverage"
---
Coverage gathers information about parts of JavaScript and CSS that were used by the page.
An example of using JavaScript coverage to produce Istambul report for page load:
```js
const { chromium } = require('playwright');
const v8toIstanbul = require('v8-to-istanbul');
(async() => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.coverage.startJSCoverage();
await page.goto('https://chromium.org');
const coverage = await page.coverage.stopJSCoverage();
for (const entry of coverage) {
const converter = new v8toIstanbul('', 0, { source: entry.source });
await converter.load();
converter.applyCoverage(entry.functions);
console.log(JSON.stringify(converter.toIstanbul()));
}
await browser.close();
})();
```
- [chromiumCoverage.startCSSCoverage([options])](api/class-chromiumcoverage.md#chromiumcoveragestartcsscoverageoptions)
- [chromiumCoverage.startJSCoverage([options])](api/class-chromiumcoverage.md#chromiumcoveragestartjscoverageoptions)
- [chromiumCoverage.stopCSSCoverage()](api/class-chromiumcoverage.md#chromiumcoveragestopcsscoverage)
- [chromiumCoverage.stopJSCoverage()](api/class-chromiumcoverage.md#chromiumcoveragestopjscoverage)
#### chromiumCoverage.startCSSCoverage([options])
- `options` <[Object]>
- `resetOnNavigation` <[boolean]> Whether to reset coverage on every navigation. Defaults to `true`.
- returns: <[Promise]>
Returns coverage is started
#### chromiumCoverage.startJSCoverage([options])
- `options` <[Object]>
- `reportAnonymousScripts` <[boolean]> Whether anonymous scripts generated by the page should be reported. Defaults to `false`.
- `resetOnNavigation` <[boolean]> Whether to reset coverage on every navigation. Defaults to `true`.
- returns: <[Promise]>
Returns coverage is started
> **NOTE** Anonymous scripts are ones that don't have an associated url. These are scripts that are dynamically created on the page using `eval` or `new Function`. If `reportAnonymousScripts` is set to `true`, anonymous scripts will have `__playwright_evaluation_script__` as their URL.
#### chromiumCoverage.stopCSSCoverage()
- returns: <[Promise]<[Array]<[Object]>>>
- `url` <[string]> StyleSheet URL
- `text` <[string]> StyleSheet content, if available.
- `ranges` <[Array]<[Object]>> StyleSheet ranges that were used. Ranges are sorted and non-overlapping.
- `start` <[number]> A start offset in text, inclusive
- `end` <[number]> An end offset in text, exclusive
Returns the array of coverage reports for all stylesheets
> **NOTE** CSS Coverage doesn't include dynamically injected style tags without sourceURLs.
#### chromiumCoverage.stopJSCoverage()
- returns: <[Promise]<[Array]<[Object]>>>
- `url` <[string]> Script URL
- `scriptId` <[string]> Script ID
- `source` <[string]> Script content, if applicable.
- `functions` <[Array]<[Object]>> V8-specific coverage format.
- `functionName` <[string]>
- `isBlockCoverage` <[boolean]>
- `ranges` <[Array]<[Object]>>
- `count` <[number]>
- `startOffset` <[number]>
- `endOffset` <[number]>
Returns the array of coverage reports for all scripts
> **NOTE** JavaScript Coverage doesn't include anonymous scripts by default. However, scripts with sourceURLs are reported.
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

View file

@ -0,0 +1,87 @@
---
id: class-consolemessage
title: "class: ConsoleMessage"
---
[ConsoleMessage] objects are dispatched by page via the [page.on('console')](api/class-page.md#pageonconsole) event.
- [consoleMessage.args()](api/class-consolemessage.md#consolemessageargs)
- [consoleMessage.location()](api/class-consolemessage.md#consolemessagelocation)
- [consoleMessage.text()](api/class-consolemessage.md#consolemessagetext)
- [consoleMessage.type()](api/class-consolemessage.md#consolemessagetype)
#### consoleMessage.args()
- returns: <[Array]<[JSHandle]>>
#### consoleMessage.location()
- returns: <[Object]>
- `url` <[string]> URL of the resource.
- `lineNumber` <[number]> 0-based line number in the resource.
- `columnNumber` <[number]> 0-based column number in the resource.
#### consoleMessage.text()
- returns: <[string]>
#### consoleMessage.type()
- returns: <[string]>
One of the following values: `'log'`, `'debug'`, `'info'`, `'error'`, `'warning'`, `'dir'`, `'dirxml'`, `'table'`, `'trace'`, `'clear'`, `'startGroup'`, `'startGroupCollapsed'`, `'endGroup'`, `'assert'`, `'profile'`, `'profileEnd'`, `'count'`, `'timeEnd'`.
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

114
docs/class-dialog.md Normal file
View file

@ -0,0 +1,114 @@
---
id: class-dialog
title: "class: Dialog"
---
[Dialog] objects are dispatched by page via the [page.on('dialog')](api/class-page.md#pageondialog) event.
An example of using `Dialog` class:
```js
const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
page.on('dialog', async dialog => {
console.log(dialog.message());
await dialog.dismiss();
await browser.close();
});
page.evaluate(() => alert('1'));
})();
```
- [dialog.accept([promptText])](api/class-dialog.md#dialogacceptprompttext)
- [dialog.defaultValue()](api/class-dialog.md#dialogdefaultvalue)
- [dialog.dismiss()](api/class-dialog.md#dialogdismiss)
- [dialog.message()](api/class-dialog.md#dialogmessage)
- [dialog.type()](api/class-dialog.md#dialogtype)
#### dialog.accept([promptText])
- `promptText` <[string]> A text to enter in prompt. Does not cause any effects if the dialog's `type` is not prompt. Optional.
- returns: <[Promise]>
Returns when the dialog has been accepted.
#### dialog.defaultValue()
- returns: <[string]>
If dialog is prompt, returns default prompt value. Otherwise, returns empty string.
#### dialog.dismiss()
- returns: <[Promise]>
Returns when the dialog has been dismissed.
#### dialog.message()
- returns: <[string]>
A message displayed in the dialog.
#### dialog.type()
- returns: <[string]>
Returns dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`.
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

125
docs/class-download.md Normal file
View file

@ -0,0 +1,125 @@
---
id: class-download
title: "class: Download"
---
[Download] objects are dispatched by page via the [page.on('download')](api/class-page.md#pageondownload) event.
All the downloaded files belonging to the browser context are deleted when the browser context is closed. All downloaded files are deleted when the browser closes.
Download event is emitted once the download starts. Download path becomes available once download completes:
```js
const [ download ] = await Promise.all([
page.waitForEvent('download'), // wait for download to start
page.click('a')
]);
// wait for download to complete
const path = await download.path();
...
```
> **NOTE** Browser context **must** be created with the `acceptDownloads` set to `true` when user needs access to the downloaded content. If `acceptDownloads` is not set or set to `false`, download events are emitted, but the actual download is not performed and user has no access to the downloaded files.
- [download.createReadStream()](api/class-download.md#downloadcreatereadstream)
- [download.delete()](api/class-download.md#downloaddelete)
- [download.failure()](api/class-download.md#downloadfailure)
- [download.path()](api/class-download.md#downloadpath)
- [download.saveAs(path)](api/class-download.md#downloadsaveaspath)
- [download.suggestedFilename()](api/class-download.md#downloadsuggestedfilename)
- [download.url()](api/class-download.md#downloadurl)
#### download.createReadStream()
- returns: <[Promise]<[null]|[Readable]>>
Returns readable stream for current download or `null` if download failed.
#### download.delete()
- returns: <[Promise]>
Deletes the downloaded file.
#### download.failure()
- returns: <[Promise]<[null]|[string]>>
Returns download error if any.
#### download.path()
- returns: <[Promise]<[null]|[string]>>
Returns path to the downloaded file in case of successful download.
#### download.saveAs(path)
- `path` <[string]> Path where the download should be saved.
- returns: <[Promise]>
Saves the download to a user-specified path.
#### download.suggestedFilename()
- returns: <[string]>
Returns suggested filename for this download. It is typically computed by the browser from the [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) response header or the `download` attribute. See the spec on [whatwg](https://html.spec.whatwg.org/#downloading-resources). Different browsers can use different logic for computing it.
#### download.url()
- returns: <[string]>
Returns downloaded url.
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

562
docs/class-elementhandle.md Normal file
View file

@ -0,0 +1,562 @@
---
id: class-elementhandle
title: "class: ElementHandle"
---
* extends: [JSHandle]
ElementHandle represents an in-page DOM element. ElementHandles can be created with the [page.$(selector)](api/class-page.md#pageselector) method.
```js
const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
const hrefElement = await page.$('a');
await hrefElement.click();
// ...
})();
```
ElementHandle prevents DOM element from garbage collection unless the handle is disposed with [jsHandle.dispose()](api/class-jshandle.md#jshandledispose). ElementHandles are auto-disposed when their origin frame gets navigated.
ElementHandle instances can be used as an argument in [page.$eval(selector, pageFunction[, arg])](api/class-page.md#pageevalselector-pagefunction-arg) and [page.evaluate(pageFunction[, arg])](api/class-page.md#pageevaluatepagefunction-arg) methods.
- [elementHandle.$(selector)](api/class-elementhandle.md#elementhandleselector)
- [elementHandle.$$(selector)](api/class-elementhandle.md#elementhandleselector-1)
- [elementHandle.$eval(selector, pageFunction[, arg])](api/class-elementhandle.md#elementhandleevalselector-pagefunction-arg)
- [elementHandle.$$eval(selector, pageFunction[, arg])](api/class-elementhandle.md#elementhandleevalselector-pagefunction-arg-1)
- [elementHandle.boundingBox()](api/class-elementhandle.md#elementhandleboundingbox)
- [elementHandle.check([options])](api/class-elementhandle.md#elementhandlecheckoptions)
- [elementHandle.click([options])](api/class-elementhandle.md#elementhandleclickoptions)
- [elementHandle.contentFrame()](api/class-elementhandle.md#elementhandlecontentframe)
- [elementHandle.dblclick([options])](api/class-elementhandle.md#elementhandledblclickoptions)
- [elementHandle.dispatchEvent(type[, eventInit])](api/class-elementhandle.md#elementhandledispatcheventtype-eventinit)
- [elementHandle.fill(value[, options])](api/class-elementhandle.md#elementhandlefillvalue-options)
- [elementHandle.focus()](api/class-elementhandle.md#elementhandlefocus)
- [elementHandle.getAttribute(name)](api/class-elementhandle.md#elementhandlegetattributename)
- [elementHandle.hover([options])](api/class-elementhandle.md#elementhandlehoveroptions)
- [elementHandle.innerHTML()](api/class-elementhandle.md#elementhandleinnerhtml)
- [elementHandle.innerText()](api/class-elementhandle.md#elementhandleinnertext)
- [elementHandle.ownerFrame()](api/class-elementhandle.md#elementhandleownerframe)
- [elementHandle.press(key[, options])](api/class-elementhandle.md#elementhandlepresskey-options)
- [elementHandle.screenshot([options])](api/class-elementhandle.md#elementhandlescreenshotoptions)
- [elementHandle.scrollIntoViewIfNeeded([options])](api/class-elementhandle.md#elementhandlescrollintoviewifneededoptions)
- [elementHandle.selectOption(values[, options])](api/class-elementhandle.md#elementhandleselectoptionvalues-options)
- [elementHandle.selectText([options])](api/class-elementhandle.md#elementhandleselecttextoptions)
- [elementHandle.setInputFiles(files[, options])](api/class-elementhandle.md#elementhandlesetinputfilesfiles-options)
- [elementHandle.tap([options])](api/class-elementhandle.md#elementhandletapoptions)
- [elementHandle.textContent()](api/class-elementhandle.md#elementhandletextcontent)
- [elementHandle.type(text[, options])](api/class-elementhandle.md#elementhandletypetext-options)
- [elementHandle.uncheck([options])](api/class-elementhandle.md#elementhandleuncheckoptions)
- [elementHandle.waitForElementState(state[, options])](api/class-elementhandle.md#elementhandlewaitforelementstatestate-options)
- [elementHandle.waitForSelector(selector[, options])](api/class-elementhandle.md#elementhandlewaitforselectorselector-options)
- [jsHandle.asElement()](api/class-jshandle.md#jshandleaselement)
- [jsHandle.dispose()](api/class-jshandle.md#jshandledispose)
- [jsHandle.evaluate(pageFunction[, arg])](api/class-jshandle.md#jshandleevaluatepagefunction-arg)
- [jsHandle.evaluateHandle(pageFunction[, arg])](api/class-jshandle.md#jshandleevaluatehandlepagefunction-arg)
- [jsHandle.getProperties()](api/class-jshandle.md#jshandlegetproperties)
- [jsHandle.getProperty(propertyName)](api/class-jshandle.md#jshandlegetpropertypropertyname)
- [jsHandle.jsonValue()](api/class-jshandle.md#jshandlejsonvalue)
#### elementHandle.$(selector)
- `selector` <[string]> A selector to query for. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- returns: <[Promise]<[null]|[ElementHandle]>>
The method finds an element matching the specified selector in the `ElementHandle`'s subtree. See [Working with selectors](./selectors.md#working-with-selectors) for more details. If no elements match the selector, returns `null`.
#### elementHandle.$$(selector)
- `selector` <[string]> A selector to query for. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- returns: <[Promise]<[Array]<[ElementHandle]>>>
The method finds all elements matching the specified selector in the `ElementHandle`s subtree. See [Working with selectors](./selectors.md#working-with-selectors) for more details. If no elements match the selector, returns empty array.
#### elementHandle.$eval(selector, pageFunction[, arg])
- `selector` <[string]> A selector to query for. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `pageFunction` <[function]\([Element]\)> Function to be evaluated in browser context
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>>
Returns the return value of `pageFunction`
The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a first argument to `pageFunction`. See [Working with selectors](./selectors.md#working-with-selectors) for more details. If no elements match the selector, the method throws an error.
If `pageFunction` returns a [Promise], then `frame.$eval` would wait for the promise to resolve and return its value.
Examples:
```js
const tweetHandle = await page.$('.tweet');
expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');
expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');
```
#### elementHandle.$$eval(selector, pageFunction[, arg])
- `selector` <[string]> A selector to query for. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `pageFunction` <[function]\([Array]<[Element]>\)> Function to be evaluated in browser context
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>>
Returns the return value of `pageFunction`
The method finds all elements matching the specified selector in the `ElementHandle`'s subtree and passes an array of matched elements as a first argument to `pageFunction`. See [Working with selectors](./selectors.md#working-with-selectors) for more details.
If `pageFunction` returns a [Promise], then `frame.$$eval` would wait for the promise to resolve and return its value.
Examples:
```html
<div class="feed">
<div class="tweet">Hello!</div>
<div class="tweet">Hi!</div>
</div>
```
```js
const feedHandle = await page.$('.feed');
expect(await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText))).toEqual(['Hello!', 'Hi!']);
```
#### elementHandle.boundingBox()
- returns: <[Promise]<[null]|[Object]>>
- `x` <[number]> the x coordinate of the element in pixels.
- `y` <[number]> the y coordinate of the element in pixels.
- `width` <[number]> the width of the element in pixels.
- `height` <[number]> the height of the element in pixels.
This method returns the bounding box of the element, or `null` if the element is not visible. The bounding box is calculated relative to the main frame viewport - which is usually the same as the browser window.
Scrolling affects the returned bonding box, similarly to [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect). That means `x` and/or `y` may be negative.
Elements from child frames return the bounding box relative to the main frame, unlike the [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
Assuming the page is static, it is safe to use bounding box coordinates to perform input. For example, the following snippet should click the center of the element.
```js
const box = await elementHandle.boundingBox();
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
```
#### elementHandle.check([options])
- `options` <[Object]>
- `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
- `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
This method checks the element by performing the following steps:
1. Ensure that element is a checkbox or a radio input. If not, this method rejects. If the element is already checked, this method returns immediately.
1. Wait for [actionability](./actionability.md) checks on the element, unless `force` option is set.
1. Scroll the element into view if needed.
1. Use [page.mouse](api/class-page.md#pagemouse) to click in the center of the element.
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
1. Ensure that the element is now checked. If not, this method rejects.
If the element is detached from the DOM at any moment during the action, this method rejects.
When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
#### elementHandle.click([options])
- `options` <[Object]>
- `button` <"left"|"right"|"middle"> Defaults to `left`.
- `clickCount` <[number]> defaults to 1. See [UIEvent.detail].
- `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
- `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
- `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used.
- `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
- `position` <[Object]> A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.
- `x` <[number]>
- `y` <[number]>
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
This method clicks the element by performing the following steps:
1. Wait for [actionability](./actionability.md) checks on the element, unless `force` option is set.
1. Scroll the element into view if needed.
1. Use [page.mouse](api/class-page.md#pagemouse) to click in the center of the element, or the specified `position`.
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
If the element is detached from the DOM at any moment during the action, this method rejects.
When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
#### elementHandle.contentFrame()
- returns: <[Promise]<[null]|[Frame]>>
Returns the content frame for element handles referencing iframe nodes, or `null` otherwise
#### elementHandle.dblclick([options])
- `options` <[Object]>
- `button` <"left"|"right"|"middle"> Defaults to `left`.
- `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
- `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
- `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used.
- `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
- `position` <[Object]> A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.
- `x` <[number]>
- `y` <[number]>
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
This method double clicks the element by performing the following steps:
1. Wait for [actionability](./actionability.md) checks on the element, unless `force` option is set.
1. Scroll the element into view if needed.
1. Use [page.mouse](api/class-page.md#pagemouse) to double click in the center of the element, or the specified `position`.
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set. Note that if the first click of the `dblclick()` triggers a navigation event, this method will reject.
If the element is detached from the DOM at any moment during the action, this method rejects.
When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
> **NOTE** `elementHandle.dblclick()` dispatches two `click` events and a single `dblclick` event.
#### elementHandle.dispatchEvent(type[, eventInit])
- `type` <[string]> DOM event type: `"click"`, `"dragstart"`, etc.
- `eventInit` <[EvaluationArgument]> Optional event-specific initialization properties.
- returns: <[Promise]>
The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the elment, `click` is dispatched. This is equivalend to calling [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
```js
await elementHandle.dispatchEvent('click');
```
Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit` properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
* [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
* [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
* [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
* [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
* [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
* [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
* [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
```js
// Note you can only create DataTransfer in Chromium and Firefox
const dataTransfer = await page.evaluateHandle(() => new DataTransfer());
await elementHandle.dispatchEvent('dragstart', { dataTransfer });
```
#### elementHandle.fill(value[, options])
- `value` <[string]> Value to set for the `<input>`, `<textarea>` or `[contenteditable]` element.
- `options` <[Object]>
- `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
This method waits for [actionability](./actionability.md) checks, focuses the element, fills it and triggers an `input` event after filling. If the element is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an error. Note that you can pass an empty string to clear the input field.
#### elementHandle.focus()
- returns: <[Promise]>
Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the element.
#### elementHandle.getAttribute(name)
- `name` <[string]> Attribute name to get the value for.
- returns: <[Promise]<[null]|[string]>>
Returns element attribute value.
#### elementHandle.hover([options])
- `options` <[Object]>
- `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
- `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used.
- `position` <[Object]> A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.
- `x` <[number]>
- `y` <[number]>
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
This method hovers over the element by performing the following steps:
1. Wait for [actionability](./actionability.md) checks on the element, unless `force` option is set.
1. Scroll the element into view if needed.
1. Use [page.mouse](api/class-page.md#pagemouse) to hover over the center of the element, or the specified `position`.
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
If the element is detached from the DOM at any moment during the action, this method rejects.
When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
#### elementHandle.innerHTML()
- returns: <[Promise]<[string]>>
Returns the `element.innerHTML`.
#### elementHandle.innerText()
- returns: <[Promise]<[string]>>
Returns the `element.innerText`.
#### elementHandle.ownerFrame()
- returns: <[Promise]<[null]|[Frame]>>
Returns the frame containing the given element.
#### elementHandle.press(key[, options])
- `key` <[string]> Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
- `options` <[Object]>
- `delay` <[number]> Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
- `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
Focuses the element, and then uses [keyboard.down(key)](api/class-keyboard.md#keyboarddownkey) and [keyboard.up(key)](api/class-keyboard.md#keyboardupkey).
`key` can specify the intended [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character to generate the text for. A superset of the `key` values can be found [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
`F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`, `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`, etc.
Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective texts.
Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When speficied with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
#### elementHandle.screenshot([options])
- `options` <[Object]>
- `omitBackground` <[boolean]> Hides default white background and allows capturing screenshots with transparency. Not applicable to `jpeg` images. Defaults to `false`.
- `path` <[string]> The file path to save the image to. The screenshot type will be inferred from file extension. If `path` is a relative path, then it is resolved relative to the current working directory. If no path is provided, the image won't be saved to the disk.
- `quality` <[number]> The quality of the image, between 0-100. Not applicable to `png` images.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- `type` <"png"|"jpeg"> Specify screenshot type, defaults to `png`.
- returns: <[Promise]<[Buffer]>>
Returns the buffer with the captured screenshot.
This method waits for the [actionability](./actionability.md) checks, then scrolls element into view before taking a screenshot. If the element is detached from DOM, the method throws an error.
#### elementHandle.scrollIntoViewIfNeeded([options])
- `options` <[Object]>
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
This method waits for [actionability](./actionability.md) checks, then tries to scroll element into view, unless it is completely visible as defined by [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)'s ```ratio```.
Throws when `elementHandle` does not point to an element [connected](https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected) to a Document or a ShadowRoot.
#### elementHandle.selectOption(values[, options])
- `values` <[null]|[string]|[ElementHandle]|[Array]<[string]>|[Object]|[Array]<[ElementHandle]>|[Array]<[Object]>> Options to select. If the `<select>` has the `multiple` attribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are equivalent to `{value:'string'}`. Option is considered matching if all specified properties match.
- `value` <[string]> Matches by `option.value`. Optional.
- `label` <[string]> Matches by `option.label`. Optional.
- `index` <[number]> Matches by the index. Optional.
- `options` <[Object]>
- `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]<[Array]<[string]>>>
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. If element is not a `<select>` element, the method throws an error.
```js
// single selection matching the value
handle.selectOption('blue');
// single selection matching both the value and the label
handle.selectOption({ label: 'Blue' });
// multiple selection
handle.selectOption('red', 'green', 'blue');
// multiple selection for blue, red and second option
handle.selectOption({ value: 'blue' }, { index: 2 }, 'red');
```
#### elementHandle.selectText([options])
- `options` <[Object]>
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
This method waits for [actionability](./actionability.md) checks, then focuses the element and selects all its text content.
#### elementHandle.setInputFiles(files[, options])
- `files` <[string]|[Array]<[string]>|[Object]|[Array]<[Object]>>
- `name` <[string]> [File] name **required**
- `mimeType` <[string]> [File] type **required**
- `buffer` <[Buffer]> File content **required**
- `options` <[Object]>
- `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
This method expects `elementHandle` to point to an [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then they are resolved relative to the the current working directory. For empty array, clears the selected files.
#### elementHandle.tap([options])
- `options` <[Object]>
- `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
- `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used.
- `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
- `position` <[Object]> A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.
- `x` <[number]>
- `y` <[number]>
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
This method taps the element by performing the following steps:
1. Wait for [actionability](./actionability.md) checks on the element, unless `force` option is set.
1. Scroll the element into view if needed.
1. Use [page.touchscreen](api/class-page.md#pagetouchscreen) to tap the center of the element, or the specified `position`.
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
If the element is detached from the DOM at any moment during the action, this method rejects.
When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
> **NOTE** `elementHandle.tap()` requires that the `hasTouch` option of the browser context be set to true.
#### elementHandle.textContent()
- returns: <[Promise]<[null]|[string]>>
Returns the `node.textContent`.
#### elementHandle.type(text[, options])
- `text` <[string]> A text to type into a focused element.
- `options` <[Object]>
- `delay` <[number]> Time to wait between key presses in milliseconds. Defaults to 0.
- `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text.
To press a special key, like `Control` or `ArrowDown`, use [elementHandle.press(key[, options])](api/class-elementhandle.md#elementhandlepresskey-options).
```js
await elementHandle.type('Hello'); // Types instantly
await elementHandle.type('World', {delay: 100}); // Types slower, like a user
```
An example of typing into a text field and then submitting the form:
```js
const elementHandle = await page.$('input');
await elementHandle.type('some text');
await elementHandle.press('Enter');
```
#### elementHandle.uncheck([options])
- `options` <[Object]>
- `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
- `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
This method checks the element by performing the following steps:
1. Ensure that element is a checkbox or a radio input. If not, this method rejects. If the element is already unchecked, this method returns immediately.
1. Wait for [actionability](./actionability.md) checks on the element, unless `force` option is set.
1. Scroll the element into view if needed.
1. Use [page.mouse](api/class-page.md#pagemouse) to click in the center of the element.
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
1. Ensure that the element is now unchecked. If not, this method rejects.
If the element is detached from the DOM at any moment during the action, this method rejects.
When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
#### elementHandle.waitForElementState(state[, options])
- `state` <"visible"|"hidden"|"stable"|"enabled"|"disabled"> A state to wait for, see below for more details.
- `options` <[Object]>
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
Returns the element satisfies the `state`.
Depending on the `state` parameter, this method waits for one of the [actionability](./actionability.md) checks to pass. This method throws when the element is detached while waiting, unless waiting for the `"hidden"` state.
* `"visible"` Wait until the element is [visible](./actionability.md#visible).
* `"hidden"` Wait until the element is [not visible](./actionability.md#visible) or [not attached](./actionability.md#attached). Note that waiting for hidden does not throw when the element detaches.
* `"stable"` Wait until the element is both [visible](./actionability.md#visible) and [stable](./actionability.md#stable).
* `"enabled"` Wait until the element is [enabled](./actionability.md#enabled).
* `"disabled"` Wait until the element is [not enabled](./actionability.md#enabled).
If the element does not satisfy the condition for the `timeout` milliseconds, this method will throw.
#### elementHandle.waitForSelector(selector[, options])
- `selector` <[string]> A selector to query for. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `options` <[Object]>
- `state` <"attached"|"detached"|"visible"|"hidden"> Defaults to `'visible'`. Can be either:
* `'attached'` - wait for element to be present in DOM.
* `'detached'` - wait for element to not be present in DOM.
* `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element without any content or with `display:none` has an empty bounding box and is not considered visible.
* `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or `visibility:hidden`. This is opposite to the `'visible'` option.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]<[null]|[ElementHandle]>>
Returns element specified by selector satisfies `state` option. Returns `null` if waiting for `hidden` or `detached`.
Wait for the `selector` relative to the element handle to satisfy `state` option (either appear/disappear from dom, or become visible/hidden). If at the moment of calling the method `selector` already satisfies the condition, the method will return immediately. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the function will throw.
```js
await page.setContent(`<div><span></span></div>`);
const div = await page.$('div');
// Waiting for the 'span' selector relative to the div.
const span = await div.waitForSelector('span', { state: 'attached' });
```
> **NOTE** This method does not work across navigations, use [page.waitForSelector(selector[, options])](api/class-page.md#pagewaitforselectorselector-options) instead.
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

103
docs/class-filechooser.md Normal file
View file

@ -0,0 +1,103 @@
---
id: class-filechooser
title: "class: FileChooser"
---
[FileChooser] objects are dispatched by the page in the [page.on('filechooser')](api/class-page.md#pageonfilechooser) event.
```js
page.on('filechooser', async (fileChooser) => {
await fileChooser.setFiles('/tmp/myfile.pdf');
});
```
- [fileChooser.element()](api/class-filechooser.md#filechooserelement)
- [fileChooser.isMultiple()](api/class-filechooser.md#filechooserismultiple)
- [fileChooser.page()](api/class-filechooser.md#filechooserpage)
- [fileChooser.setFiles(files[, options])](api/class-filechooser.md#filechoosersetfilesfiles-options)
#### fileChooser.element()
- returns: <[ElementHandle]>
Returns input element associated with this file chooser.
#### fileChooser.isMultiple()
- returns: <[boolean]>
Returns whether this file chooser accepts multiple files.
#### fileChooser.page()
- returns: <[Page]>
Returns page this file chooser belongs to.
#### fileChooser.setFiles(files[, options])
- `files` <[string]|[Array]<[string]>|[Object]|[Array]<[Object]>>
- `name` <[string]> [File] name **required**
- `mimeType` <[string]> [File] type **required**
- `buffer` <[Buffer]> File content **required**
- `options` <[Object]>
- `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
Sets the value of the file input this chooser is associated with. If some of the `filePaths` are relative paths, then they are resolved relative to the the current working directory. For empty array, clears the selected files.
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

View file

@ -0,0 +1,74 @@
---
id: class-firefoxbrowser
title: "class: FirefoxBrowser"
---
* extends: [Browser]
Firefox browser instance does not expose Firefox-specific features.
- [browser.on('disconnected')](api/class-browser.md#browserondisconnected)
- [browser.close()](api/class-browser.md#browserclose)
- [browser.contexts()](api/class-browser.md#browsercontexts)
- [browser.isConnected()](api/class-browser.md#browserisconnected)
- [browser.newContext([options])](api/class-browser.md#browsernewcontextoptions)
- [browser.newPage([options])](api/class-browser.md#browsernewpageoptions)
- [browser.version()](api/class-browser.md#browserversion)
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

784
docs/class-frame.md Normal file
View file

@ -0,0 +1,784 @@
---
id: class-frame
title: "class: Frame"
---
At every point of time, page exposes its current frame tree via the [page.mainFrame()](api/class-page.md#pagemainframe) and [frame.childFrames()](api/class-frame.md#framechildframes) methods.
[Frame] object's lifecycle is controlled by three events, dispatched on the page object:
* [page.on('frameattached')](api/class-page.md#pageonframeattached) - fired when the frame gets attached to the page. A Frame can be attached to the page only once.
* [page.on('framenavigated')](api/class-page.md#pageonframenavigated) - fired when the frame commits navigation to a different URL.
* [page.on('framedetached')](api/class-page.md#pageonframedetached) - fired when the frame gets detached from the page. A Frame can be detached from the page only once.
An example of dumping frame tree:
```js
const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
(async () => {
const browser = await firefox.launch();
const page = await browser.newPage();
await page.goto('https://www.google.com/chrome/browser/canary.html');
dumpFrameTree(page.mainFrame(), '');
await browser.close();
function dumpFrameTree(frame, indent) {
console.log(indent + frame.url());
for (const child of frame.childFrames()) {
dumpFrameTree(child, indent + ' ');
}
}
})();
```
An example of getting text from an iframe element:
```js
const frame = page.frames().find(frame => frame.name() === 'myframe');
const text = await frame.$eval('.selector', element => element.textContent);
console.log(text);
```
- [frame.$(selector)](api/class-frame.md#frameselector)
- [frame.$$(selector)](api/class-frame.md#frameselector-1)
- [frame.$eval(selector, pageFunction[, arg])](api/class-frame.md#frameevalselector-pagefunction-arg)
- [frame.$$eval(selector, pageFunction[, arg])](api/class-frame.md#frameevalselector-pagefunction-arg-1)
- [frame.addScriptTag(params)](api/class-frame.md#frameaddscripttagparams)
- [frame.addStyleTag(params)](api/class-frame.md#frameaddstyletagparams)
- [frame.check(selector[, options])](api/class-frame.md#framecheckselector-options)
- [frame.childFrames()](api/class-frame.md#framechildframes)
- [frame.click(selector[, options])](api/class-frame.md#frameclickselector-options)
- [frame.content()](api/class-frame.md#framecontent)
- [frame.dblclick(selector[, options])](api/class-frame.md#framedblclickselector-options)
- [frame.dispatchEvent(selector, type[, eventInit, options])](api/class-frame.md#framedispatcheventselector-type-eventinit-options)
- [frame.evaluate(pageFunction[, arg])](api/class-frame.md#frameevaluatepagefunction-arg)
- [frame.evaluateHandle(pageFunction[, arg])](api/class-frame.md#frameevaluatehandlepagefunction-arg)
- [frame.fill(selector, value[, options])](api/class-frame.md#framefillselector-value-options)
- [frame.focus(selector[, options])](api/class-frame.md#framefocusselector-options)
- [frame.frameElement()](api/class-frame.md#frameframeelement)
- [frame.getAttribute(selector, name[, options])](api/class-frame.md#framegetattributeselector-name-options)
- [frame.goto(url[, options])](api/class-frame.md#framegotourl-options)
- [frame.hover(selector[, options])](api/class-frame.md#framehoverselector-options)
- [frame.innerHTML(selector[, options])](api/class-frame.md#frameinnerhtmlselector-options)
- [frame.innerText(selector[, options])](api/class-frame.md#frameinnertextselector-options)
- [frame.isDetached()](api/class-frame.md#frameisdetached)
- [frame.name()](api/class-frame.md#framename)
- [frame.page()](api/class-frame.md#framepage)
- [frame.parentFrame()](api/class-frame.md#frameparentframe)
- [frame.press(selector, key[, options])](api/class-frame.md#framepressselector-key-options)
- [frame.selectOption(selector, values[, options])](api/class-frame.md#frameselectoptionselector-values-options)
- [frame.setContent(html[, options])](api/class-frame.md#framesetcontenthtml-options)
- [frame.setInputFiles(selector, files[, options])](api/class-frame.md#framesetinputfilesselector-files-options)
- [frame.tap(selector[, options])](api/class-frame.md#frametapselector-options)
- [frame.textContent(selector[, options])](api/class-frame.md#frametextcontentselector-options)
- [frame.title()](api/class-frame.md#frametitle)
- [frame.type(selector, text[, options])](api/class-frame.md#frametypeselector-text-options)
- [frame.uncheck(selector[, options])](api/class-frame.md#frameuncheckselector-options)
- [frame.url()](api/class-frame.md#frameurl)
- [frame.waitForFunction(pageFunction[, arg, options])](api/class-frame.md#framewaitforfunctionpagefunction-arg-options)
- [frame.waitForLoadState([state, options])](api/class-frame.md#framewaitforloadstatestate-options)
- [frame.waitForNavigation([options])](api/class-frame.md#framewaitfornavigationoptions)
- [frame.waitForSelector(selector[, options])](api/class-frame.md#framewaitforselectorselector-options)
- [frame.waitForTimeout(timeout)](api/class-frame.md#framewaitfortimeouttimeout)
#### frame.$(selector)
- `selector` <[string]> A selector to query for. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- returns: <[Promise]<[null]|[ElementHandle]>>
Returns the ElementHandle pointing to the frame element.
The method finds an element matching the specified selector within the frame. See [Working with selectors](./selectors.md#working-with-selectors) for more details. If no elements match the selector, returns `null`.
#### frame.$$(selector)
- `selector` <[string]> A selector to query for. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- returns: <[Promise]<[Array]<[ElementHandle]>>>
Returns the ElementHandles pointing to the frame elements.
The method finds all elements matching the specified selector within the frame. See [Working with selectors](./selectors.md#working-with-selectors) for more details. If no elements match the selector, returns empty array.
#### frame.$eval(selector, pageFunction[, arg])
- `selector` <[string]> A selector to query for. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `pageFunction` <[function]\([Element]\)> Function to be evaluated in browser context
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>>
Returns the return value of `pageFunction`
The method finds an element matching the specified selector within the frame and passes it as a first argument to `pageFunction`. See [Working with selectors](./selectors.md#working-with-selectors) for more details. If no elements match the selector, the method throws an error.
If `pageFunction` returns a [Promise], then `frame.$eval` would wait for the promise to resolve and return its value.
Examples:
```js
const searchValue = await frame.$eval('#search', el => el.value);
const preloadHref = await frame.$eval('link[rel=preload]', el => el.href);
const html = await frame.$eval('.main-container', (e, suffix) => e.outerHTML + suffix, 'hello');
```
#### frame.$$eval(selector, pageFunction[, arg])
- `selector` <[string]> A selector to query for. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `pageFunction` <[function]\([Array]<[Element]>\)> Function to be evaluated in browser context
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>>
Returns the return value of `pageFunction`
The method finds all elements matching the specified selector within the frame and passes an array of matched elements as a first argument to `pageFunction`. See [Working with selectors](./selectors.md#working-with-selectors) for more details.
If `pageFunction` returns a [Promise], then `frame.$$eval` would wait for the promise to resolve and return its value.
Examples:
```js
const divsCounts = await frame.$$eval('div', (divs, min) => divs.length >= min, 10);
```
#### frame.addScriptTag(params)
- `params` <[Object]>
- `url` <[string]> URL of a script to be added. Optional.
- `path` <[string]> Path to the JavaScript file to be injected into frame. If `path` is a relative path, then it is resolved relative to the current working directory. Optional.
- `content` <[string]> Raw JavaScript content to be injected into frame. Optional.
- `type` <[string]> Script type. Use 'module' in order to load a Javascript ES6 module. See [script](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) for more details. Optional.
- returns: <[Promise]<[ElementHandle]>>
Returns the added tag when the script's onload fires or when the script content was injected into frame.
Adds a `<script>` tag into the page with the desired url or content.
#### frame.addStyleTag(params)
- `params` <[Object]>
- `url` <[string]> URL of the `<link>` tag. Optional.
- `path` <[string]> Path to the CSS file to be injected into frame. If `path` is a relative path, then it is resolved relative to the current working directory. Optional.
- `content` <[string]> Raw CSS content to be injected into frame. Optional.
- returns: <[Promise]<[ElementHandle]>>
Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
Adds a `<link rel="stylesheet">` tag into the page with the desired url or a `<style type="text/css">` tag with the content.
#### frame.check(selector[, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `options` <[Object]>
- `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
- `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
This method checks an element matching `selector` by performing the following steps:
1. Find an element match matching `selector`. If there is none, wait until a matching element is attached to the DOM.
1. Ensure that matched element is a checkbox or a radio input. If not, this method rejects. If the element is already checked, this method returns immediately.
1. Wait for [actionability](./actionability.md) checks on the matched element, unless `force` option is set. If the element is detached during the checks, the whole action is retried.
1. Scroll the element into view if needed.
1. Use [page.mouse](api/class-page.md#pagemouse) to click in the center of the element.
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
1. Ensure that the element is now checked. If not, this method rejects.
When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
#### frame.childFrames()
- returns: <[Array]<[Frame]>>
#### frame.click(selector[, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `options` <[Object]>
- `button` <"left"|"right"|"middle"> Defaults to `left`.
- `clickCount` <[number]> defaults to 1. See [UIEvent.detail].
- `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
- `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
- `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used.
- `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
- `position` <[Object]> A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.
- `x` <[number]>
- `y` <[number]>
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
This method clicks an element matching `selector` by performing the following steps:
1. Find an element match matching `selector`. If there is none, wait until a matching element is attached to the DOM.
1. Wait for [actionability](./actionability.md) checks on the matched element, unless `force` option is set. If the element is detached during the checks, the whole action is retried.
1. Scroll the element into view if needed.
1. Use [page.mouse](api/class-page.md#pagemouse) to click in the center of the element, or the specified `position`.
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
#### frame.content()
- returns: <[Promise]<[string]>>
Gets the full HTML contents of the frame, including the doctype.
#### frame.dblclick(selector[, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `options` <[Object]>
- `button` <"left"|"right"|"middle"> Defaults to `left`.
- `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
- `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
- `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used.
- `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
- `position` <[Object]> A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.
- `x` <[number]>
- `y` <[number]>
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
This method double clicks an element matching `selector` by performing the following steps:
1. Find an element match matching `selector`. If there is none, wait until a matching element is attached to the DOM.
1. Wait for [actionability](./actionability.md) checks on the matched element, unless `force` option is set. If the element is detached during the checks, the whole action is retried.
1. Scroll the element into view if needed.
1. Use [page.mouse](api/class-page.md#pagemouse) to double click in the center of the element, or the specified `position`.
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set. Note that if the first click of the `dblclick()` triggers a navigation event, this method will reject.
When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
> **NOTE** `frame.dblclick()` dispatches two `click` events and a single `dblclick` event.
#### frame.dispatchEvent(selector, type[, eventInit, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `type` <[string]> DOM event type: `"click"`, `"dragstart"`, etc.
- `eventInit` <[EvaluationArgument]> Optional event-specific initialization properties.
- `options` <[Object]>
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
The snippet below dispatches the `click` event on the element. Regardless of the visibility state of the elment, `click` is dispatched. This is equivalend to calling [element.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click).
```js
await frame.dispatchEvent('button#submit', 'click');
```
Under the hood, it creates an instance of an event based on the given `type`, initializes it with `eventInit` properties and dispatches it on the element. Events are `composed`, `cancelable` and bubble by default.
Since `eventInit` is event-specific, please refer to the events documentation for the lists of initial properties:
* [DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent/DragEvent)
* [FocusEvent](https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/FocusEvent)
* [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent)
* [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent)
* [PointerEvent](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/PointerEvent)
* [TouchEvent](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent)
* [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event)
You can also specify `JSHandle` as the property value if you want live objects to be passed into the event:
```js
// Note you can only create DataTransfer in Chromium and Firefox
const dataTransfer = await frame.evaluateHandle(() => new DataTransfer());
await frame.dispatchEvent('#source', 'dragstart', { dataTransfer });
```
#### frame.evaluate(pageFunction[, arg])
- `pageFunction` <[function]|[string]> Function to be evaluated in browser context
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>>
Returns the return value of `pageFunction`
If the function passed to the `frame.evaluate` returns a [Promise], then `frame.evaluate` would wait for the promise to resolve and return its value.
If the function passed to the `frame.evaluate` returns a non-[Serializable] value, then `frame.evaluate` returns `undefined`. DevTools Protocol also supports transferring some additional values that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.
```js
const result = await frame.evaluate(([x, y]) => {
return Promise.resolve(x * y);
}, [7, 8]);
console.log(result); // prints "56"
```
A string can also be passed in instead of a function.
```js
console.log(await frame.evaluate('1 + 2')); // prints "3"
```
[ElementHandle] instances can be passed as an argument to the `frame.evaluate`:
```js
const bodyHandle = await frame.$('body');
const html = await frame.evaluate(([body, suffix]) => body.innerHTML + suffix, [bodyHandle, 'hello']);
await bodyHandle.dispose();
```
#### frame.evaluateHandle(pageFunction[, arg])
- `pageFunction` <[function]|[string]> Function to be evaluated in the page context
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[JSHandle]>>
Returns the return value of `pageFunction` as in-page object (JSHandle).
The only difference between `frame.evaluate` and `frame.evaluateHandle` is that `frame.evaluateHandle` returns in-page object (JSHandle).
If the function, passed to the `frame.evaluateHandle`, returns a [Promise], then `frame.evaluateHandle` would wait for the promise to resolve and return its value.
```js
const aWindowHandle = await frame.evaluateHandle(() => Promise.resolve(window));
aWindowHandle; // Handle for the window object.
```
A string can also be passed in instead of a function.
```js
const aHandle = await frame.evaluateHandle('document'); // Handle for the 'document'.
```
[JSHandle] instances can be passed as an argument to the `frame.evaluateHandle`:
```js
const aHandle = await frame.evaluateHandle(() => document.body);
const resultHandle = await frame.evaluateHandle(([body, suffix]) => body.innerHTML + suffix, [aHandle, 'hello']);
console.log(await resultHandle.jsonValue());
await resultHandle.dispose();
```
#### frame.fill(selector, value[, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `value` <[string]> Value to fill for the `<input>`, `<textarea>` or `[contenteditable]` element.
- `options` <[Object]>
- `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
This method waits for an element matching `selector`, waits for [actionability](./actionability.md) checks, focuses the element, fills it and triggers an `input` event after filling. If the element matching `selector` is not an `<input>`, `<textarea>` or `[contenteditable]` element, this method throws an error. Note that you can pass an empty string to clear the input field.
To send fine-grained keyboard events, use [frame.type(selector, text[, options])](api/class-frame.md#frametypeselector-text-options).
#### frame.focus(selector[, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `options` <[Object]>
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
This method fetches an element with `selector` and focuses it. If there's no element matching `selector`, the method waits until a matching element appears in the DOM.
#### frame.frameElement()
- returns: <[Promise]<[ElementHandle]>>
Returns the `frame` or `iframe` element handle which corresponds to this frame.
This is an inverse of [elementHandle.contentFrame()](api/class-elementhandle.md#elementhandlecontentframe). Note that returned handle actually belongs to the parent frame.
This method throws an error if the frame has been detached before `frameElement()` returns.
```js
const frameElement = await frame.frameElement();
const contentFrame = await frameElement.contentFrame();
console.log(frame === contentFrame); // -> true
```
#### frame.getAttribute(selector, name[, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `name` <[string]> Attribute name to get the value for.
- `options` <[Object]>
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]<[null]|[string]>>
Returns element attribute value.
#### frame.goto(url[, options])
- `url` <[string]> URL to navigate frame to. The url should include scheme, e.g. `https://`.
- `options` <[Object]>
- `referer` <[string]> Referer header value. If provided it will take preference over the referer header value set by [page.setExtraHTTPHeaders(headers)](api/class-page.md#pagesetextrahttpheadersheaders).
- `timeout` <[number]> Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](api/class-page.md#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- `waitUntil` <"load"|"domcontentloaded"|"networkidle"> When to consider operation succeeded, defaults to `load`. Events can be either:
* `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
* `'load'` - consider operation to be finished when the `load` event is fired.
* `'networkidle'` - consider operation to be finished when there are no network connections for at least `500` ms.
- returns: <[Promise]<[null]|[Response]>>
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
`frame.goto` will throw an error if:
* there's an SSL error (e.g. in case of self-signed certificates).
* target URL is invalid.
* the `timeout` is exceeded during navigation.
* the remote server does not respond or is unreachable.
* the main resource failed to load.
`frame.goto` will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling [response.status()](api/class-response.md#responsestatus).
> **NOTE** `frame.goto` either throws an error or returns a main resource response. The only exceptions are navigation to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
> **NOTE** Headless mode doesn't support navigation to a PDF document. See the [upstream issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).
#### frame.hover(selector[, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `options` <[Object]>
- `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
- `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used.
- `position` <[Object]> A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.
- `x` <[number]>
- `y` <[number]>
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
This method hovers over an element matching `selector` by performing the following steps:
1. Find an element match matching `selector`. If there is none, wait until a matching element is attached to the DOM.
1. Wait for [actionability](./actionability.md) checks on the matched element, unless `force` option is set. If the element is detached during the checks, the whole action is retried.
1. Scroll the element into view if needed.
1. Use [page.mouse](api/class-page.md#pagemouse) to hover over the center of the element, or the specified `position`.
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
#### frame.innerHTML(selector[, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `options` <[Object]>
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]<[string]>>
Returns `element.innerHTML`.
#### frame.innerText(selector[, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `options` <[Object]>
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]<[string]>>
Returns `element.innerText`.
#### frame.isDetached()
- returns: <[boolean]>
Returns `true` if the frame has been detached, or `false` otherwise.
#### frame.name()
- returns: <[string]>
Returns frame's name attribute as specified in the tag.
If the name is empty, returns the id attribute instead.
> **NOTE** This value is calculated once when the frame is created, and will not update if the attribute is changed later.
#### frame.page()
- returns: <[Page]>
Returns the page containing this frame.
#### frame.parentFrame()
- returns: <[null]|[Frame]>
Parent frame, if any. Detached frames and main frames return `null`.
#### frame.press(selector, key[, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `key` <[string]> Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
- `options` <[Object]>
- `delay` <[number]> Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
- `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
`key` can specify the intended [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character to generate the text for. A superset of the `key` values can be found [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
`F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`, `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`, etc.
Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective texts.
Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When speficied with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
#### frame.selectOption(selector, values[, options])
- `selector` <[string]> A selector to query for. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `values` <[null]|[string]|[ElementHandle]|[Array]<[string]>|[Object]|[Array]<[ElementHandle]>|[Array]<[Object]>> Options to select. If the `<select>` has the `multiple` attribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are equivalent to `{value:'string'}`. Option is considered matching if all specified properties match.
- `value` <[string]> Matches by `option.value`. Optional.
- `label` <[string]> Matches by `option.label`. Optional.
- `index` <[number]> Matches by the index. Optional.
- `options` <[Object]>
- `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]<[Array]<[string]>>>
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. If there's no `<select>` element matching `selector`, the method throws an error.
```js
// single selection matching the value
frame.selectOption('select#colors', 'blue');
// single selection matching both the value and the label
frame.selectOption('select#colors', { label: 'Blue' });
// multiple selection
frame.selectOption('select#colors', 'red', 'green', 'blue');
```
#### frame.setContent(html[, options])
- `html` <[string]> HTML markup to assign to the page.
- `options` <[Object]>
- `timeout` <[number]> Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](api/class-page.md#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- `waitUntil` <"load"|"domcontentloaded"|"networkidle"> When to consider operation succeeded, defaults to `load`. Events can be either:
* `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
* `'load'` - consider operation to be finished when the `load` event is fired.
* `'networkidle'` - consider operation to be finished when there are no network connections for at least `500` ms.
- returns: <[Promise]>
#### frame.setInputFiles(selector, files[, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `files` <[string]|[Array]<[string]>|[Object]|[Array]<[Object]>>
- `name` <[string]> [File] name **required**
- `mimeType` <[string]> [File] type **required**
- `buffer` <[Buffer]> File content **required**
- `options` <[Object]>
- `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
This method expects `selector` to point to an [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then they are resolved relative to the the current working directory. For empty array, clears the selected files.
#### frame.tap(selector[, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `options` <[Object]>
- `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
- `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the operation, and then restores current modifiers back. If not specified, currently pressed modifiers are used.
- `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
- `position` <[Object]> A point to use relative to the top-left corner of element padding box. If not specified, uses some visible point of the element.
- `x` <[number]>
- `y` <[number]>
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
This method taps an element matching `selector` by performing the following steps:
1. Find an element match matching `selector`. If there is none, wait until a matching element is attached to the DOM.
1. Wait for [actionability](./actionability.md) checks on the matched element, unless `force` option is set. If the element is detached during the checks, the whole action is retried.
1. Scroll the element into view if needed.
1. Use [page.touchscreen](api/class-page.md#pagetouchscreen) to tap the center of the element, or the specified `position`.
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
> **NOTE** `frame.tap()` requires that the `hasTouch` option of the browser context be set to true.
#### frame.textContent(selector[, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `options` <[Object]>
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]<[null]|[string]>>
Returns `element.textContent`.
#### frame.title()
- returns: <[Promise]<[string]>>
Returns the page title.
#### frame.type(selector, text[, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `text` <[string]> A text to type into a focused element.
- `options` <[Object]>
- `delay` <[number]> Time to wait between key presses in milliseconds. Defaults to 0.
- `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text. `frame.type` can be used to send fine-grained keyboard events. To fill values in form fields, use [frame.fill(selector, value[, options])](api/class-frame.md#framefillselector-value-options).
To press a special key, like `Control` or `ArrowDown`, use [keyboard.press(key[, options])](api/class-keyboard.md#keyboardpresskey-options).
```js
await frame.type('#mytextarea', 'Hello'); // Types instantly
await frame.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user
```
#### frame.uncheck(selector[, options])
- `selector` <[string]> A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `options` <[Object]>
- `force` <[boolean]> Whether to bypass the [actionability](./actionability.md) checks. Defaults to `false`.
- `noWaitAfter` <[boolean]> Actions that initiate navigations are waiting for these navigations to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to `false`.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
This method checks an element matching `selector` by performing the following steps:
1. Find an element match matching `selector`. If there is none, wait until a matching element is attached to the DOM.
1. Ensure that matched element is a checkbox or a radio input. If not, this method rejects. If the element is already unchecked, this method returns immediately.
1. Wait for [actionability](./actionability.md) checks on the matched element, unless `force` option is set. If the element is detached during the checks, the whole action is retried.
1. Scroll the element into view if needed.
1. Use [page.mouse](api/class-page.md#pagemouse) to click in the center of the element.
1. Wait for initiated navigations to either succeed or fail, unless `noWaitAfter` option is set.
1. Ensure that the element is now unchecked. If not, this method rejects.
When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. Passing zero timeout disables this.
#### frame.url()
- returns: <[string]>
Returns frame's url.
#### frame.waitForFunction(pageFunction[, arg, options])
- `pageFunction` <[function]|[string]> Function to be evaluated in browser context
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- `options` <[Object]>
- `polling` <[number]|"raf"> If `polling` is `'raf'`, then `pageFunction` is constantly executed in `requestAnimationFrame` callback. If `polling` is a number, then it is treated as an interval in milliseconds at which the function would be executed. Defaults to `raf`.
- `timeout` <[number]> maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout).
- returns: <[Promise]<[JSHandle]>>
Returns when the `pageFunction` returns a truthy value, returns that value.
The `waitForFunction` can be used to observe viewport size change:
```js
const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
(async () => {
const browser = await firefox.launch();
const page = await browser.newPage();
const watchDog = page.mainFrame().waitForFunction('window.innerWidth < 100');
page.setViewportSize({width: 50, height: 50});
await watchDog;
await browser.close();
})();
```
To pass an argument to the predicate of `frame.waitForFunction` function:
```js
const selector = '.foo';
await frame.waitForFunction(selector => !!document.querySelector(selector), selector);
```
#### frame.waitForLoadState([state, options])
- `state` <"load"|"domcontentloaded"|"networkidle"> Optional load state to wait for, defaults to `load`. If the state has been already reached while loading current document, the method returns immediately. Can be one of:
* `'load'` - wait for the `load` event to be fired.
* `'domcontentloaded'` - wait for the `DOMContentLoaded` event to be fired.
* `'networkidle'` - wait until there are no network connections for at least `500` ms.
- `options` <[Object]>
- `timeout` <[number]> Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](api/class-page.md#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>
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 when this method is called. If current document has already reached the required state, resolves immediately.
```js
await frame.click('button'); // Click triggers navigation.
await frame.waitForLoadState(); // Waits for 'load' state by default.
```
#### frame.waitForNavigation([options])
- `options` <[Object]>
- `timeout` <[number]> Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultNavigationTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaultnavigationtimeouttimeout), [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout), [page.setDefaultNavigationTimeout(timeout)](api/class-page.md#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- `url` <[string]|[RegExp]|[Function]> URL string, URL regex pattern or predicate receiving [URL] to match while waiting for the navigation.
- `waitUntil` <"load"|"domcontentloaded"|"networkidle"> When to consider operation succeeded, defaults to `load`. Events can be either:
* `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
* `'load'` - consider operation to be finished when the `load` event is fired.
* `'networkidle'` - consider operation to be finished when there are no network connections for at least `500` ms.
- returns: <[Promise]<[null]|[Response]>>
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with `null`.
This 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:
```js
const [response] = await Promise.all([
frame.waitForNavigation(), // Wait for the navigation to finish
frame.click('a.my-link'), // Clicking the link will indirectly cause a navigation
]);
```
**NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL is considered a navigation.
#### frame.waitForSelector(selector[, options])
- `selector` <[string]> A selector to query for. See [working with selectors](./selectors.md#working-with-selectors) for more details.
- `options` <[Object]>
- `state` <"attached"|"detached"|"visible"|"hidden"> Defaults to `'visible'`. Can be either:
* `'attached'` - wait for element to be present in DOM.
* `'detached'` - wait for element to not be present in DOM.
* `'visible'` - wait for element to have non-empty bounding box and no `visibility:hidden`. Note that element without any content or with `display:none` has an empty bounding box and is not considered visible.
* `'hidden'` - wait for element to be either detached from DOM, or have an empty bounding box or `visibility:hidden`. This is opposite to the `'visible'` option.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](api/class-page.md#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]<[null]|[ElementHandle]>>
Returns when element specified by selector satisfies `state` option. Returns `null` if waiting for `hidden` or `detached`.
Wait for the `selector` to satisfy `state` option (either appear/disappear from dom, or become visible/hidden). If at the moment of calling the method `selector` already satisfies the condition, the method will return immediately. If the selector doesn't satisfy the condition for the `timeout` milliseconds, the function will throw.
This method works across navigations:
```js
const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
(async () => {
const browser = await webkit.launch();
const page = await browser.newPage();
let currentURL;
page.mainFrame()
.waitForSelector('img')
.then(() => console.log('First URL with image: ' + currentURL));
for (currentURL of ['https://example.com', 'https://google.com', 'https://bbc.com']) {
await page.goto(currentURL);
}
await browser.close();
})();
```
#### frame.waitForTimeout(timeout)
- `timeout` <[number]> A timeout to wait for
- returns: <[Promise]>
Waits for the given `timeout` in milliseconds.
Note that `frame.waitForTimeout()` should only be used for debugging. Tests using the timer in production are going to be flaky. Use signals such as network events, selectors becoming visible and others instead.
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

151
docs/class-jshandle.md Normal file
View file

@ -0,0 +1,151 @@
---
id: class-jshandle
title: "class: JSHandle"
---
JSHandle represents an in-page JavaScript object. JSHandles can be created with the [page.evaluateHandle(pageFunction[, arg])](api/class-page.md#pageevaluatehandlepagefunction-arg) method.
```js
const windowHandle = await page.evaluateHandle(() => window);
// ...
```
JSHandle prevents the referenced JavaScript object being garbage collected unless the handle is exposed with [jsHandle.dispose()](api/class-jshandle.md#jshandledispose). JSHandles are auto-disposed when their origin frame gets navigated or the parent context gets destroyed.
JSHandle instances can be used as an argument in [page.$eval(selector, pageFunction[, arg])](api/class-page.md#pageevalselector-pagefunction-arg), [page.evaluate(pageFunction[, arg])](api/class-page.md#pageevaluatepagefunction-arg) and [page.evaluateHandle(pageFunction[, arg])](api/class-page.md#pageevaluatehandlepagefunction-arg) methods.
- [jsHandle.asElement()](api/class-jshandle.md#jshandleaselement)
- [jsHandle.dispose()](api/class-jshandle.md#jshandledispose)
- [jsHandle.evaluate(pageFunction[, arg])](api/class-jshandle.md#jshandleevaluatepagefunction-arg)
- [jsHandle.evaluateHandle(pageFunction[, arg])](api/class-jshandle.md#jshandleevaluatehandlepagefunction-arg)
- [jsHandle.getProperties()](api/class-jshandle.md#jshandlegetproperties)
- [jsHandle.getProperty(propertyName)](api/class-jshandle.md#jshandlegetpropertypropertyname)
- [jsHandle.jsonValue()](api/class-jshandle.md#jshandlejsonvalue)
#### jsHandle.asElement()
- returns: <[null]|[ElementHandle]>
Returns either `null` or the object handle itself, if the object handle is an instance of [ElementHandle].
#### jsHandle.dispose()
- returns: <[Promise]>
The `jsHandle.dispose` method stops referencing the element handle.
#### jsHandle.evaluate(pageFunction[, arg])
- `pageFunction` <[function]> Function to be evaluated in browser context
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>>
Returns the return value of `pageFunction`
This method passes this handle as the first argument to `pageFunction`.
If `pageFunction` returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return its value.
Examples:
```js
const tweetHandle = await page.$('.tweet .retweets');
expect(await tweetHandle.evaluate((node, suffix) => node.innerText, ' retweets')).toBe('10 retweets');
```
#### jsHandle.evaluateHandle(pageFunction[, arg])
- `pageFunction` <[function]|[string]> Function to be evaluated
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[JSHandle]>>
Returns the return value of `pageFunction` as in-page object (JSHandle).
This method passes this handle as the first argument to `pageFunction`.
The only difference between `jsHandle.evaluate` and `jsHandle.evaluateHandle` is that `jsHandle.evaluateHandle` returns in-page object (JSHandle).
If the function passed to the `jsHandle.evaluateHandle` returns a [Promise], then `jsHandle.evaluateHandle` would wait for the promise to resolve and return its value.
See [page.evaluateHandle(pageFunction[, arg])](api/class-page.md#pageevaluatehandlepagefunction-arg) for more details.
#### jsHandle.getProperties()
- returns: <[Promise]<[Map]<[string], [JSHandle]>>>
The method returns a map with **own property names** as keys and JSHandle instances for the property values.
```js
const handle = await page.evaluateHandle(() => ({window, document}));
const properties = await handle.getProperties();
const windowHandle = properties.get('window');
const documentHandle = properties.get('document');
await handle.dispose();
```
#### jsHandle.getProperty(propertyName)
- `propertyName` <[string]> property to get
- returns: <[Promise]<[JSHandle]>>
Fetches a single property from the referenced object.
#### jsHandle.jsonValue()
- returns: <[Promise]<[Serializable]>>
Returns a JSON representation of the object. If the object has a `toJSON` function, it **will not be called**.
> **NOTE** The method will return an empty JSON object if the referenced object is not stringifiable. It will throw an error if the object has circular references.
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

194
docs/class-keyboard.md Normal file
View file

@ -0,0 +1,194 @@
---
id: class-keyboard
title: "class: Keyboard"
---
Keyboard provides an api for managing a virtual keyboard. The high level api is [keyboard.type(text[, options])](api/class-keyboard.md#keyboardtypetext-options), which takes raw characters and generates proper keydown, keypress/input, and keyup events on your page.
For finer control, you can use [keyboard.down(key)](api/class-keyboard.md#keyboarddownkey), [keyboard.up(key)](api/class-keyboard.md#keyboardupkey), and [keyboard.insertText(text)](api/class-keyboard.md#keyboardinserttexttext) to manually fire events as if they were generated from a real keyboard.
An example of holding down `Shift` in order to select and delete some text:
```js
await page.keyboard.type('Hello World!');
await page.keyboard.press('ArrowLeft');
await page.keyboard.down('Shift');
for (let i = 0; i < ' World'.length; i++)
await page.keyboard.press('ArrowLeft');
await page.keyboard.up('Shift');
await page.keyboard.press('Backspace');
// Result text will end up saying 'Hello!'
```
An example of pressing uppercase `A`
```js
await page.keyboard.press('Shift+KeyA');
// or
await page.keyboard.press('Shift+A');
```
An example to trigger select-all with the keyboard
```js
// on Windows and Linux
await page.keyboard.press('Control+A');
// on macOS
await page.keyboard.press('Meta+A');
```
- [keyboard.down(key)](api/class-keyboard.md#keyboarddownkey)
- [keyboard.insertText(text)](api/class-keyboard.md#keyboardinserttexttext)
- [keyboard.press(key[, options])](api/class-keyboard.md#keyboardpresskey-options)
- [keyboard.type(text[, options])](api/class-keyboard.md#keyboardtypetext-options)
- [keyboard.up(key)](api/class-keyboard.md#keyboardupkey)
#### keyboard.down(key)
- `key` <[string]> Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
- returns: <[Promise]>
Dispatches a `keydown` event.
`key` can specify the intended [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character to generate the text for. A superset of the `key` values can be found [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
`F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`, `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`, etc.
Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective texts.
If `key` is a modifier key, `Shift`, `Meta`, `Control`, or `Alt`, subsequent key presses will be sent with that modifier active. To release the modifier key, use [keyboard.up(key)](api/class-keyboard.md#keyboardupkey).
After the key is pressed once, subsequent calls to [keyboard.down(key)](api/class-keyboard.md#keyboarddownkey) will have [repeat](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat) set to true. To release the key, use [keyboard.up(key)](api/class-keyboard.md#keyboardupkey).
> **NOTE** Modifier keys DO influence `keyboard.down`. Holding down `Shift` will type the text in upper case.
#### keyboard.insertText(text)
- `text` <[string]> Sets input to the specified text value.
- returns: <[Promise]>
Dispatches only `input` event, does not emit the `keydown`, `keyup` or `keypress` events.
```js
page.keyboard.insertText('嗨');
```
> **NOTE** Modifier keys DO NOT effect `keyboard.insertText`. Holding down `Shift` will not type the text in upper case.
#### keyboard.press(key[, options])
- `key` <[string]> Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
- `options` <[Object]>
- `delay` <[number]> Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.
- returns: <[Promise]>
`key` can specify the intended [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) value or a single character to generate the text for. A superset of the `key` values can be found [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
`F1` - `F12`, `Digit0`- `Digit9`, `KeyA`- `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`, `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`, etc.
Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta`, `ShiftLeft`.
Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective texts.
Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When speficied with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
```js
const page = await browser.newPage();
await page.goto('https://keycode.info');
await page.keyboard.press('A');
await page.screenshot({ path: 'A.png' });
await page.keyboard.press('ArrowLeft');
await page.screenshot({ path: 'ArrowLeft.png' });
await page.keyboard.press('Shift+O');
await page.screenshot({ path: 'O.png' });
await browser.close();
```
Shortcut for [keyboard.down(key)](api/class-keyboard.md#keyboarddownkey) and [keyboard.up(key)](api/class-keyboard.md#keyboardupkey).
#### keyboard.type(text[, options])
- `text` <[string]> A text to type into a focused element.
- `options` <[Object]>
- `delay` <[number]> Time to wait between key presses in milliseconds. Defaults to 0.
- returns: <[Promise]>
Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text.
To press a special key, like `Control` or `ArrowDown`, use [keyboard.press(key[, options])](api/class-keyboard.md#keyboardpresskey-options).
```js
await page.keyboard.type('Hello'); // Types instantly
await page.keyboard.type('World', {delay: 100}); // Types slower, like a user
```
> **NOTE** Modifier keys DO NOT effect `keyboard.type`. Holding down `Shift` will not type the text in upper case.
#### keyboard.up(key)
- `key` <[string]> Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
- returns: <[Promise]>
Dispatches a `keyup` event.
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

97
docs/class-logger.md Normal file
View file

@ -0,0 +1,97 @@
---
id: class-logger
title: "class: Logger"
---
Playwright generates a lot of logs and they are accessible via the pluggable logger sink.
```js
const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
(async () => {
const browser = await chromium.launch({
logger: {
isEnabled: (name, severity) => name === 'browser',
log: (name, severity, message, args) => console.log(`${name} ${message}`)
}
});
...
})();
```
- [logger.isEnabled(name, severity)](api/class-logger.md#loggerisenabledname-severity)
- [logger.log(name, severity, message, args, hints)](api/class-logger.md#loggerlogname-severity-message-args-hints)
#### logger.isEnabled(name, severity)
- `name` <[string]> logger name
- `severity` <"verbose"|"info"|"warning"|"error">
- returns: <[boolean]>
Determines whether sink is interested in the logger with the given name and severity.
#### logger.log(name, severity, message, args, hints)
- `name` <[string]> logger name
- `severity` <"verbose"|"info"|"warning"|"error">
- `message` <[string]|[Error]> log message format
- `args` <[Array]<[Object]>> message arguments
- `hints` <[Object]> optional formatting hints
- `color` <[string]> Optional preferred logger color.
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

130
docs/class-mouse.md Normal file
View file

@ -0,0 +1,130 @@
---
id: class-mouse
title: "class: Mouse"
---
The Mouse class operates in main-frame CSS pixels relative to the top-left corner of the viewport.
Every `page` object has its own Mouse, accessible with [page.mouse](api/class-page.md#pagemouse).
```js
// Using page.mouse to trace a 100x100 square.
await page.mouse.move(0, 0);
await page.mouse.down();
await page.mouse.move(0, 100);
await page.mouse.move(100, 100);
await page.mouse.move(100, 0);
await page.mouse.move(0, 0);
await page.mouse.up();
```
- [mouse.click(x, y[, options])](api/class-mouse.md#mouseclickx-y-options)
- [mouse.dblclick(x, y[, options])](api/class-mouse.md#mousedblclickx-y-options)
- [mouse.down([options])](api/class-mouse.md#mousedownoptions)
- [mouse.move(x, y[, options])](api/class-mouse.md#mousemovex-y-options)
- [mouse.up([options])](api/class-mouse.md#mouseupoptions)
#### mouse.click(x, y[, options])
- `x` <[number]>
- `y` <[number]>
- `options` <[Object]>
- `button` <"left"|"right"|"middle"> Defaults to `left`.
- `clickCount` <[number]> defaults to 1. See [UIEvent.detail].
- `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
- returns: <[Promise]>
Shortcut for [mouse.move(x, y[, options])](api/class-mouse.md#mousemovex-y-options), [mouse.down([options])](api/class-mouse.md#mousedownoptions), [mouse.up([options])](api/class-mouse.md#mouseupoptions).
#### mouse.dblclick(x, y[, options])
- `x` <[number]>
- `y` <[number]>
- `options` <[Object]>
- `button` <"left"|"right"|"middle"> Defaults to `left`.
- `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.
- returns: <[Promise]>
Shortcut for [mouse.move(x, y[, options])](api/class-mouse.md#mousemovex-y-options), [mouse.down([options])](api/class-mouse.md#mousedownoptions), [mouse.up([options])](api/class-mouse.md#mouseupoptions), [mouse.down([options])](api/class-mouse.md#mousedownoptions) and [mouse.up([options])](api/class-mouse.md#mouseupoptions).
#### mouse.down([options])
- `options` <[Object]>
- `button` <"left"|"right"|"middle"> Defaults to `left`.
- `clickCount` <[number]> defaults to 1. See [UIEvent.detail].
- returns: <[Promise]>
Dispatches a `mousedown` event.
#### mouse.move(x, y[, options])
- `x` <[number]>
- `y` <[number]>
- `options` <[Object]>
- `steps` <[number]> defaults to 1. Sends intermediate `mousemove` events.
- returns: <[Promise]>
Dispatches a `mousemove` event.
#### mouse.up([options])
- `options` <[Object]>
- `button` <"left"|"right"|"middle"> Defaults to `left`.
- `clickCount` <[number]> defaults to 1. See [UIEvent.detail].
- returns: <[Promise]>
Dispatches a `mouseup` event.
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

1525
docs/class-page.md Normal file

File diff suppressed because it is too large Load diff

147
docs/class-playwright.md Normal file
View file

@ -0,0 +1,147 @@
---
id: class-playwright
title: "class: Playwright"
---
Playwright module provides a method to launch a browser instance. The following is a typical example of using Playwright to drive automation:
```js
const { chromium, firefox, webkit } = require('playwright');
(async () => {
const browser = await chromium.launch(); // Or 'firefox' or 'webkit'.
const page = await browser.newPage();
await page.goto('http://example.com');
// other actions...
await browser.close();
})();
```
By default, the `playwright` NPM package automatically downloads browser executables during installation. The `playwright-core` NPM package can be used to skip automatic downloads.
- [playwright.chromium](api/class-playwright.md#playwrightchromium)
- [playwright.devices](api/class-playwright.md#playwrightdevices)
- [playwright.errors](api/class-playwright.md#playwrighterrors)
- [playwright.firefox](api/class-playwright.md#playwrightfirefox)
- [playwright.selectors](api/class-playwright.md#playwrightselectors)
- [playwright.webkit](api/class-playwright.md#playwrightwebkit)
#### playwright.chromium
- type: <[BrowserType]>
This object can be used to launch or connect to Chromium, returning instances of [ChromiumBrowser].
#### playwright.devices
- type: <[Object]>
Returns a list of devices to be used with [browser.newContext([options])](api/class-browser.md#browsernewcontextoptions) or [browser.newPage([options])](api/class-browser.md#browsernewpageoptions). Actual list of devices can be found in [src/server/deviceDescriptors.ts](https://github.com/Microsoft/playwright/blob/master/src/server/deviceDescriptors.ts).
```js
const { webkit, devices } = require('playwright');
const iPhone = devices['iPhone 6'];
(async () => {
const browser = await webkit.launch();
const context = await browser.newContext({
...iPhone
});
const page = await context.newPage();
await page.goto('http://example.com');
// other actions...
await browser.close();
})();
```
#### playwright.errors
- type: <[Object]>
- `TimeoutError` <[function]> A class of [TimeoutError].
Playwright methods might throw errors if they are unable to fulfill a request. For example, [page.waitForSelector(selector[, options])](api/class-page.md#pagewaitforselectorselector-options) might fail if the selector doesn't match any nodes during the given timeframe.
For certain types of errors Playwright uses specific error classes. These classes are available via [`playwright.errors`](#playwrighterrors).
An example of handling a timeout error:
```js
try {
await page.waitForSelector('.foo');
} catch (e) {
if (e instanceof playwright.errors.TimeoutError) {
// Do something if this is a timeout.
}
}
```
#### playwright.firefox
- type: <[BrowserType]>
This object can be used to launch or connect to Firefox, returning instances of [FirefoxBrowser].
#### playwright.selectors
- type: <[Selectors]>
Selectors can be used to install custom selector engines. See [Working with selectors](./selectors.md#working-with-selectors) for more information.
#### playwright.webkit
- type: <[BrowserType]>
This object can be used to launch or connect to WebKit, returning instances of [WebKitBrowser].
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

209
docs/class-request.md Normal file
View file

@ -0,0 +1,209 @@
---
id: class-request
title: "class: Request"
---
Whenever the page sends a request for a network resource the following sequence of events are emitted by [Page]:
* [page.on('request')](api/class-page.md#pageonrequest) emitted when the request is issued by the page.
* [page.on('response')](api/class-page.md#pageonresponse) emitted when/if the response status and headers are received for the request.
* [page.on('requestfinished')](api/class-page.md#pageonrequestfinished) emitted when the response body is downloaded and the request is complete.
If request fails at some point, then instead of `'requestfinished'` event (and possibly instead of 'response' event), the [page.on('requestfailed')](api/class-page.md#pageonrequestfailed) event is emitted.
> **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with `'requestfinished'` event.
If request gets a 'redirect' response, the request is successfully finished with the 'requestfinished' event, and a new request is issued to a redirected url.
- [request.failure()](api/class-request.md#requestfailure)
- [request.frame()](api/class-request.md#requestframe)
- [request.headers()](api/class-request.md#requestheaders)
- [request.isNavigationRequest()](api/class-request.md#requestisnavigationrequest)
- [request.method()](api/class-request.md#requestmethod)
- [request.postData()](api/class-request.md#requestpostdata)
- [request.postDataBuffer()](api/class-request.md#requestpostdatabuffer)
- [request.postDataJSON()](api/class-request.md#requestpostdatajson)
- [request.redirectedFrom()](api/class-request.md#requestredirectedfrom)
- [request.redirectedTo()](api/class-request.md#requestredirectedto)
- [request.resourceType()](api/class-request.md#requestresourcetype)
- [request.response()](api/class-request.md#requestresponse)
- [request.timing()](api/class-request.md#requesttiming)
- [request.url()](api/class-request.md#requesturl)
#### request.failure()
- returns: <[null]|[Object]>
- `errorText` <[string]> Human-readable error message, e.g. `'net::ERR_FAILED'`.
The method returns `null` unless this request has failed, as reported by `requestfailed` event.
Example of logging of all the failed requests:
```js
page.on('requestfailed', request => {
console.log(request.url() + ' ' + request.failure().errorText);
});
```
#### request.frame()
- returns: <[Frame]>
Returns the [Frame] that initiated this request.
#### request.headers()
- returns: <[Object]<[string], [string]>>
An object with HTTP headers associated with the request. All header names are lower-case.
#### request.isNavigationRequest()
- returns: <[boolean]>
Whether this request is driving frame's navigation.
#### request.method()
- returns: <[string]>
Request's method (GET, POST, etc.)
#### request.postData()
- returns: <[null]|[string]>
Request's post body, if any.
#### request.postDataBuffer()
- returns: <[null]|[Buffer]>
Request's post body in a binary form, if any.
#### request.postDataJSON()
- returns: <[null]|[Object]>
Returns parsed request's body for `form-urlencoded` and JSON as a fallback if any.
When the response is `application/x-www-form-urlencoded` then a key/value object of the values will be returned. Otherwise it will be parsed as JSON.
#### request.redirectedFrom()
- returns: <[null]|[Request]>
Request that was redirected by the server to this one, if any.
When the server responds with a redirect, Playwright creates a new [Request] object. The two requests are connected by `redirectedFrom()` and `redirectedTo()` methods. When multiple server redirects has happened, it is possible to construct the whole redirect chain by repeatedly calling `redirectedFrom()`.
For example, if the website `http://example.com` redirects to `https://example.com`:
```js
const response = await page.goto('http://example.com');
console.log(response.request().redirectedFrom().url()); // 'http://example.com'
```
If the website `https://google.com` has no redirects:
```js
const response = await page.goto('https://google.com');
console.log(response.request().redirectedFrom()); // null
```
#### request.redirectedTo()
- returns: <[null]|[Request]>
New request issued by the browser if the server responded with redirect.
This method is the opposite of [request.redirectedFrom()](api/class-request.md#requestredirectedfrom):
```js
console.log(request.redirectedFrom().redirectedTo() === request); // true
```
#### request.resourceType()
- returns: <[string]>
Contains the request's resource type as it was perceived by the rendering engine. ResourceType will be one of the following: `document`, `stylesheet`, `image`, `media`, `font`, `script`, `texttrack`, `xhr`, `fetch`, `eventsource`, `websocket`, `manifest`, `other`.
#### request.response()
- returns: <[Promise]<[null]|[Response]>>
Returns the matching [Response] object, or `null` if the response was not received due to error.
#### request.timing()
- returns: <[Object]>
- `startTime` <[number]> Request start time in milliseconds elapsed since January 1, 1970 00:00:00 UTC
- `domainLookupStart` <[number]> Time immediately before the browser starts the domain name lookup for the resource. The value is given in milliseconds relative to `startTime`, -1 if not available.
- `domainLookupEnd` <[number]> Time immediately after the browser starts the domain name lookup for the resource. The value is given in milliseconds relative to `startTime`, -1 if not available.
- `connectStart` <[number]> Time immediately before the user agent starts establishing the connection to the server to retrieve the resource. The value is given in milliseconds relative to `startTime`, -1 if not available.
- `secureConnectionStart` <[number]> Time immediately before the browser starts the handshake process to secure the current connection. The value is given in milliseconds relative to `startTime`, -1 if not available.
- `connectEnd` <[number]> Time immediately before the user agent starts establishing the connection to the server to retrieve the resource. The value is given in milliseconds relative to `startTime`, -1 if not available.
- `requestStart` <[number]> Time immediately before the browser starts requesting the resource from the server, cache, or local resource. The value is given in milliseconds relative to `startTime`, -1 if not available.
- `responseStart` <[number]> Time immediately after the browser starts requesting the resource from the server, cache, or local resource. The value is given in milliseconds relative to `startTime`, -1 if not available.
- `responseEnd` <[number]> Time immediately after the browser receives the last byte of the resource or immediately before the transport connection is closed, whichever comes first. The value is given in milliseconds relative to `startTime`, -1 if not available.
Returns resource timing information for given request. Most of the timing values become available upon the response, `responseEnd` becomes available when request finishes. Find more information at [Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming).
```js
const [request] = await Promise.all([
page.waitForEvent('requestfinished'),
page.goto(httpsServer.EMPTY_PAGE)
]);
console.log(request.timing());
```
#### request.url()
- returns: <[string]>
URL of the request.
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

134
docs/class-response.md Normal file
View file

@ -0,0 +1,134 @@
---
id: class-response
title: "class: Response"
---
[Response] class represents responses which are received by page.
- [response.body()](api/class-response.md#responsebody)
- [response.finished()](api/class-response.md#responsefinished)
- [response.frame()](api/class-response.md#responseframe)
- [response.headers()](api/class-response.md#responseheaders)
- [response.json()](api/class-response.md#responsejson)
- [response.ok()](api/class-response.md#responseok)
- [response.request()](api/class-response.md#responserequest)
- [response.status()](api/class-response.md#responsestatus)
- [response.statusText()](api/class-response.md#responsestatustext)
- [response.text()](api/class-response.md#responsetext)
- [response.url()](api/class-response.md#responseurl)
#### response.body()
- returns: <[Promise]<[Buffer]>>
Returns the buffer with response body.
#### response.finished()
- returns: <[Promise]<[null]|[Error]>>
Waits for this response to finish, returns failure error if request failed.
#### response.frame()
- returns: <[Frame]>
Returns the [Frame] that initiated this response.
#### response.headers()
- returns: <[Object]<[string], [string]>>
Returns the object with HTTP headers associated with the response. All header names are lower-case.
#### response.json()
- returns: <[Promise]<[Serializable]>>
Returns the JSON representation of response body.
This method will throw if the response body is not parsable via `JSON.parse`.
#### response.ok()
- returns: <[boolean]>
Contains a boolean stating whether the response was successful (status in the range 200-299) or not.
#### response.request()
- returns: <[Request]>
Returns the matching [Request] object.
#### response.status()
- returns: <[number]>
Contains the status code of the response (e.g., 200 for a success).
#### response.statusText()
- returns: <[string]>
Contains the status text of the response (e.g. usually an "OK" for a success).
#### response.text()
- returns: <[Promise]<[string]>>
Returns the text representation of response body.
#### response.url()
- returns: <[string]>
Contains the URL of the response.
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

146
docs/class-route.md Normal file
View file

@ -0,0 +1,146 @@
---
id: class-route
title: "class: Route"
---
Whenever a network route is set up with [page.route(url, handler)](api/class-page.md#pagerouteurl-handler) or [browserContext.route(url, handler)](api/class-browsercontext.md#browsercontextrouteurl-handler), the `Route` object allows to handle the route.
- [route.abort([errorCode])](api/class-route.md#routeaborterrorcode)
- [route.continue([overrides])](api/class-route.md#routecontinueoverrides)
- [route.fulfill(response)](api/class-route.md#routefulfillresponse)
- [route.request()](api/class-route.md#routerequest)
#### route.abort([errorCode])
- `errorCode` <[string]> Optional error code. Defaults to `failed`, could be one of the following:
* `'aborted'` - An operation was aborted (due to user action)
* `'accessdenied'` - Permission to access a resource, other than the network, was denied
* `'addressunreachable'` - The IP address is unreachable. This usually means that there is no route to the specified host or network.
* `'blockedbyclient'` - The client chose to block the request.
* `'blockedbyresponse'` - The request failed because the response was delivered along with requirements which are not met ('X-Frame-Options' and 'Content-Security-Policy' ancestor checks, for instance).
* `'connectionaborted'` - A connection timed out as a result of not receiving an ACK for data sent.
* `'connectionclosed'` - A connection was closed (corresponding to a TCP FIN).
* `'connectionfailed'` - A connection attempt failed.
* `'connectionrefused'` - A connection attempt was refused.
* `'connectionreset'` - A connection was reset (corresponding to a TCP RST).
* `'internetdisconnected'` - The Internet connection has been lost.
* `'namenotresolved'` - The host name could not be resolved.
* `'timedout'` - An operation timed out.
* `'failed'` - A generic failure occurred.
- returns: <[Promise]>
Aborts the route's request.
#### route.continue([overrides])
- `overrides` <[Object]> Optional request overrides, can override following properties:
- `url` <[string]> If set changes the request URL. New URL must have same protocol as original one.
- `method` <[string]> If set changes the request method (e.g. GET or POST)
- `postData` <[string]|[Buffer]> If set changes the post data of request
- `headers` <[Object]<[string], [string]>> If set changes the request HTTP headers. Header values will be converted to a string.
- returns: <[Promise]>
Continues route's request with optional overrides.
```js
await page.route('**/*', (route, request) => {
// Override headers
const headers = {
...request.headers(),
foo: 'bar', // set "foo" header
origin: undefined, // remove "origin" header
};
route.continue({headers});
});
```
#### route.fulfill(response)
- `response` <[Object]> Response that will fulfill this route's request.
- `status` <[number]> Response status code, defaults to `200`.
- `headers` <[Object]<[string], [string]>> Optional response headers. Header values will be converted to a string.
- `contentType` <[string]> If set, equals to setting `Content-Type` response header.
- `body` <[string]|[Buffer]> Optional response body.
- `path` <[string]> Optional file path to respond with. The content type will be inferred from file extension. If `path` is a relative path, then it is resolved relative to the current working directory.
- returns: <[Promise]>
Fulfills route's request with given response.
An example of fulfilling all requests with 404 responses:
```js
await page.route('**/*', route => {
route.fulfill({
status: 404,
contentType: 'text/plain',
body: 'Not Found!'
});
});
```
An example of serving static file:
```js
await page.route('**/xhr_endpoint', route => route.fulfill({ path: 'mock_data.json' }));
```
#### route.request()
- returns: <[Request]>
A request to be routed.
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

114
docs/class-selectors.md Normal file
View file

@ -0,0 +1,114 @@
---
id: class-selectors
title: "class: Selectors"
---
Selectors can be used to install custom selector engines. See [Working with selectors](./selectors.md#working-with-selectors) for more information.
- [selectors.register(name, script[, options])](api/class-selectors.md#selectorsregistername-script-options)
#### selectors.register(name, script[, options])
- `name` <[string]> Name that is used in selectors as a prefix, e.g. `{name: 'foo'}` enables `foo=myselectorbody` selectors. May only contain `[a-zA-Z0-9_]` characters.
- `script` <[function]|[string]|[Object]> Script that evaluates to a selector engine instance.
- `path` <[string]> Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working directory. Optional.
- `content` <[string]> Raw script content. Optional.
- `options` <[Object]>
- `contentScript` <[boolean]> Whether to run this selector engine in isolated JavaScript environment. This environment has access to the same DOM, but not any JavaScript objects from the frame's scripts. Defaults to `false`. Note that running as a content script is not guaranteed when this engine is used together with other registered engines.
- returns: <[Promise]>
An example of registering selector engine that queries elements based on a tag name:
```js
const { selectors, firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
(async () => {
// Must be a function that evaluates to a selector engine instance.
const createTagNameEngine = () => ({
// Returns the first element matching given selector in the root's subtree.
query(root, selector) {
return root.querySelector(selector);
},
// Returns all elements matching given selector in the root's subtree.
queryAll(root, selector) {
return Array.from(root.querySelectorAll(selector));
}
});
// Register the engine. Selectors will be prefixed with "tag=".
await selectors.register('tag', createTagNameEngine);
const browser = await firefox.launch();
const page = await browser.newPage();
await page.setContent(`<div><button>Click me</button></div>`);
// Use the selector prefixed with its name.
const button = await page.$('tag=button');
// Combine it with other selector engines.
await page.click('tag=div >> text="Click me"');
// Can use it in any methods supporting selectors.
const buttonCount = await page.$$eval('tag=button', buttons => buttons.length);
await browser.close();
})();
```
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

View file

@ -0,0 +1,67 @@
---
id: class-timeouterror
title: "class: TimeoutError"
---
* extends: [Error]
TimeoutError is emitted whenever certain operations are terminated due to timeout, e.g. [page.waitForSelector(selector[, options])](api/class-page.md#pagewaitforselectorselector-options) or [browserType.launch([options])](api/class-browsertype.md#browsertypelaunchoptions).
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

74
docs/class-touchscreen.md Normal file
View file

@ -0,0 +1,74 @@
---
id: class-touchscreen
title: "class: Touchscreen"
---
The Touchscreen class operates in main-frame CSS pixels relative to the top-left corner of the viewport. Methods on the touchscreen can only be used in browser contexts that have been intialized with `hasTouch` set to true.
- [touchscreen.tap(x, y)](api/class-touchscreen.md#touchscreentapx-y)
#### touchscreen.tap(x, y)
- `x` <[number]>
- `y` <[number]>
- returns: <[Promise]>
Dispatches a `touchstart` and `touchend` event with a single touch at the position (`x`,`y`).
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

76
docs/class-video.md Normal file
View file

@ -0,0 +1,76 @@
---
id: class-video
title: "class: Video"
---
When browser context is created with the `videosPath` option, each page has a video object associated with it.
```js
console.log(await page.video().path());
```
- [video.path()](api/class-video.md#videopath)
#### video.path()
- returns: <[Promise]<[string]>>
Returns the file system path this video will be recorded to. The video is guaranteed to be written to the filesystem upon closing the browser context.
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

View file

@ -0,0 +1,74 @@
---
id: class-webkitbrowser
title: "class: WebKitBrowser"
---
* extends: [Browser]
WebKit browser instance does not expose WebKit-specific features.
- [browser.on('disconnected')](api/class-browser.md#browserondisconnected)
- [browser.close()](api/class-browser.md#browserclose)
- [browser.contexts()](api/class-browser.md#browsercontexts)
- [browser.isConnected()](api/class-browser.md#browserisconnected)
- [browser.newContext([options])](api/class-browser.md#browsernewcontextoptions)
- [browser.newPage([options])](api/class-browser.md#browsernewpageoptions)
- [browser.version()](api/class-browser.md#browserversion)
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

115
docs/class-websocket.md Normal file
View file

@ -0,0 +1,115 @@
---
id: class-websocket
title: "class: WebSocket"
---
The [WebSocket] class represents websocket connections in the page.
- [webSocket.on('close')](api/class-websocket.md#websocketonclose)
- [webSocket.on('framereceived')](api/class-websocket.md#websocketonframereceived)
- [webSocket.on('framesent')](api/class-websocket.md#websocketonframesent)
- [webSocket.on('socketerror')](api/class-websocket.md#websocketonsocketerror)
- [webSocket.isClosed()](api/class-websocket.md#websocketisclosed)
- [webSocket.url()](api/class-websocket.md#websocketurl)
- [webSocket.waitForEvent(event[, optionsOrPredicate])](api/class-websocket.md#websocketwaitforeventevent-optionsorpredicate)
#### webSocket.on('close')
Fired when the websocket closes.
#### webSocket.on('framereceived')
- type: <[Object]>
- `payload` <[string]|[Buffer]> frame payload
Fired when the websocket recieves a frame.
#### webSocket.on('framesent')
- type: <[Object]>
- `payload` <[string]|[Buffer]> frame payload
Fired when the websocket sends a frame.
#### webSocket.on('socketerror')
- type: <[String]>
Fired when the websocket has an error.
#### webSocket.isClosed()
- returns: <[boolean]>
Indicates that the web socket has been closed.
#### webSocket.url()
- returns: <[string]>
Contains the URL of the WebSocket.
#### webSocket.waitForEvent(event[, optionsOrPredicate])
- `event` <[string]> Event name, same one would pass into `webSocket.on(event)`.
- `optionsOrPredicate` <[Function]|[Object]> Either a predicate that receives an event or an options object. Optional.
- `predicate` <[Function]> receives the event data and resolves to truthy value when the waiting should resolve.
- `timeout` <[number]> maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](api/class-browsercontext.md#browsercontextsetdefaulttimeouttimeout).
- returns: <[Promise]<[Object]>>
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 webSocket is closed before the event is fired.
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

111
docs/class-worker.md Normal file
View file

@ -0,0 +1,111 @@
---
id: class-worker
title: "class: Worker"
---
The Worker class represents a [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API). `worker` event is emitted on the page object to signal a worker creation. `close` event is emitted on the worker object when the worker is gone.
```js
page.on('worker', worker => {
console.log('Worker created: ' + worker.url());
worker.on('close', worker => console.log('Worker destroyed: ' + worker.url()));
});
console.log('Current workers:');
for (const worker of page.workers())
console.log(' ' + worker.url());
```
- [worker.on('close')](api/class-worker.md#workeronclose)
- [worker.evaluate(pageFunction[, arg])](api/class-worker.md#workerevaluatepagefunction-arg)
- [worker.evaluateHandle(pageFunction[, arg])](api/class-worker.md#workerevaluatehandlepagefunction-arg)
- [worker.url()](api/class-worker.md#workerurl)
#### worker.on('close')
- type: <[Worker]>
Emitted when this dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is terminated.
#### worker.evaluate(pageFunction[, arg])
- `pageFunction` <[function]|[string]> Function to be evaluated in the worker context
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[Serializable]>>
Returns the return value of `pageFunction`
If the function passed to the `worker.evaluate` returns a [Promise], then `worker.evaluate` would wait for the promise to resolve and return its value.
If the function passed to the `worker.evaluate` returns a non-[Serializable] value, then `worker.evaluate` returns `undefined`. DevTools Protocol also supports transferring some additional values that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.
#### worker.evaluateHandle(pageFunction[, arg])
- `pageFunction` <[function]|[string]> Function to be evaluated in the page context
- `arg` <[EvaluationArgument]> Optional argument to pass to `pageFunction`
- returns: <[Promise]<[JSHandle]>>
Returns the return value of `pageFunction` as in-page object (JSHandle).
The only difference between `worker.evaluate` and `worker.evaluateHandle` is that `worker.evaluateHandle` returns in-page object (JSHandle).
If the function passed to the `worker.evaluateHandle` returns a [Promise], then `worker.evaluateHandle` would wait for the promise to resolve and return its value.
#### worker.url()
- returns: <[string]>
[Playwright]: api/class-playwright.md "Playwright"
[Browser]: api/class-browser.md "Browser"
[BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api/class-page.md "Page"
[Frame]: api/class-frame.md "Frame"
[ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api/class-dialog.md "Dialog"
[Download]: api/class-download.md "Download"
[Video]: api/class-video.md "Video"
[FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api/class-request.md "Request"
[Response]: api/class-response.md "Response"
[Selectors]: api/class-selectors.md "Selectors"
[Route]: api/class-route.md "Route"
[WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api/class-worker.md "Worker"
[BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"
[RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp "RegExp"
[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"
[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"
[URL]: https://nodejs.org/api/url.html "URL"
[USKeyboardLayout]: ../src/usKeyboardLayout.ts "USKeyboardLayout"
[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"
[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"
[null]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null "null"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"
[Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "Readable"
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "string"
[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"

View file

@ -1,26 +1,17 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: cli
title: "Command Line Interface"
---
# Playwright CLI Playwright comes with the command line tools that run via `npx` or as a part of the `npm` scripts.
Playwright comes with the command line tools that run via `npx` or as a part of
the `npm` scripts.
<!-- GEN:toc -->
- [Usage](#usage) - [Usage](#usage)
- [Generate code](#generate-code) - [Generate code](#generate-code)
- [Open pages](#open-pages) - [Open pages](#open-pages)
* [Emulate devices](#emulate-devices)
* [Emulate color scheme and viewport size](#emulate-color-scheme-and-viewport-size)
* [Emulate geolocation, language and timezone](#emulate-geolocation-language-and-timezone)
- [Inspect selectors](#inspect-selectors) - [Inspect selectors](#inspect-selectors)
- [playwright.$(selector)](#playwrightselector)
- [playwright.$$(selector)](#playwrightselector-1)
- [playwright.inspect(selector)](#playwrightinspectselector)
- [playwright.selector(element)](#playwrightselectorelement)
- [Take screenshot](#take-screenshot) - [Take screenshot](#take-screenshot)
- [Generate PDF](#generate-pdf) - [Generate PDF](#generate-pdf)
- [Known limitations](#known-limitations) - [Known limitations](#known-limitations)
<!-- GEN:stop -->
## Usage ## Usage
@ -44,18 +35,13 @@ Running from `package.json` script
$ npx playwright codegen wikipedia.org $ npx playwright codegen wikipedia.org
``` ```
Run `codegen` and perform actions in the browser. Playwright CLI will generate Run `codegen` and perform actions in the browser. Playwright CLI will generate JavaScript code for the user interactions. `codegen` will attempt to generate resilient text-based selectors.
JavaScript code for the user interactions. `codegen` will attempt to generate
resilient text-based selectors.
<img <img src="https://user-images.githubusercontent.com/284612/92536033-7e7ebe00-f1ed-11ea-9e1a-7cbd912e3391.gif">
src="https://user-images.githubusercontent.com/284612/92536033-7e7ebe00-f1ed-11ea-9e1a-7cbd912e3391.gif">
## Open pages ## Open pages
With `open`, you can use Playwright bundled browsers to browse web pages. With `open`, you can use Playwright bundled browsers to browse web pages. Playwright provides cross-platform WebKit builds that can be used to reproduce Safari rendering across Windows, Linux and macOS.
Playwright provides cross-platform WebKit builds that can be used to reproduce
Safari rendering across Windows, Linux and macOS.
```sh ```sh
# Open page in Chromium # Open page in Chromium
@ -69,8 +55,7 @@ npx playwright wk example.com
### Emulate devices ### Emulate devices
`open` can emulate mobile and tablet devices `open` can emulate mobile and tablet devices ([see all devices](https://github.com/microsoft/playwright/blob/master/src/server/deviceDescriptors.ts)).
([see all devices](https://github.com/microsoft/playwright/blob/master/src/server/deviceDescriptors.ts)).
```sh ```sh
# Emulate iPhone 11. # Emulate iPhone 11.
@ -94,16 +79,13 @@ npx playwright --timezone="Europe/Rome" --geolocation="41.890221,12.492348" --la
## Inspect selectors ## Inspect selectors
During `open` or `codegen`, you can use following API inside the developer tools During `open` or `codegen`, you can use following API inside the developer tools console of any browser.
console of any browser.
<img <img src="https://user-images.githubusercontent.com/284612/92536317-37dd9380-f1ee-11ea-875d-daf1b206dd56.png">
src="https://user-images.githubusercontent.com/284612/92536317-37dd9380-f1ee-11ea-875d-daf1b206dd56.png">
#### playwright.$(selector) #### playwright.$(selector)
Query Playwright selector, using the actual Playwright query engine, for Query Playwright selector, using the actual Playwright query engine, for example:
example:
```js ```js
> playwright.$('.auth-form >> text=Log in'); > playwright.$('.auth-form >> text=Log in');
@ -123,8 +105,7 @@ Same as `playwright.$`, but returns all matching elements.
#### playwright.inspect(selector) #### playwright.inspect(selector)
Reveal element in the Elements panel (if DevTools of the respective browser Reveal element in the Elements panel (if DevTools of the respective browser supports it).
supports it).
```js ```js
> playwright.inspect('text=Log in') > playwright.inspect('text=Log in')
@ -173,46 +154,45 @@ $ npx playwright pdf https://en.wikipedia.org/wiki/PDF wiki.pdf
## Known limitations ## Known limitations
Opening WebKit Web Inspector will disconnect Playwright from the browser. In Opening WebKit Web Inspector will disconnect Playwright from the browser. In such cases, code generation will stop.
such cases, code generation will stop. [Playwright]: api/class-playwright.md "Playwright"
[Playwright]: api.md#class-playwright "Playwright" [Browser]: api/class-browser.md "Browser"
[Browser]: api.md#class-browser "Browser" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [Page]: api/class-page.md "Page"
[Page]: api.md#class-page "Page" [Frame]: api/class-frame.md "Frame"
[Frame]: api.md#class-frame "Frame" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [Dialog]: api/class-dialog.md "Dialog"
[Dialog]: api.md#class-dialog "Dialog" [Download]: api/class-download.md "Download"
[Download]: api.md#class-download "Download" [Video]: api/class-video.md "Video"
[Video]: api.md#class-video "Video" [FileChooser]: api/class-filechooser.md "FileChooser"
[FileChooser]: api.md#class-filechooser "FileChooser" [Keyboard]: api/class-keyboard.md "Keyboard"
[Keyboard]: api.md#class-keyboard "Keyboard" [Mouse]: api/class-mouse.md "Mouse"
[Mouse]: api.md#class-mouse "Mouse" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Request]: api/class-request.md "Request"
[Request]: api.md#class-request "Request" [Response]: api/class-response.md "Response"
[Response]: api.md#class-response "Response" [Selectors]: api/class-selectors.md "Selectors"
[Selectors]: api.md#class-selectors "Selectors" [Route]: api/class-route.md "Route"
[Route]: api.md#class-route "Route" [WebSocket]: api/class-websocket.md "WebSocket"
[WebSocket]: api.md#class-websocket "WebSocket" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [Accessibility]: api/class-accessibility.md "Accessibility"
[Accessibility]: api.md#class-accessibility "Accessibility" [Worker]: api/class-worker.md "Worker"
[Worker]: api.md#class-worker "Worker" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserType]: api/class-browsertype.md "BrowserType"
[BrowserType]: api.md#class-browsertype "BrowserType" [Logger]: api/class-logger.md "Logger"
[Logger]: api.md#class-logger "Logger" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [CDPSession]: api/class-cdpsession.md "CDPSession"
[CDPSession]: api.md#class-cdpsession "CDPSession" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -1,33 +1,26 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: core-concepts
title: "Core concepts"
---
# Core concepts Playwright provides a set of APIs to automate Chromium, Firefox and WebKit browsers. By using the Playwright API, you can write JavaScript code to create new browser pages, navigate to URLs and then interact with elements on a page.
Playwright provides a set of APIs to automate Chromium, Firefox and WebKit Along with a test runner Playwright can be used to automate user interactions to validate and test web applications. The Playwright API enables this through the following primitives.
browsers. By using the Playwright API, you can write JavaScript code to create
new browser pages, navigate to URLs and then interact with elements on a page.
Along with a test runner Playwright can be used to automate user interactions to
validate and test web applications. The Playwright API enables this through the
following primitives.
<!-- GEN:toc-top-level -->
- [Browser](#browser) - [Browser](#browser)
- [Browser contexts](#browser-contexts) - [Browser contexts](#browser-contexts)
- [Pages and frames](#pages-and-frames) - [Pages and frames](#pages-and-frames)
- [Selectors](#selectors) - [Selectors](#selectors)
- [Auto-waiting](#auto-waiting) - [Auto-waiting](#auto-waiting)
- [Execution contexts: Node.js and Browser](#execution-contexts-nodejs-and-browser) - [Execution contexts: Node.js and Browser](#execution-contexts-nodejs-and-browser)
- [Evaluation Argument](#evaluation-argument)
- [Object & Element handles](#object--element-handles) - [Object & Element handles](#object--element-handles)
<!-- GEN:stop -->
<br/> <br/>
## Browser ## Browser
A [Browser] refers to an instance of Chromium, Firefox or WebKit. Playwright A [Browser] refers to an instance of Chromium, Firefox or WebKit. Playwright scripts generally start with launching a browser instance and end with closing the browser. Browser instances can be launched in headless (without a GUI) or headful mode.
scripts generally start with launching a browser instance and end with closing
the browser. Browser instances can be launched in headless (without a GUI) or
headful mode.
```js ```js
const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'. const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
@ -36,8 +29,7 @@ const browser = await chromium.launch({ headless: false });
await browser.close(); await browser.close();
``` ```
Launching a browser instance can be expensive, and Playwright is designed to Launching a browser instance can be expensive, and Playwright is designed to maximize what a single instance can do through multiple browser contexts.
maximize what a single instance can do through multiple browser contexts.
#### API reference #### API reference
- [Browser] - [Browser]
@ -46,17 +38,14 @@ maximize what a single instance can do through multiple browser contexts.
## Browser contexts ## Browser contexts
A [BrowserContext] is an isolated incognito-alike session within a browser A [BrowserContext] is an isolated incognito-alike session within a browser instance. Browser contexts are fast and cheap to create. Browser contexts can be used to parallelize isolated test executions.
instance. Browser contexts are fast and cheap to create. Browser contexts can be
used to parallelize isolated test executions.
```js ```js
const browser = await chromium.launch(); const browser = await chromium.launch();
const context = await browser.newContext(); const context = await browser.newContext();
``` ```
Browser contexts can also be used to emulate multi-page scenarios involving Browser contexts can also be used to emulate multi-page scenarios involving mobile devices, permissions, locale and color scheme.
mobile devices, permissions, locale and color scheme.
```js ```js
const { devices } = require('playwright'); const { devices } = require('playwright');
@ -73,15 +62,13 @@ const context = await browser.newContext({
#### API reference #### API reference
- [BrowserContext] - [BrowserContext]
- [browser.newContext([options])](./api.md#browsernewcontextoptions) - [browser.newContext([options])](api/class-browser.md#browsernewcontextoptions)
<br/> <br/>
## Pages and frames ## Pages and frames
A Browser context can have multiple pages. A [Page] refers to a single tab or a A Browser context can have multiple pages. A [Page] refers to a single tab or a popup window within a browser context. It should be used to navigate to URLs and interact with the page content.
popup window within a browser context. It should be used to navigate to URLs and
interact with the page content.
```js ```js
// Create a page. // Create a page.
@ -103,12 +90,9 @@ window.location.href = 'https://example.com';
> Read more on [page navigation and loading](./navigations.md). > Read more on [page navigation and loading](./navigations.md).
A page can have one or more [Frame] objects attached to it. Each page has a main A page can have one or more [Frame] objects attached to it. Each page has a main frame and page-level interactions (like `click`) are assumed to operate in the main frame.
frame and page-level interactions (like `click`) are assumed to operate in the
main frame.
A page can have additional frames attached with the `iframe` HTML tag. These A page can have additional frames attached with the `iframe` HTML tag. These frames can be accessed for interactions inside the frame.
frames can be accessed for interactions inside the frame.
```js ```js
// Get frame using the frame's name attribute // Get frame using the frame's name attribute
@ -128,21 +112,17 @@ await frame.fill('#username-input', 'John');
#### API reference #### API reference
- [Page] - [Page]
- [Frame] - [Frame]
- [page.frame(frameSelector)](./api.md#pageframeframeselector) - [page.frame(frameSelector)](api/class-page.md#pageframeframeselector)
<br/> <br/>
## Selectors ## Selectors
Playwright can search for elements using CSS selectors, XPath selectors, HTML Playwright can search for elements using CSS selectors, XPath selectors, HTML attributes like `id`, `data-test-id` and even text content.
attributes like `id`, `data-test-id` and even text content.
You can explicitly specify the selector engine you are using or let Playwright You can explicitly specify the selector engine you are using or let Playwright detect it.
detect it.
All selector engines except for XPath pierce shadow DOM by default. If you want All selector engines except for XPath pierce shadow DOM by default. If you want to enforce regular DOM selection, you can use the `*:light` versions of the selectors. You don't typically need to though.
to enforce regular DOM selection, you can use the `*:light` versions of the
selectors. You don't typically need to though.
Learn more about selectors and selector engines [here](./selectors.md). Learn more about selectors and selector engines [here](./selectors.md).
@ -175,8 +155,7 @@ await page.click('xpath=//html/body/div');
await page.click('css:light=div'); await page.click('css:light=div');
``` ```
Selectors using the same or different engines can be combined using the `>>` Selectors using the same or different engines can be combined using the `>>` separator. For example,
separator. For example,
```js ```js
// Click an element with text 'Sign Up' inside of a #free-month-promo. // Click an element with text 'Sign Up' inside of a #free-month-promo.
@ -192,15 +171,12 @@ const sectionText = await page.$eval('*css=section >> text=Selectors', e => e.te
## Auto-waiting ## Auto-waiting
Actions like `click` and `fill` auto-wait for the element to be visible and Actions like `click` and `fill` auto-wait for the element to be visible and [actionable](./actionability.md). For example, click will:
[actionable](./actionability.md). For example, click will:
- wait for an element with the given selector to appear in the DOM - wait for an element with the given selector to appear in the DOM
- wait for it to become visible: have non-empty bounding box and no - wait for it to become visible: have non-empty bounding box and no `visibility:hidden`
`visibility:hidden`
- wait for it to stop moving: for example, wait until css transition finishes - wait for it to stop moving: for example, wait until css transition finishes
- scroll the element into view - scroll the element into view
- wait for it to receive pointer events at the action point: for example, wait - wait for it to receive pointer events at the action point: for example, wait until element becomes non-obscured by other elements
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
```js ```js
@ -214,8 +190,7 @@ await page.fill('#search', 'query');
await page.click('#search'); await page.click('#search');
``` ```
You can explicitly wait for an element to appear in the DOM or to become You can explicitly wait for an element to appear in the DOM or to become visible:
visible:
```js ```js
// Wait for #search to appear in the DOM. // Wait for #search to appear in the DOM.
@ -234,30 +209,23 @@ await page.waitForSelector('#promo', { state: 'detached' });
``` ```
#### API reference #### API reference
- [page.click(selector[, options])](./api.md#pageclickselector-options) - [page.click(selector[, options])](api/class-page.md#pageclickselector-options)
- [page.fill(selector, value[, options])](./api.md#pagefillselector-value-options) - [page.fill(selector, value[, options])](api/class-page.md#pagefillselector-value-options)
- [page.waitForSelector(selector[, options])](./api.md#pagewaitforselectorselector-options) - [page.waitForSelector(selector[, options])](api/class-page.md#pagewaitforselectorselector-options)
<br/> <br/>
## Execution contexts: Node.js and Browser ## Execution contexts: Node.js and Browser
Playwright scripts run in your Node.js environment. Your page scripts run in the Playwright scripts run in your Node.js environment. Your page scripts run in the browser page environment. Those environments don't intersect, they are running in different virtual machines in different processes and even potentially on different computers.
browser page environment. Those environments don't intersect, they are running
in different virtual machines in different processes and even potentially on
different computers.
The [page.evaluate(pageFunction[, arg])](./api.md#pageevaluatepagefunction-arg) The [page.evaluate(pageFunction[, arg])](api/class-page.md#pageevaluatepagefunction-arg) API can run a JavaScript function in the context of the web page and bring results back to the Node.js environment. Browser globals like `window` and `document` can be used in `evaluate`.
API can run a JavaScript function in the context of the web page and bring
results back to the Node.js environment. Browser globals like `window` and
`document` can be used in `evaluate`.
```js ```js
const href = await page.evaluate(() => document.location.href); const href = await page.evaluate(() => document.location.href);
``` ```
If the result is a Promise or if the function is asynchronous evaluate will If the result is a Promise or if the function is asynchronous evaluate will automatically wait until it's resolved:
automatically wait until it's resolved:
```js ```js
const status = await page.evaluate(async () => { const status = await page.evaluate(async () => {
@ -266,13 +234,52 @@ const status = await page.evaluate(async () => {
}); });
``` ```
### Evaluation ## Evaluation Argument
Functions passed inside Playwright evaluation methods like [page.evaluate(pageFunction[, arg])](api/class-page.md#pageevaluatepagefunction-arg) take a single optional argument. This argument can be a mix of [Serializable] values and [JSHandle] or [ElementHandle] instances. Handles are automatically converted to the value they represent.
[page.evaluate(pageFunction[, arg])](./api.md#pageevaluatepagefunction-arg) can
accept parameters. These parameters are serialized and sent into your web page ```js
over the wire. You can pass primitive types, JSON-alike objects and remote // A primitive value.
object handles received from the page. await page.evaluate(num => num, 42);
// An array.
await page.evaluate(array => array.length, [1, 2, 3]);
// An object.
await page.evaluate(object => object.foo, { foo: 'bar' });
// A single handle.
const button = await page.$('button');
await page.evaluate(button => button.textContent, button);
// Alternative notation using elementHandle.evaluate.
await button.evaluate((button, from) => button.textContent.substring(from), 5);
// Object with multiple handles.
const button1 = await page.$('.button1');
const button2 = await page.$('.button2');
await page.evaluate(
o => o.button1.textContent + o.button2.textContent,
{ button1, button2 });
// Object destructuring works. Note that property names must match
// between the destructured object and the argument.
// Also note the required parenthesis.
await page.evaluate(
({ button1, button2 }) => button1.textContent + button2.textContent,
{ button1, button2 });
// Array works as well. Arbitrary names can be used for destructuring.
// Note the required parenthesis.
await page.evaluate(
([b1, b2]) => b1.textContent + b2.textContent,
[button1, button2]);
// Any non-cyclic mix of serializables and handles works.
await page.evaluate(
x => x.button1.textContent + x.list[0].textContent + String(x.foo),
{ button1, list: [button2], foo: null });
```
Right: Right:
@ -295,39 +302,27 @@ const result = await page.evaluate(() => {
``` ```
#### API reference #### API reference
- [page.evaluate(pageFunction[, arg])](./api.md#pageevaluatepagefunction-arg) - [page.evaluate(pageFunction[, arg])](api/class-page.md#pageevaluatepagefunction-arg)
- [frame.evaluate(pageFunction[, arg])](./api.md#frameevaluatepagefunction-arg) - [frame.evaluate(pageFunction[, arg])](api/class-frame.md#frameevaluatepagefunction-arg)
- [EvaluationArgument] - [EvaluationArgument]
<br/> <br/>
## Object & Element handles ## Object & Element handles
Playwright can create Node-side handles to the page DOM elements or any other Playwright can create Node-side handles to the page DOM elements or any other objects inside the page. These handles live in the Node.js process, whereas the actual objects reside in browser.
objects inside the page. These handles live in the Node.js process, whereas the
actual objects reside in browser.
There are two types of handles: There are two types of handles:
- [JSHandle] to reference any JavaScript objects in the page - [JSHandle] to reference any JavaScript objects in the page
- [ElementHandle] to reference DOM elements in the page - [ElementHandle] to reference DOM elements in the page
Note that since any DOM element in the page is also a JavaScript object, Note that since any DOM element in the page is also a JavaScript object, Playwright's [ElementHandle] extends [JSHandle].
Playwright's [ElementHandle] extends [JSHandle].
### Handles Lifecycle ### Handles Lifecycle
- Handles can be acquired using the page methods - Handles can be acquired using the page methods [page.evaluateHandle(pageFunction[, arg])](api/class-page.md#pageevaluatehandlepagefunction-arg), [page.$(selector)](api/class-page.md#pageselector) or [page.$$(selector)](api/class-page.md#pageselector-1) or their frame counterparts [frame.evaluateHandle(pageFunction[, arg])](api/class-frame.md#frameevaluatehandlepagefunction-arg), [frame.$(selector)](api/class-frame.md#frameselector) or [frame.$$(selector)](api/class-frame.md#frameselector-1).
[page.evaluateHandle(pageFunction[, arg])](./api.md#pageevaluatehandlepagefunction-arg), - Once created, handles will retain object from [garbage collection](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management).
[page.$(selector)](./api.md#pageselector) or - Handles will be **automatically disposed** once the page or frame they belong to navigates or closes.
[page.$$(selector)](./api.md#pageselector-1) or their frame counterparts - Handles can be **manually disposed** using [jsHandle.dispose()](api/class-jshandle.md#jshandledispose) method.
[frame.evaluateHandle(pageFunction[, arg])](./api.md#frameevaluatehandlepagefunction-arg),
[frame.$(selector)](./api.md#frameselector) or
[frame.$$(selector)](./api.md#frameselector-1).
- Once created, handles will retain object from
[garbage collection](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management).
- Handles will be **automatically disposed** once the page or frame they
belong to navigates or closes.
- Handles can be **manually disposed** using
[jsHandle.dispose()](./api.md#jshandledispose) method.
### Example: ElementHandle ### Example: ElementHandle
@ -337,9 +332,7 @@ const ulElementHandle = await page.$('ul');
await ulElementHandle.evaluate(ulElement => getComputedStyle(ulElement).getPropertyValue('display')); await ulElementHandle.evaluate(ulElement => getComputedStyle(ulElement).getPropertyValue('display'));
``` ```
Handles can also be passed as arguments to Handles can also be passed as arguments to [page.evaluate(pageFunction[, arg])](api/class-page.md#pageevaluatepagefunction-arg) function:
[page.evaluate(pageFunction[, arg])](./api.md#pageevaluatepagefunction-arg)
function:
```js ```js
// In the page API, you can pass handle as a parameter. // In the page API, you can pass handle as a parameter.
@ -379,48 +372,48 @@ await myArrayHandle.dispose();
#### API reference #### API reference
- [JSHandle] - [JSHandle]
- [ElementHandle] - [ElementHandle]
- [page.evaluateHandle(pageFunction[, arg])](./api.md#pageevaluatehandlepagefunction-arg) - [page.evaluateHandle(pageFunction[, arg])](api/class-page.md#pageevaluatehandlepagefunction-arg)
- [page.$(selector)](./api.md#pageselector) - [page.$(selector)](api/class-page.md#pageselector)
- [page.$$(selector)](./api.md#pageselector-1) - [page.$$(selector)](api/class-page.md#pageselector-1)
- [jsHandle.evaluate(pageFunction[, arg])](./api.md#jshandleevaluatepagefunction-arg) - [jsHandle.evaluate(pageFunction[, arg])](api/class-jshandle.md#jshandleevaluatepagefunction-arg)
[Playwright]: api.md#class-playwright "Playwright" [Playwright]: api/class-playwright.md "Playwright"
[Browser]: api.md#class-browser "Browser" [Browser]: api/class-browser.md "Browser"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api.md#class-page "Page" [Page]: api/class-page.md "Page"
[Frame]: api.md#class-frame "Frame" [Frame]: api/class-frame.md "Frame"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api.md#class-dialog "Dialog" [Dialog]: api/class-dialog.md "Dialog"
[Download]: api.md#class-download "Download" [Download]: api/class-download.md "Download"
[Video]: api.md#class-video "Video" [Video]: api/class-video.md "Video"
[FileChooser]: api.md#class-filechooser "FileChooser" [FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api.md#class-keyboard "Keyboard" [Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api.md#class-mouse "Mouse" [Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api.md#class-request "Request" [Request]: api/class-request.md "Request"
[Response]: api.md#class-response "Response" [Response]: api/class-response.md "Response"
[Selectors]: api.md#class-selectors "Selectors" [Selectors]: api/class-selectors.md "Selectors"
[Route]: api.md#class-route "Route" [Route]: api/class-route.md "Route"
[WebSocket]: api.md#class-websocket "WebSocket" [WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api.md#class-accessibility "Accessibility" [Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api.md#class-worker "Worker" [Worker]: api/class-worker.md "Worker"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api.md#class-browsertype "BrowserType" [BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api.md#class-logger "Logger" [Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api.md#class-cdpsession "CDPSession" [CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -1,30 +1,19 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: debug
title: "Debugging tools"
---
# Debugging tools Playwright scripts work with existing debugging tools, like Node.js debuggers and browser developer tools. Playwright also introduces new debugging features for browser automation.
Playwright scripts work with existing debugging tools, like Node.js debuggers
and browser developer tools. Playwright also introduces new debugging features
for browser automation.
<!-- GEN:toc -->
- [Run in headful mode](#run-in-headful-mode) - [Run in headful mode](#run-in-headful-mode)
- [Visual Studio Code debugger](#visual-studio-code-debugger) - [Visual Studio Code debugger](#visual-studio-code-debugger)
* [Use launch config](#use-launch-config)
* [Use the new JavaScript debugger](#use-the-new-javascript-debugger)
- [Browser Developer Tools](#browser-developer-tools) - [Browser Developer Tools](#browser-developer-tools)
* [API for Chromium](#api-for-chromium)
- [Run in Debug Mode](#run-in-debug-mode) - [Run in Debug Mode](#run-in-debug-mode)
* [Defaults](#defaults)
* [Debugging Selectors](#debugging-selectors)
* [Evaluate Source Maps](#evaluate-source-maps)
- [Verbose API logs](#verbose-api-logs) - [Verbose API logs](#verbose-api-logs)
<!-- GEN:stop -->
## Run in headful mode ## Run in headful mode
Playwright runs browsers in headless mode by default. To change this behavior, Playwright runs browsers in headless mode by default. To change this behavior, use `headless: false` as a launch option. You can also use the `slowMo` option to slow down execution and follow along while debugging.
use `headless: false` as a launch option. You can also use the `slowMo` option
to slow down execution and follow along while debugging.
```js ```js
await chromium.launch({ headless: false, slowMo: 100 }); // or firefox, webkit await chromium.launch({ headless: false, slowMo: 100 }); // or firefox, webkit
@ -32,44 +21,32 @@ await chromium.launch({ headless: false, slowMo: 100 }); // or firefox, webkit
## Visual Studio Code debugger ## Visual Studio Code debugger
The VS Code debugger can be used to pause and resume execution of Playwright The VS Code debugger can be used to pause and resume execution of Playwright scripts with breakpoints. The debugger can be configured in two ways.
scripts with breakpoints. The debugger can be configured in two ways.
### Use launch config ### Use launch config
Setup Setup [`launch.json` configuration](https://code.visualstudio.com/docs/nodejs/nodejs-debugging) for your Node.js project. Once configured launch the scripts with F5 and use breakpoints.
[`launch.json` configuration](https://code.visualstudio.com/docs/nodejs/nodejs-debugging)
for your Node.js project. Once configured launch the scripts with F5 and use
breakpoints.
### Use the new JavaScript debugger ### Use the new JavaScript debugger
VS Code 1.46+ introduces the new JavaScript debugger behind a feature flag. The VS Code 1.46+ introduces the new JavaScript debugger behind a feature flag. The new debugger does not require a `launch.json` configuration. To use this:
new debugger does not require a `launch.json` configuration. To use this:
1. Enable the preview debugger 1. Enable the preview debugger
* Open JSON settings and add `"debug.javascript.usePreview": true` * Open JSON settings and add `"debug.javascript.usePreview": true`
* Open settings UI and enable the `Debug JavaScript: Use Preview` * Open settings UI and enable the `Debug JavaScript: Use Preview` setting
setting
1. Set a breakpoint in VS Code 1. Set a breakpoint in VS Code
* Use the `debugger` keyword or set a breakpoint in the VS Code UI * Use the `debugger` keyword or set a breakpoint in the VS Code UI
1. Run your Node.js script from the terminal 1. Run your Node.js script from the terminal
## Browser Developer Tools ## Browser Developer Tools
You can use browser developer tools in Chromium, Firefox and WebKit while You can use browser developer tools in Chromium, Firefox and WebKit while running a Playwright script. Developer tools help to:
running a Playwright script. Developer tools help to:
* Inspect the DOM tree and **find element selectors** * Inspect the DOM tree and **find element selectors**
* **See console logs** during execution (or learn how to * **See console logs** during execution (or learn how to [read logs via API](./verification.md#console-logs))
[read logs via API](./verification.md#console-logs))
* Check **network activity** and other developer tools features * Check **network activity** and other developer tools features
<a <a href="https://user-images.githubusercontent.com/284612/77234134-5f21a500-6b69-11ea-92ec-1c146e1333ec.png"><img src="https://user-images.githubusercontent.com/284612/77234134-5f21a500-6b69-11ea-92ec-1c146e1333ec.png" width="500" alt="Chromium Developer Tools"></a>
href="https://user-images.githubusercontent.com/284612/77234134-5f21a500-6b69-11ea-92ec-1c146e1333ec.png"><img
src="https://user-images.githubusercontent.com/284612/77234134-5f21a500-6b69-11ea-92ec-1c146e1333ec.png"
width="500" alt="Chromium Developer Tools"></a>
> **For WebKit**: Note that launching WebKit Inspector during the execution will > **For WebKit**: Note that launching WebKit Inspector during the execution will prevent the Playwright script from executing any further.
prevent the Playwright script from executing any further.
### API for Chromium ### API for Chromium
@ -81,8 +58,7 @@ await chromium.launch({ devtools: true });
## Run in Debug Mode ## Run in Debug Mode
Set the `PWDEBUG` environment variable to run your scripts in debug mode. This Set the `PWDEBUG` environment variable to run your scripts in debug mode. This configures the browser for debugging.
configures the browser for debugging.
```sh ```sh
# Linux/macOS # Linux/macOS
@ -98,40 +74,26 @@ $ npm run test
With PWDEBUG, the following defaults are configured for you: With PWDEBUG, the following defaults are configured for you:
* **Run in headful**: With PWDEBUG, browsers always launch in headful mode * **Run in headful**: With PWDEBUG, browsers always launch in headful mode
* **Disables timeout**: PWDEBUG sets timeout to 0 (= no timeout) * **Disables timeout**: PWDEBUG sets timeout to 0 (= no timeout)
* **Preserve DevTools preferences**: When used with `devtools: true`, PWDEBUG * **Preserve DevTools preferences**: When used with `devtools: true`, PWDEBUG preserves the docked/undocked state of Chrome DevTools
preserves the docked/undocked state of Chrome DevTools
### Debugging Selectors ### Debugging Selectors
PWDEBUG configures a `playwright` object in the browser to highlight PWDEBUG configures a `playwright` object in the browser to highlight [Playwright selectors](./selectors.md). This can be used to verify text or composite selectors. To use this:
[Playwright selectors](./selectors.md). This can be used to verify text or
composite selectors. To use this:
1. Setup a breakpoint to pause the execution 1. Setup a breakpoint to pause the execution
1. Open the console panel in browser developer tools 1. Open the console panel in browser developer tools
1. Use the `playwright` API 1. Use the `playwright` API
* `playwright.$(selector)`: Highlight the first occurrence of the * `playwright.$(selector)`: Highlight the first occurrence of the selector. This reflects how `page.$` would see the page.
selector. This reflects how `page.$` would see the page. * `playwright.$$(selector)`: Highlight all occurrences of the selector. This reflects how `page.$$` would see the page.
* `playwright.$$(selector)`: Highlight all occurrences of the selector. * `playwright.inspect(selector)`: Inspect the selector in the Elements panel.
This reflects how `page.$$` would see the page.
* `playwright.inspect(selector)`: Inspect the selector in the Elements
panel.
* `playwright.clear()`: Clear existing highlights. * `playwright.clear()`: Clear existing highlights.
<a <a href="https://user-images.githubusercontent.com/284612/86857345-299abc00-c073-11ea-9e31-02923a9f0d4b.png"><img src="https://user-images.githubusercontent.com/284612/86857345-299abc00-c073-11ea-9e31-02923a9f0d4b.png" width="500" alt="Highlight selectors"></a>
href="https://user-images.githubusercontent.com/284612/86857345-299abc00-c073-11ea-9e31-02923a9f0d4b.png"><img
src="https://user-images.githubusercontent.com/284612/86857345-299abc00-c073-11ea-9e31-02923a9f0d4b.png"
width="500" alt="Highlight selectors"></a>
### Evaluate Source Maps ### Evaluate Source Maps
PWDEBUG also enables source maps for PWDEBUG also enables source maps for [`page.evaluate` executions](core-concepts.md#evaluation). This improves the debugging experience for JavaScript executions in the page context.
[`page.evaluate` executions](core-concepts.md#evaluation). This improves the
debugging experience for JavaScript executions in the page context.
<a <a href="https://user-images.githubusercontent.com/284612/86857568-a6c63100-c073-11ea-82a4-bfd531a4ec87.png"><img src="https://user-images.githubusercontent.com/284612/86857568-a6c63100-c073-11ea-82a4-bfd531a4ec87.png" width="500" alt="Highlight selectors"></a>
href="https://user-images.githubusercontent.com/284612/86857568-a6c63100-c073-11ea-82a4-bfd531a4ec87.png"><img
src="https://user-images.githubusercontent.com/284612/86857568-a6c63100-c073-11ea-82a4-bfd531a4ec87.png"
width="500" alt="Highlight selectors"></a>
## Verbose API logs ## Verbose API logs
@ -146,44 +108,44 @@ $ set DEBUG=pw:api
$ npm run test $ npm run test
``` ```
[Playwright]: api.md#class-playwright "Playwright" [Playwright]: api/class-playwright.md "Playwright"
[Browser]: api.md#class-browser "Browser" [Browser]: api/class-browser.md "Browser"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api.md#class-page "Page" [Page]: api/class-page.md "Page"
[Frame]: api.md#class-frame "Frame" [Frame]: api/class-frame.md "Frame"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api.md#class-dialog "Dialog" [Dialog]: api/class-dialog.md "Dialog"
[Download]: api.md#class-download "Download" [Download]: api/class-download.md "Download"
[Video]: api.md#class-video "Video" [Video]: api/class-video.md "Video"
[FileChooser]: api.md#class-filechooser "FileChooser" [FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api.md#class-keyboard "Keyboard" [Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api.md#class-mouse "Mouse" [Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api.md#class-request "Request" [Request]: api/class-request.md "Request"
[Response]: api.md#class-response "Response" [Response]: api/class-response.md "Response"
[Selectors]: api.md#class-selectors "Selectors" [Selectors]: api/class-selectors.md "Selectors"
[Route]: api.md#class-route "Route" [Route]: api/class-route.md "Route"
[WebSocket]: api.md#class-websocket "WebSocket" [WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api.md#class-accessibility "Accessibility" [Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api.md#class-worker "Worker" [Worker]: api/class-worker.md "Worker"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api.md#class-browsertype "BrowserType" [BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api.md#class-logger "Logger" [Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api.md#class-cdpsession "CDPSession" [CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -2,7 +2,6 @@
[Dockerfile.bionic](Dockerfile.bionic) and [Dockerfile.focal](Dockerfile.focal) can be used to run Playwright scripts in Docker environments. These images includes all the dependencies needed to run browsers in a Docker container, including browsers. [Dockerfile.bionic](Dockerfile.bionic) and [Dockerfile.focal](Dockerfile.focal) can be used to run Playwright scripts in Docker environments. These images includes all the dependencies needed to run browsers in a Docker container, including browsers.
<!-- GEN:toc -->
- [Usage](#usage) - [Usage](#usage)
* [Pull the image](#pull-the-image) * [Pull the image](#pull-the-image)
* [Run the image](#run-the-image) * [Run the image](#run-the-image)
@ -17,7 +16,6 @@
* [Ubuntu 20](#ubuntu-20) * [Ubuntu 20](#ubuntu-20)
* [Ubuntu 18](#ubuntu-18) * [Ubuntu 18](#ubuntu-18)
* [Alpine](#alpine) * [Alpine](#alpine)
<!-- GEN:stop -->
## Usage ## Usage

View file

@ -1,18 +1,16 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: emulation
title: "Device and environment emulation"
---
# Device and environment emulation Playwright allows overriding various parameters of the device where the browser is running:
Playwright allows overriding various parameters of the device where the browser
is running:
- viewport size, device scale factor, touch support - viewport size, device scale factor, touch support
- locale, timezone - locale, timezone
- color scheme - color scheme
- geolocation - geolocation
Most of these parameters are configured during the browser context construction, Most of these parameters are configured during the browser context construction, but some of them such as viewport size can be changed for individual pages.
but some of them such as viewport size can be changed for individual pages.
<!-- GEN:toc-top-level -->
- [Devices](#devices) - [Devices](#devices)
- [User agent](#user-agent) - [User agent](#user-agent)
- [Viewport](#viewport) - [Viewport](#viewport)
@ -20,14 +18,12 @@ but some of them such as viewport size can be changed for individual pages.
- [Permissions](#permissions) - [Permissions](#permissions)
- [Geolocation](#geolocation) - [Geolocation](#geolocation)
- [Color scheme and media](#color-scheme-and-media) - [Color scheme and media](#color-scheme-and-media)
<!-- GEN:stop -->
<br/> <br/>
## Devices ## Devices
Playwright comes with a registry of device parameters for selected mobile Playwright comes with a registry of device parameters for selected mobile devices. It can be used to simulate browser behavior on a mobile device:
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');
@ -42,8 +38,8 @@ const context = await browser.newContext({
All pages created in the context above will share the same device parameters. All pages created in the context above will share the same device parameters.
#### API reference #### API reference
- [playwright.devices](./api.md#playwrightdevices) - [playwright.devices](api/class-playwright.md#playwrightdevices)
- [browser.newContext([options])](./api.md#browsernewcontextoptions) - [browser.newContext([options])](api/class-browser.md#browsernewcontextoptions)
<br/> <br/>
@ -58,7 +54,7 @@ const context = await browser.newContext({
``` ```
#### API reference #### API reference
- [browser.newContext([options])](./api.md#browsernewcontextoptions) - [browser.newContext([options])](api/class-browser.md#browsernewcontextoptions)
<br/> <br/>
@ -83,8 +79,8 @@ const context = await browser.newContext({
``` ```
#### API reference #### API reference
- [browser.newContext([options])](./api.md#browsernewcontextoptions) - [browser.newContext([options])](api/class-browser.md#browsernewcontextoptions)
- [page.setViewportSize(viewportSize)](./api.md#pagesetviewportsizeviewportsize) - [page.setViewportSize(viewportSize)](api/class-page.md#pagesetviewportsizeviewportsize)
<br/> <br/>
@ -99,7 +95,7 @@ const context = await browser.newContext({
``` ```
#### API reference #### API reference
- [browser.newContext([options])](./api.md#browsernewcontextoptions) - [browser.newContext([options])](api/class-browser.md#browsernewcontextoptions)
<br/> <br/>
@ -132,9 +128,9 @@ await context.clearPermissions();
``` ```
#### API reference #### API reference
- [browser.newContext([options])](./api.md#browsernewcontextoptions) - [browser.newContext([options])](api/class-browser.md#browsernewcontextoptions)
- [browserContext.grantPermissions(permissions[, options])](./api.md#browsercontextgrantpermissionspermissions-options) - [browserContext.grantPermissions(permissions[, options])](api/class-browsercontext.md#browsercontextgrantpermissionspermissions-options)
- [browserContext.clearPermissions()](./api.md#browsercontextclearpermissions) - [browserContext.clearPermissions()](api/class-browsercontext.md#browsercontextclearpermissions)
<br/> <br/>
@ -156,15 +152,14 @@ await context.setGeolocation({ longitude: 29.979097, latitude: 31.134256 });
**Note** you can only change geolocation for all pages in the context. **Note** you can only change geolocation for all pages in the context.
#### API reference #### API reference
- [browser.newContext([options])](./api.md#browsernewcontextoptions) - [browser.newContext([options])](api/class-browser.md#browsernewcontextoptions)
- [browserContext.setGeolocation(geolocation)](./api.md#browsercontextsetgeolocationgeolocation) - [browserContext.setGeolocation(geolocation)](api/class-browsercontext.md#browsercontextsetgeolocationgeolocation)
<br/> <br/>
## Color scheme and media ## Color scheme and media
Create a context with dark or light mode. Pages created in this context will Create a context with dark or light mode. Pages created in this context will follow this color scheme preference.
follow this color scheme preference.
```js ```js
// Create context with dark mode // Create context with dark mode
@ -185,46 +180,46 @@ await page.emulateMedia({ media: 'print' });
``` ```
#### API reference #### API reference
- [browser.newContext([options])](./api.md#browsernewcontextoptions) - [browser.newContext([options])](api/class-browser.md#browsernewcontextoptions)
- [page.emulateMedia(params)](./api.md#pageemulatemediaparams) - [page.emulateMedia(params)](api/class-page.md#pageemulatemediaparams)
[Playwright]: api.md#class-playwright "Playwright" [Playwright]: api/class-playwright.md "Playwright"
[Browser]: api.md#class-browser "Browser" [Browser]: api/class-browser.md "Browser"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api.md#class-page "Page" [Page]: api/class-page.md "Page"
[Frame]: api.md#class-frame "Frame" [Frame]: api/class-frame.md "Frame"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api.md#class-dialog "Dialog" [Dialog]: api/class-dialog.md "Dialog"
[Download]: api.md#class-download "Download" [Download]: api/class-download.md "Download"
[Video]: api.md#class-video "Video" [Video]: api/class-video.md "Video"
[FileChooser]: api.md#class-filechooser "FileChooser" [FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api.md#class-keyboard "Keyboard" [Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api.md#class-mouse "Mouse" [Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api.md#class-request "Request" [Request]: api/class-request.md "Request"
[Response]: api.md#class-response "Response" [Response]: api/class-response.md "Response"
[Selectors]: api.md#class-selectors "Selectors" [Selectors]: api/class-selectors.md "Selectors"
[Route]: api.md#class-route "Route" [Route]: api/class-route.md "Route"
[WebSocket]: api.md#class-websocket "WebSocket" [WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api.md#class-accessibility "Accessibility" [Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api.md#class-worker "Worker" [Worker]: api/class-worker.md "Worker"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api.md#class-browsertype "BrowserType" [BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api.md#class-logger "Logger" [Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api.md#class-cdpsession "CDPSession" [CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -1,35 +1,22 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: extensibility
title: "Extensibility"
---
# Extensibility
<!-- GEN:toc-top-level -->
- [Custom selector engines](#custom-selector-engines) - [Custom selector engines](#custom-selector-engines)
<!-- GEN:stop -->
## Custom selector engines ## Custom selector engines
Playwright supports custom selector engines, registered with Playwright supports custom selector engines, registered with [selectors.register(name, script[, options])](api/class-selectors.md#selectorsregistername-script-options).
[selectors.register(name, script[, options])](./api.md#selectorsregistername-script-options).
Selector engine should have the following properties: Selector engine should have the following properties:
- `create` function to create a relative selector from `root` (root is either - `create` function to create a relative selector from `root` (root is either a `Document`, `ShadowRoot` or `Element`) to a `target` element.
a `Document`, `ShadowRoot` or `Element`) to a `target` element. - `query` function to query first element matching `selector` relative to the `root`.
- `query` function to query first element matching `selector` relative to the - `queryAll` function to query all elements matching `selector` relative to the `root`.
`root`.
- `queryAll` function to query all elements matching `selector` relative to
the `root`.
By default the engine is run directly in the frame's JavaScript context and, for By default the engine is run directly in the frame's JavaScript context and, for example, can call an application-defined function. To isolate the engine from any JavaScript in the frame, but leave access to the DOM, register the engine with `{contentScript: true}` option. Content script engine is safer because it is protected from any tampering with the global objects, for example altering `Node.prototype` methods. All built-in selector engines run as content scripts. Note that running as a content script is not guaranteed when the engine is used together with other custom engines.
example, can call an application-defined function. To isolate the engine from
any JavaScript in the frame, but leave access to the DOM, register the engine
with `{contentScript: true}` option. Content script engine is safer because it
is protected from any tampering with the global objects, for example altering
`Node.prototype` methods. All built-in selector engines run as content scripts.
Note that running as a content script is not guaranteed when the engine is used
together with other custom engines.
An example of registering selector engine that queries elements based on a tag An example of registering selector engine that queries elements based on a tag name:
name:
```js ```js
// Must be a function that evaluates to a selector engine instance. // Must be a function that evaluates to a selector engine instance.
@ -58,44 +45,44 @@ await page.click('tag=div >> span >> "Click me"');
const buttonCount = await page.$$eval('tag=button', buttons => buttons.length); const buttonCount = await page.$$eval('tag=button', buttons => buttons.length);
``` ```
[Playwright]: api.md#class-playwright "Playwright" [Playwright]: api/class-playwright.md "Playwright"
[Browser]: api.md#class-browser "Browser" [Browser]: api/class-browser.md "Browser"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api.md#class-page "Page" [Page]: api/class-page.md "Page"
[Frame]: api.md#class-frame "Frame" [Frame]: api/class-frame.md "Frame"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api.md#class-dialog "Dialog" [Dialog]: api/class-dialog.md "Dialog"
[Download]: api.md#class-download "Download" [Download]: api/class-download.md "Download"
[Video]: api.md#class-video "Video" [Video]: api/class-video.md "Video"
[FileChooser]: api.md#class-filechooser "FileChooser" [FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api.md#class-keyboard "Keyboard" [Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api.md#class-mouse "Mouse" [Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api.md#class-request "Request" [Request]: api/class-request.md "Request"
[Response]: api.md#class-response "Response" [Response]: api/class-response.md "Response"
[Selectors]: api.md#class-selectors "Selectors" [Selectors]: api/class-selectors.md "Selectors"
[Route]: api.md#class-route "Route" [Route]: api/class-route.md "Route"
[WebSocket]: api.md#class-websocket "WebSocket" [WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api.md#class-accessibility "Accessibility" [Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api.md#class-worker "Worker" [Worker]: api/class-worker.md "Worker"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api.md#class-browsertype "BrowserType" [BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api.md#class-logger "Logger" [Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api.md#class-cdpsession "CDPSession" [CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -1,8 +1,8 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: input
title: "Input"
---
# Input
<!-- GEN:toc-top-level -->
- [Text input](#text-input) - [Text input](#text-input)
- [Checkboxes and radio buttons](#checkboxes-and-radio-buttons) - [Checkboxes and radio buttons](#checkboxes-and-radio-buttons)
- [Select options](#select-options) - [Select options](#select-options)
@ -11,16 +11,10 @@
- [Keys and shortcuts](#keys-and-shortcuts) - [Keys and shortcuts](#keys-and-shortcuts)
- [Upload files](#upload-files) - [Upload files](#upload-files)
- [Focus element](#focus-element) - [Focus element](#focus-element)
<!-- GEN:stop -->
<br/>
## Text input ## Text input
This is the easiest way to fill out the form fields. It focuses the element and 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>`, `[contenteditable]` and `<label>` associated with an input or textarea.
triggers an `input` event with the entered text. It works for `<input>`,
`<textarea>`, `[contenteditable]` and `<label>` associated with an input or
textarea.
```js ```js
// Text input // Text input
@ -40,17 +34,15 @@ await page.fill('text=First Name', 'Peter');
``` ```
#### API reference #### API reference
- [page.fill(selector, value[, options])](./api.md#pagefillselector-value-options) - [page.fill(selector, value[, options])](api/class-page.md#pagefillselector-value-options)
- [frame.fill(selector, value[, options])](./api.md#framefillselector-value-options) - [frame.fill(selector, value[, options])](api/class-frame.md#framefillselector-value-options)
- [elementHandle.fill(value[, options])](./api.md#elementhandlefillvalue-options) - [elementHandle.fill(value[, options])](api/class-elementhandle.md#elementhandlefillvalue-options)
<br/> <br/>
## Checkboxes and radio buttons ## Checkboxes and radio buttons
This is the easiest way to check and uncheck a checkbox or a radio button. This This is the easiest way to check and uncheck a checkbox or a radio button. This method can be used with `input[type=checkbox]`, `input[type=radio]`, `[role=checkbox]` or `label` associated with checkbox or radio button.
method can be used with `input[type=checkbox]`, `input[type=radio]`,
`[role=checkbox]` or `label` associated with checkbox or radio button.
```js ```js
// Check the checkbox // Check the checkbox
@ -64,20 +56,18 @@ await page.check('text=XL');
``` ```
#### API reference #### API reference
- [page.check(selector[, options])](./api.md#pagecheckselector-options) - [page.check(selector[, options])](api/class-page.md#pagecheckselector-options)
- [page.uncheck(selector[, options])](./api.md#pageuncheckselector-options) - [page.uncheck(selector[, options])](api/class-page.md#pageuncheckselector-options)
- [frame.check(selector[, options])](./api.md#framecheckselector-options) - [frame.check(selector[, options])](api/class-frame.md#framecheckselector-options)
- [frame.uncheck(selector[, options])](./api.md#frameuncheckselector-options) - [frame.uncheck(selector[, options])](api/class-frame.md#frameuncheckselector-options)
- [elementHandle.check([options])](./api.md#elementhandlecheckoptions) - [elementHandle.check([options])](api/class-elementhandle.md#elementhandlecheckoptions)
- [elementHandle.uncheck([options])](./api.md#elementhandleuncheckoptions) - [elementHandle.uncheck([options])](api/class-elementhandle.md#elementhandleuncheckoptions)
<br/> <br/>
## Select options ## Select options
Selects one or multiple options in the `<select>` element. You can specify Selects one or multiple options in the `<select>` element. You can specify option `value`, `label` or `elementHandle` to select. Multiple options can be selected.
option `value`, `label` or `elementHandle` to select. Multiple options can be
selected.
```js ```js
// Single selection matching the value // Single selection matching the value
@ -95,9 +85,9 @@ await page.selectOption('select#colors', option);
``` ```
#### API reference #### API reference
- [page.selectOption(selector, values[, options])](./api.md#pageselectoptionselector-values-options) - [page.selectOption(selector, values[, options])](api/class-page.md#pageselectoptionselector-values-options)
- [frame.selectOption(selector, values[, options])](./api.md#frameselectoptionselector-values-options) - [frame.selectOption(selector, values[, options])](api/class-frame.md#frameselectoptionselector-values-options)
- [elementHandle.selectOption(values[, options])](./api.md#elementhandleselectoptionvalues-options) - [elementHandle.selectOption(values[, options])](api/class-elementhandle.md#elementhandleselectoptionvalues-options)
<br/> <br/>
@ -127,21 +117,15 @@ await page.click('#item', { position: { x: 0, y: 0} });
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 - wait for it to become displayed, i.e. not empty, no `display:none`, no `visibility:hidden`
`visibility:hidden`
- wait for it to stop moving, for example, until css transition finishes - wait for it to stop moving, for example, until css transition finishes
- scroll the element into view - scroll the element into view
- wait for it to receive pointer events at the action point, for example, - wait for it to receive pointer events at the action point, for example, waits until element becomes non-obscured by other elements
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
#### Forcing the click #### Forcing the click
Sometimes, apps use non-trivial logic where hovering the element overlays it Sometimes, apps use non-trivial logic where hovering the element overlays it with another element that intercepts the click. This behavior is indistinguishable from a bug where element gets covered and the click is dispatched elsewhere. If you know this is taking place, you can bypass the [actionability](./actionability.md) checks and force the click:
with another element that intercepts the click. This behavior is
indistinguishable from a bug where element gets covered and the click is
dispatched elsewhere. If you know this is taking place, you can bypass the
[actionability](./actionability.md) checks and force the click:
```js ```js
await page.click('button#submit', { force: true }); await page.click('button#submit', { force: true });
@ -149,53 +133,46 @@ await page.click('button#submit', { force: true });
#### Programmatic click #### Programmatic click
If you are not interested in testing your app under the real conditions and want If you are not interested in testing your app under the real conditions and want to simulate the click by any means possible, you can trigger the [`HTMLElement.click()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click) behavior via simply dispatching a click event on the element:
to simulate the click by any means possible, you can trigger the
[`HTMLElement.click()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click)
behavior via simply dispatching a click event on the element:
```js ```js
await page.dispatchEvent('button#submit', 'click'); await page.dispatchEvent('button#submit', 'click');
``` ```
#### API reference #### API reference
- [page.click(selector[, options])](./api.md#pageclickselector-options) - [page.click(selector[, options])](api/class-page.md#pageclickselector-options)
- [frame.click(selector[, options])](./api.md#frameclickselector-options) - [frame.click(selector[, options])](api/class-frame.md#frameclickselector-options)
- [elementHandle.click([options])](./api.md#elementhandleclickoptions) - [elementHandle.click([options])](api/class-elementhandle.md#elementhandleclickoptions)
- [page.dblclick(selector[, options])](./api.md#pagedblclickselector-options) - [page.dblclick(selector[, options])](api/class-page.md#pagedblclickselector-options)
- [frame.dblclick(selector[, options])](./api.md#framedblclickselector-options) - [frame.dblclick(selector[, options])](api/class-frame.md#framedblclickselector-options)
- [elementHandle.dblclick([options])](./api.md#elementhandledblclickoptions) - [elementHandle.dblclick([options])](api/class-elementhandle.md#elementhandledblclickoptions)
- [page.hover(selector[, options])](./api.md#pagehoverselector-options) - [page.hover(selector[, options])](api/class-page.md#pagehoverselector-options)
- [frame.hover(selector[, options])](./api.md#framehoverselector-options) - [frame.hover(selector[, options])](api/class-frame.md#framehoverselector-options)
- [elementHandle.hover([options])](./api.md#elementhandlehoveroptions) - [elementHandle.hover([options])](api/class-elementhandle.md#elementhandlehoveroptions)
- [page.dispatchEvent(selector, type[, eventInit, options])](./api.md#pagedispatcheventselector-type-eventinit-options) - [page.dispatchEvent(selector, type[, eventInit, options])](api/class-page.md#pagedispatcheventselector-type-eventinit-options)
- [frame.dispatchEvent(selector, type[, eventInit, options])](./api.md#framedispatcheventselector-type-eventinit-options) - [frame.dispatchEvent(selector, type[, eventInit, options])](api/class-frame.md#framedispatcheventselector-type-eventinit-options)
- [elementHandle.dispatchEvent(type[, eventInit])](./api.md#elementhandledispatcheventtype-eventinit) - [elementHandle.dispatchEvent(type[, eventInit])](api/class-elementhandle.md#elementhandledispatcheventtype-eventinit)
<br/> <br/>
## Type characters ## Type characters
Type into the field character by character, as if it was a user with a real Type into the field character by character, as if it was a user with a real keyboard.
keyboard.
```js ```js
// Type character by character // Type character by character
await page.type('#area', 'Hello World!'); await page.type('#area', 'Hello World!');
``` ```
This method will emit all the necessary keyboard events, with all the `keydown`, 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.
`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 > **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.
only need to type characters if there is special keyboard handling on the page.
#### API reference #### API reference
- [page.type(selector, text[, options])](./api.md#pagetypeselector-text-options) - [page.type(selector, text[, options])](api/class-page.md#pagetypeselector-text-options)
- [frame.type(selector, text[, options])](./api.md#frametypeselector-text-options) - [frame.type(selector, text[, options])](api/class-frame.md#frametypeselector-text-options)
- [elementHandle.type(text[, options])](./api.md#elementhandletypetext-options) - [elementHandle.type(text[, options])](api/class-elementhandle.md#elementhandletypetext-options)
- [keyboard.type(text[, options])](./api.md#keyboardtypetext-options) - [keyboard.type(text[, options])](api/class-keyboard.md#keyboardtypetext-options)
<br/> <br/>
@ -212,10 +189,7 @@ await page.press('#name', 'Control+ArrowRight');
await page.press('#value', '$'); await page.press('#value', '$');
``` ```
This method focuses the selected element and produces a single keystroke. It This method focuses the selected element and produces a single keystroke. It accepts the logical key names that are emitted in the [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) property of the keyboard events:
accepts the logical key names that are emitted in the
[keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key)
property of the keyboard events:
``` ```
Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape, Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape,
@ -223,13 +197,10 @@ ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight,
ArrowUp, F1 - F12, Digit0 - Digit9, KeyA - KeyZ, etc. ArrowUp, F1 - F12, Digit0 - Digit9, KeyA - KeyZ, etc.
``` ```
- You can alternatively specify a single character you'd like to produce such - You can alternatively specify a single character you'd like to produce such as `"a"` or `"#"`.
as `"a"` or `"#"`. - Following modification shortcuts are also supported: `Shift, Control, Alt, Meta`.
- Following modification shortcuts are also supported: `Shift, Control, Alt,
Meta`.
Simple version produces a single character. This character is case-sensitive, so Simple version produces a single character. This character is case-sensitive, so `"a"` and `"A"` will produce different results.
`"a"` and `"A"` will produce different results.
```js ```js
// <input id=name> // <input id=name>
@ -239,19 +210,15 @@ await page.press('#name', 'Shift+A');
await page.press('#name', 'Shift+ArrowLeft'); await page.press('#name', 'Shift+ArrowLeft');
``` ```
Shortcuts such as `"Control+o"` or `"Control+Shift+T"` are supported as well. Shortcuts such as `"Control+o"` or `"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.
When specified with the modifier, modifier is pressed and being held while the
subsequent key is being pressed.
Note that you still need to specify the capital `A` in `Shift-A` to produce the Note that you still need to specify the capital `A` in `Shift-A` to produce the capital character. `Shift-a` produces a lower-case one as if you had the `CapsLock` toggled.
capital character. `Shift-a` produces a lower-case one as if you had the
`CapsLock` toggled.
#### API reference #### API reference
- [page.press(selector, key[, options])](./api.md#pagepressselector-key-options) - [page.press(selector, key[, options])](api/class-page.md#pagepressselector-key-options)
- [frame.press(selector, key[, options])](./api.md#framepressselector-key-options) - [frame.press(selector, key[, options])](api/class-frame.md#framepressselector-key-options)
- [elementHandle.press(key[, options])](./api.md#elementhandlepresskey-options) - [elementHandle.press(key[, options])](api/class-elementhandle.md#elementhandlepresskey-options)
- [keyboard.press(key[, options])](./api.md#keyboardpresskey-options) - [keyboard.press(key[, options])](api/class-keyboard.md#keyboardpresskey-options)
<br/> <br/>
@ -275,23 +242,16 @@ await page.setInputFiles('input#upload', {
}); });
``` ```
You can select input files for upload using the `page.setInputFiles` method. It 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.
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.
#### Example #### Example
[This script](examples/upload.js) uploads a file to an `input` element that [This script](examples/upload.js) uploads a file to an `input` element that accepts file uploads.
accepts file uploads.
#### API reference #### API reference
- [page.setInputFiles(selector, files[, options])](./api.md#pagesetinputfilesselector-files-options) - [page.setInputFiles(selector, files[, options])](api/class-page.md#pagesetinputfilesselector-files-options)
- [frame.setInputFiles(selector, files[, options])](./api.md#framesetinputfilesselector-files-options) - [frame.setInputFiles(selector, files[, options])](api/class-frame.md#framesetinputfilesselector-files-options)
- [elementHandle.setInputFiles(files[, options])](./api.md#elementhandlesetinputfilesfiles-options) - [elementHandle.setInputFiles(files[, options])](api/class-elementhandle.md#elementhandlesetinputfilesfiles-options)
<br/> <br/>
@ -304,49 +264,49 @@ await page.focus('input#name');
``` ```
#### API reference #### API reference
- [page.focus(selector[, options])](./api.md#pagefocusselector-options) - [page.focus(selector[, options])](api/class-page.md#pagefocusselector-options)
- [frame.focus(selector[, options])](./api.md#framefocusselector-options) - [frame.focus(selector[, options])](api/class-frame.md#framefocusselector-options)
- [elementHandle.focus()](./api.md#elementhandlefocus) - [elementHandle.focus()](api/class-elementhandle.md#elementhandlefocus)
<br/> <br/>
[Playwright]: api.md#class-playwright "Playwright" [Playwright]: api/class-playwright.md "Playwright"
[Browser]: api.md#class-browser "Browser" [Browser]: api/class-browser.md "Browser"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api.md#class-page "Page" [Page]: api/class-page.md "Page"
[Frame]: api.md#class-frame "Frame" [Frame]: api/class-frame.md "Frame"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api.md#class-dialog "Dialog" [Dialog]: api/class-dialog.md "Dialog"
[Download]: api.md#class-download "Download" [Download]: api/class-download.md "Download"
[Video]: api.md#class-video "Video" [Video]: api/class-video.md "Video"
[FileChooser]: api.md#class-filechooser "FileChooser" [FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api.md#class-keyboard "Keyboard" [Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api.md#class-mouse "Mouse" [Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api.md#class-request "Request" [Request]: api/class-request.md "Request"
[Response]: api.md#class-response "Response" [Response]: api/class-response.md "Response"
[Selectors]: api.md#class-selectors "Selectors" [Selectors]: api/class-selectors.md "Selectors"
[Route]: api.md#class-route "Route" [Route]: api/class-route.md "Route"
[WebSocket]: api.md#class-websocket "WebSocket" [WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api.md#class-accessibility "Accessibility" [Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api.md#class-worker "Worker" [Worker]: api/class-worker.md "Worker"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api.md#class-browsertype "BrowserType" [BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api.md#class-logger "Logger" [Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api.md#class-cdpsession "CDPSession" [CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -1,21 +1,16 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: installation
title: "Advanced installation"
---
# Advanced installation
<!-- GEN:toc -->
- [Managing browser binaries](#managing-browser-binaries) - [Managing browser binaries](#managing-browser-binaries)
- [Download from artifact repository](#download-from-artifact-repository) - [Download from artifact repository](#download-from-artifact-repository)
- [Skip browser downloads](#skip-browser-downloads) - [Skip browser downloads](#skip-browser-downloads)
- [Download single browser binary](#download-single-browser-binary) - [Download single browser binary](#download-single-browser-binary)
<!-- GEN:stop -->
<br>
## Managing browser binaries ## Managing browser binaries
Each version of Playwright needs specific versions of browser binaries to Each version of Playwright needs specific versions of browser binaries to operate. By default Playwright downloads Chromium, WebKit and Firefox browsers into the OS-specific cache folders:
operate. By default Playwright downloads Chromium, WebKit and Firefox browsers
into the OS-specific cache folders:
- `%USERPROFILE%\AppData\Local\ms-playwright` on Windows - `%USERPROFILE%\AppData\Local\ms-playwright` on Windows
- `~/Library/Caches/ms-playwright` on MacOS - `~/Library/Caches/ms-playwright` on MacOS
- `~/.cache/ms-playwright` on Linux - `~/.cache/ms-playwright` on Linux
@ -24,8 +19,7 @@ into the OS-specific cache folders:
npm i -D playwright npm i -D playwright
``` ```
These browsers will take few hundreds of megabytes of the disk space when These browsers will take few hundreds of megabytes of the disk space when installed:
installed:
```sh ```sh
du -hs ./Library/Caches/ms-playwright/* du -hs ./Library/Caches/ms-playwright/*
@ -34,8 +28,7 @@ du -hs ./Library/Caches/ms-playwright/*
180M webkit-XXXX 180M webkit-XXXX
``` ```
You can override default behavior using environment variables. When installing You can override default behavior using environment variables. When installing Playwright, ask it to download browsers into a specific location:
Playwright, ask it to download browsers into a specific location:
```sh ```sh
# Linux/macOS # Linux/macOS
@ -46,8 +39,7 @@ $ set PLAYWRIGHT_BROWSERS_PATH=%USERPROFILE%\pw-browsers
$ npm i -D playwright $ npm i -D playwright
``` ```
When running Playwright scripts, ask it to search for browsers in a shared When running Playwright scripts, ask it to search for browsers in a shared location:
location:
```sh ```sh
# Linux/macOS # Linux/macOS
@ -58,8 +50,7 @@ $ set PLAYWRIGHT_BROWSERS_PATH=%USERPROFILE%\pw-browsers
$ node playwright-script.js $ node playwright-script.js
``` ```
Or you can opt into the hermetic install and place binaries under the Or you can opt into the hermetic install and place binaries under the `node_modules/` folder:
`node_modules/` folder:
```sh ```sh
# Linux/macOS # Linux/macOS
@ -70,13 +61,11 @@ $ set PLAYWRIGHT_BROWSERS_PATH=0
$ npm i -D playwright $ npm i -D playwright
``` ```
Playwright keeps track of packages that need those browsers and will garbage Playwright keeps track of packages that need those browsers and will garbage collect them as you update Playwright to the newer versions.
collect them as you update Playwright to the newer versions.
<br> <br>
> **NOTE** Developers can opt-in in this mode via exporting > **NOTE** Developers can opt-in in this mode via exporting `PLAYWRIGHT_BROWSERS_PATH=$HOME/pw-browsers` in their `.bashrc`.
`PLAYWRIGHT_BROWSERS_PATH=$HOME/pw-browsers` in their `.bashrc`.
<br> <br>
@ -84,9 +73,7 @@ collect them as you update Playwright to the newer versions.
By default, Playwright downloads browsers from Microsoft and Google public CDNs. By default, Playwright downloads browsers from Microsoft and Google public CDNs.
Sometimes companies maintain an internal artifact repository to host browser Sometimes companies maintain an internal artifact repository to host browser binaries. In this case, Playwright can be configured to download from a custom location using the `PLAYWRIGHT_DOWNLOAD_HOST` env variable.
binaries. In this case, Playwright can be configured to download from a custom
location using the `PLAYWRIGHT_DOWNLOAD_HOST` env variable.
```sh ```sh
# Linux/macOS # Linux/macOS
@ -97,10 +84,7 @@ $ set PLAYWRIGHT_DOWNLOAD_HOST=192.168.1.78
$ npm i -D playwright $ npm i -D playwright
``` ```
It is also possible to use a per-browser download hosts using It is also possible to use a per-browser download hosts using `PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST`, `PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST` and `PLAYWRIGHT_WEBKIT_DOWNLOAD_HOST` env variables that take precedence over `PLAYWRIGHT_DOWNLOAD_HOST`.
`PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST`, `PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST` and
`PLAYWRIGHT_WEBKIT_DOWNLOAD_HOST` env variables that take precedence over
`PLAYWRIGHT_DOWNLOAD_HOST`.
```sh ```sh
# Linux/macOS # Linux/macOS
@ -111,11 +95,9 @@ $ PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST=192.168.1.1 PLAYWRIGHT_DOWNLOAD_HOST=192.168.
## Skip browser downloads ## Skip browser downloads
In certain cases, it is desired to avoid browser downloads altogether because In certain cases, it is desired to avoid browser downloads altogether because browser binaries are managed separately.
browser binaries are managed separately.
This can be done by setting `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` variable before This can be done by setting `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` variable before installation.
installation.
```sh ```sh
# Linux/macOS # Linux/macOS
@ -157,44 +139,44 @@ const { webkit } = require('playwright-webkit');
})(); })();
``` ```
[Playwright]: api.md#class-playwright "Playwright" [Playwright]: api/class-playwright.md "Playwright"
[Browser]: api.md#class-browser "Browser" [Browser]: api/class-browser.md "Browser"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api.md#class-page "Page" [Page]: api/class-page.md "Page"
[Frame]: api.md#class-frame "Frame" [Frame]: api/class-frame.md "Frame"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api.md#class-dialog "Dialog" [Dialog]: api/class-dialog.md "Dialog"
[Download]: api.md#class-download "Download" [Download]: api/class-download.md "Download"
[Video]: api.md#class-video "Video" [Video]: api/class-video.md "Video"
[FileChooser]: api.md#class-filechooser "FileChooser" [FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api.md#class-keyboard "Keyboard" [Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api.md#class-mouse "Mouse" [Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api.md#class-request "Request" [Request]: api/class-request.md "Request"
[Response]: api.md#class-response "Response" [Response]: api/class-response.md "Response"
[Selectors]: api.md#class-selectors "Selectors" [Selectors]: api/class-selectors.md "Selectors"
[Route]: api.md#class-route "Route" [Route]: api/class-route.md "Route"
[WebSocket]: api.md#class-websocket "WebSocket" [WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api.md#class-accessibility "Accessibility" [Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api.md#class-worker "Worker" [Worker]: api/class-worker.md "Worker"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api.md#class-browsertype "BrowserType" [BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api.md#class-logger "Logger" [Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api.md#class-cdpsession "CDPSession" [CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -1,33 +1,28 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: intro
title: "Getting Started"
---
# Getting Started
<!-- GEN:toc-top-level -->
- [Installation](#installation) - [Installation](#installation)
- [Usage](#usage) - [Usage](#usage)
- [First script](#first-script) - [First script](#first-script)
- [Record scripts](#record-scripts) - [Record scripts](#record-scripts)
- [TypeScript support](#typescript-support) - [TypeScript support](#typescript-support)
- [System requirements](#system-requirements) - [System requirements](#system-requirements)
<!-- GEN:stop -->
## Installation ## Installation
Use npm or Yarn to install Playwright in your Node.js project. See Use npm or Yarn to install Playwright in your Node.js project. See [system requirements](#system-requirements).
[system requirements](#system-requirements).
```sh ```sh
npm i -D playwright npm i -D playwright
``` ```
This single command downloads the Playwright NPM package and browser binaries This single command downloads the Playwright NPM package and browser binaries for Chromium, Firefox and WebKit. To modify this behavior see [installation parameters](./installation.md).
for Chromium, Firefox and WebKit. To modify this behavior see
[installation parameters](./installation.md).
## Usage ## Usage
Once installed, you can `require` Playwright in a Node.js script, and launch any Once installed, you can `require` Playwright in a Node.js script, and launch any of the 3 browsers (`chromium`, `firefox` and `webkit`).
of the 3 browsers (`chromium`, `firefox` and `webkit`).
```js ```js
const { chromium } = require('playwright'); const { chromium } = require('playwright');
@ -39,11 +34,7 @@ const { chromium } = require('playwright');
})(); })();
``` ```
Playwright APIs are asynchronous and return Promise objects. Our code examples Playwright APIs are asynchronous and return Promise objects. Our code examples use [the async/await pattern](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await) to ease readability. The code is wrapped in an unnamed async arrow function which is invoking itself.
use
[the async/await pattern](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await)
to ease readability. The code is wrapped in an unnamed async arrow function
which is invoking itself.
```js ```js
(async () => { // Start of async arrow function (async () => { // Start of async arrow function
@ -54,8 +45,7 @@ which is invoking itself.
## First script ## First script
In our first script, we will navigate to `whatsmyuseragent.org` and take a In our first script, we will navigate to `whatsmyuseragent.org` and take a screenshot in WebKit.
screenshot in WebKit.
```js ```js
const { webkit } = require('playwright'); const { webkit } = require('playwright');
@ -69,9 +59,7 @@ const { webkit } = require('playwright');
})(); })();
``` ```
By default, Playwright runs the browsers in headless mode. To see the browser By default, Playwright runs the browsers in headless mode. To see the browser UI, pass the `headless: false` flag while launching the browser. You can also use `slowMo` to slow down execution.
UI, pass the `headless: false` flag while launching the browser. You can also
use `slowMo` to slow down execution.
```js ```js
firefox.launch({ headless: false, slowMo: 50 }); firefox.launch({ headless: false, slowMo: 50 });
@ -79,8 +67,7 @@ firefox.launch({ headless: false, slowMo: 50 });
## Record scripts ## Record scripts
[Playwright CLI](./cli.md) can be used to record user interactions and generate [Playwright CLI](./cli.md) can be used to record user interactions and generate JavaScript code.
JavaScript code.
```sh ```sh
npx playwright codegen wikipedia.org npx playwright codegen wikipedia.org
@ -88,14 +75,11 @@ npx playwright codegen wikipedia.org
## TypeScript support ## TypeScript support
Playwright includes built-in support for TypeScript. Type definitions will be Playwright includes built-in support for TypeScript. Type definitions will be imported automatically. It is recommended to use type-checking to improve the IDE experience.
imported automatically. It is recommended to use type-checking to improve the
IDE experience.
### In JavaScript ### In JavaScript
Add the following to the top of your JavaScript file to get type-checking in VS Add the following to the top of your JavaScript file to get type-checking in VS Code or WebStorm.
Code or WebStorm.
```js ```js
//@ts-check //@ts-check
@ -111,8 +95,7 @@ let page;
### In TypeScript ### In TypeScript
TypeScript support will work out-of-the-box. Types can also be imported TypeScript support will work out-of-the-box. Types can also be imported explicitly.
explicitly.
```ts ```ts
let page: import('playwright').Page; let page: import('playwright').Page;
@ -120,54 +103,50 @@ let page: import('playwright').Page;
## System requirements ## System requirements
Playwright requires Node.js version 10.17 or above. The browser binaries for Playwright requires Node.js version 10.17 or above. The browser binaries for Chromium, Firefox and WebKit work across the 3 platforms (Windows, macOS, Linux):
Chromium, Firefox and WebKit work across the 3 platforms (Windows, macOS,
Linux):
* **Windows**: Works with Windows and Windows Subsystem for Linux (WSL). * **Windows**: Works with Windows and Windows Subsystem for Linux (WSL).
* **macOS**: Requires 10.14 or above. * **macOS**: Requires 10.14 or above.
* **Linux**: Depending on your Linux distribution, you might need to install * **Linux**: Depending on your Linux distribution, you might need to install additional dependencies to run the browsers.
additional dependencies to run the browsers.
* Firefox requires Ubuntu 18.04+ * Firefox requires Ubuntu 18.04+
* For Ubuntu 18.04, the additional dependencies are defined in * For Ubuntu 18.04, the additional dependencies are defined in [our Docker image](docker/Dockerfile.bionic), which is based on Ubuntu.
[our Docker image](docker/Dockerfile.bionic), which is based on Ubuntu. [Playwright]: api/class-playwright.md "Playwright"
[Playwright]: api.md#class-playwright "Playwright" [Browser]: api/class-browser.md "Browser"
[Browser]: api.md#class-browser "Browser" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [Page]: api/class-page.md "Page"
[Page]: api.md#class-page "Page" [Frame]: api/class-frame.md "Frame"
[Frame]: api.md#class-frame "Frame" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [Dialog]: api/class-dialog.md "Dialog"
[Dialog]: api.md#class-dialog "Dialog" [Download]: api/class-download.md "Download"
[Download]: api.md#class-download "Download" [Video]: api/class-video.md "Video"
[Video]: api.md#class-video "Video" [FileChooser]: api/class-filechooser.md "FileChooser"
[FileChooser]: api.md#class-filechooser "FileChooser" [Keyboard]: api/class-keyboard.md "Keyboard"
[Keyboard]: api.md#class-keyboard "Keyboard" [Mouse]: api/class-mouse.md "Mouse"
[Mouse]: api.md#class-mouse "Mouse" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Request]: api/class-request.md "Request"
[Request]: api.md#class-request "Request" [Response]: api/class-response.md "Response"
[Response]: api.md#class-response "Response" [Selectors]: api/class-selectors.md "Selectors"
[Selectors]: api.md#class-selectors "Selectors" [Route]: api/class-route.md "Route"
[Route]: api.md#class-route "Route" [WebSocket]: api/class-websocket.md "WebSocket"
[WebSocket]: api.md#class-websocket "WebSocket" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [Accessibility]: api/class-accessibility.md "Accessibility"
[Accessibility]: api.md#class-accessibility "Accessibility" [Worker]: api/class-worker.md "Worker"
[Worker]: api.md#class-worker "Worker" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserType]: api/class-browsertype.md "BrowserType"
[BrowserType]: api.md#class-browsertype "BrowserType" [Logger]: api/class-logger.md "Logger"
[Logger]: api.md#class-logger "Logger" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [CDPSession]: api/class-cdpsession.md "CDPSession"
[CDPSession]: api.md#class-cdpsession "CDPSession" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -1,15 +1,14 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: languages
# Supported languages title: "Supported languages"
---
The Playwright API is available in multiple languages. The Playwright API is available in multiple languages.
<!-- GEN:toc -->
- [JavaScript and TypeScript](#javascript-and-typescript) - [JavaScript and TypeScript](#javascript-and-typescript)
- [Python](#python) - [Python](#python)
- [C#](#c) - [C#](#c)
- [Go](#go) - [Go](#go)
<!-- GEN:stop -->
## JavaScript and TypeScript ## JavaScript and TypeScript
@ -55,44 +54,44 @@ go get github.com/mxschmitt/playwright-go
* [GitHub repo](https://github.com/mxschmitt/playwright-go) * [GitHub repo](https://github.com/mxschmitt/playwright-go)
* [Documentation](https://pkg.go.dev/github.com/mxschmitt/playwright-go?tab=doc) * [Documentation](https://pkg.go.dev/github.com/mxschmitt/playwright-go?tab=doc)
[Playwright]: api.md#class-playwright "Playwright" [Playwright]: api/class-playwright.md "Playwright"
[Browser]: api.md#class-browser "Browser" [Browser]: api/class-browser.md "Browser"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api.md#class-page "Page" [Page]: api/class-page.md "Page"
[Frame]: api.md#class-frame "Frame" [Frame]: api/class-frame.md "Frame"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api.md#class-dialog "Dialog" [Dialog]: api/class-dialog.md "Dialog"
[Download]: api.md#class-download "Download" [Download]: api/class-download.md "Download"
[Video]: api.md#class-video "Video" [Video]: api/class-video.md "Video"
[FileChooser]: api.md#class-filechooser "FileChooser" [FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api.md#class-keyboard "Keyboard" [Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api.md#class-mouse "Mouse" [Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api.md#class-request "Request" [Request]: api/class-request.md "Request"
[Response]: api.md#class-response "Response" [Response]: api/class-response.md "Response"
[Selectors]: api.md#class-selectors "Selectors" [Selectors]: api/class-selectors.md "Selectors"
[Route]: api.md#class-route "Route" [Route]: api/class-route.md "Route"
[WebSocket]: api.md#class-websocket "WebSocket" [WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api.md#class-accessibility "Accessibility" [Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api.md#class-worker "Worker" [Worker]: api/class-worker.md "Worker"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api.md#class-browsertype "BrowserType" [BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api.md#class-logger "Logger" [Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api.md#class-cdpsession "CDPSession" [CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -1,22 +1,21 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: mobile
title: "Experimental support for Chrome for Android"
---
# Experimental support for Chrome for Android - [Requirements](#requirements)
- [How to run](#how-to-run)
- [Known limitations](#known-limitations)
You can try Playwright against Chrome for Android today. This support is You can try Playwright against Chrome for Android today. This support is experimental. Support for devices is tracked in the issue [#1122](https://github.com/microsoft/playwright/issues/1122).
experimental. Support for devices is tracked in the issue
[#1122](https://github.com/microsoft/playwright/issues/1122).
## Requirements ## Requirements
- [Playwright 1.6](https://www.npmjs.com/package/playwright) or newer - [Playwright 1.6](https://www.npmjs.com/package/playwright) or newer
- [ADB daemon](https://developer.android.com/studio/command-line/adb) running - [ADB daemon](https://developer.android.com/studio/command-line/adb) running and authenticated with your device.
and authenticated with your device. - [`Chrome 87`](https://play.google.com/store/apps/details?id=com.android.chrome) or newer installed on the device
- [`Chrome 87`](https://play.google.com/store/apps/details?id=com.android.chrome)
or newer installed on the device
- "Enable command line on non-rooted devices" enabled in `chrome://flags`. - "Enable command line on non-rooted devices" enabled in `chrome://flags`.
> Playwright will be looking for ADB daemon on the default port `5037`. It > Playwright will be looking for ADB daemon on the default port `5037`. It will use the first device available. Typically running `adb devices` is all you need to do.
will use the first device available. Typically running `adb devices` is all
you need to do.
## How to run ## How to run
@ -35,57 +34,52 @@ const { _clank } = require('playwright');
})(); })();
``` ```
> > [Clank](https://chromium.googlesource.com/chromium/src/+/master/docs/memory/android_dev_tips.md) is a code name for Chrome for Android.
[Clank](https://chromium.googlesource.com/chromium/src/+/master/docs/memory/android_dev_tips.md)
is a code name for Chrome for Android.
## Known limitations ## Known limitations
- Raw USB operation is not yet supported, so you need ADB. - Raw USB operation is not yet supported, so you need ADB.
- Only `launchPersistentContext` works, launching ephemeral contexts is not - Only `launchPersistentContext` works, launching ephemeral contexts is not supported.
supported. - Passing `viewport: null` is necessary to make sure resolution is not emulated.
- Passing `viewport: null` is necessary to make sure resolution is not - Device needs to be awake to produce screenshots. Enabling "Stay awake" developer mode will help.
emulated.
- Device needs to be awake to produce screenshots. Enabling "Stay awake"
developer mode will help.
- We didn't run all the tests against the device, so not everything works. - We didn't run all the tests against the device, so not everything works.
[Playwright]: api.md#class-playwright "Playwright" [Playwright]: api/class-playwright.md "Playwright"
[Browser]: api.md#class-browser "Browser" [Browser]: api/class-browser.md "Browser"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api.md#class-page "Page" [Page]: api/class-page.md "Page"
[Frame]: api.md#class-frame "Frame" [Frame]: api/class-frame.md "Frame"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api.md#class-dialog "Dialog" [Dialog]: api/class-dialog.md "Dialog"
[Download]: api.md#class-download "Download" [Download]: api/class-download.md "Download"
[Video]: api.md#class-video "Video" [Video]: api/class-video.md "Video"
[FileChooser]: api.md#class-filechooser "FileChooser" [FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api.md#class-keyboard "Keyboard" [Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api.md#class-mouse "Mouse" [Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api.md#class-request "Request" [Request]: api/class-request.md "Request"
[Response]: api.md#class-response "Response" [Response]: api/class-response.md "Response"
[Selectors]: api.md#class-selectors "Selectors" [Selectors]: api/class-selectors.md "Selectors"
[Route]: api.md#class-route "Route" [Route]: api/class-route.md "Route"
[WebSocket]: api.md#class-websocket "WebSocket" [WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api.md#class-accessibility "Accessibility" [Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api.md#class-worker "Worker" [Worker]: api/class-worker.md "Worker"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api.md#class-browsertype "BrowserType" [BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api.md#class-logger "Logger" [Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api.md#class-cdpsession "CDPSession" [CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -1,23 +1,18 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: multi-pages
title: "Multi-page scenarios"
---
# Multi-page scenarios Playwright can automate scenarios that span multiple browser contexts or multiple tabs in a browser window.
Playwright can automate scenarios that span multiple browser contexts or
multiple tabs in a browser window.
<!-- GEN:toc-top-level -->
- [Multiple contexts](#multiple-contexts) - [Multiple contexts](#multiple-contexts)
- [Multiple pages](#multiple-pages) - [Multiple pages](#multiple-pages)
- [Handling new pages](#handling-new-pages) - [Handling new pages](#handling-new-pages)
- [Handling popups](#handling-popups) - [Handling popups](#handling-popups)
<!-- GEN:stop -->
## Multiple contexts ## Multiple contexts
[Browser contexts](core-concepts.md#browser-contexts) are isolated environments [Browser contexts](core-concepts.md#browser-contexts) are isolated environments on a single browser instance. Playwright can create multiple browser contexts within a single scenario. This is useful when you want to test for multi-user functionality, like chat.
on a single browser instance. Playwright can create multiple browser contexts
within a single scenario. This is useful when you want to test for multi-user
functionality, like chat.
```js ```js
const { chromium } = require('playwright'); const { chromium } = require('playwright');
@ -36,16 +31,14 @@ await adminContext.addCookies(adminCookies);
#### API reference #### API reference
- [BrowserContext] - [BrowserContext]
- [browser.newContext([options])](./api.md#browsernewcontextoptions) - [browser.newContext([options])](api/class-browser.md#browsernewcontextoptions)
- [browserContext.addCookies(cookies)](./api.md#browsercontextaddcookiescookies) - [browserContext.addCookies(cookies)](api/class-browsercontext.md#browsercontextaddcookiescookies)
## Multiple pages ## Multiple pages
Each browser context can host multiple pages (tabs). Each browser context can host multiple pages (tabs).
* Each page behaves like a focused, active page. Bringing the page to front is * Each page behaves like a focused, active page. Bringing the page to front is not required.
not required. * Pages inside a context respect context-level emulation, like viewport sizes, custom network routes or browser locale.
* Pages inside a context respect context-level emulation, like viewport sizes,
custom network routes or browser locale.
```js ```js
// Create two pages // Create two pages
@ -58,14 +51,12 @@ const allPages = context.pages();
#### API reference #### API reference
- [Page] - [Page]
- [browserContext.newPage()](./api.md#browsercontextnewpage) - [browserContext.newPage()](api/class-browsercontext.md#browsercontextnewpage)
- [browserContext.pages()](./api.md#browsercontextpages) - [browserContext.pages()](api/class-browsercontext.md#browsercontextpages)
## Handling new pages ## Handling new pages
The `page` event on browser contexts can be used to get new pages that are The `page` event on browser contexts can be used to get new pages that are created in the context. This can be used to handle new pages opened by `target="_blank"` links.
created in the context. This can be used to handle new pages opened by
`target="_blank"` links.
```js ```js
// Get page after a specific action (e.g. clicking a link) // Get page after a specific action (e.g. clicking a link)
@ -77,8 +68,7 @@ await newPage.waitForLoadState();
console.log(await newPage.title()); console.log(await newPage.title());
``` ```
If the action that triggers the new page is unknown, the following pattern can If the action that triggers the new page is unknown, the following pattern can be used.
be used.
```js ```js
// Get all new pages (including popups) in the context // Get all new pages (including popups) in the context
@ -89,15 +79,13 @@ context.on('page', async page => {
``` ```
#### API reference #### API reference
- [browserContext.on('page')](./api.md#browsercontextonpage) - [browserContext.on('page')](api/class-browsercontext.md#browsercontextonpage)
## Handling popups ## Handling popups
If the page opens a pop-up, you can get a reference to it by listening to the If the page opens a pop-up, you can get a reference to it by listening to the `popup` event on the page.
`popup` event on the page.
This event is emitted in addition to the `browserContext.on('page')` event, but This event is emitted in addition to the `browserContext.on('page')` event, but only for popups relevant to this page.
only for popups relevant to this page.
```js ```js
// Get popup after a specific action (e.g., click) // Get popup after a specific action (e.g., click)
@ -109,8 +97,7 @@ await popup.waitForLoadState();
await popup.title(); await popup.title();
``` ```
If the action that triggers the popup is unknown, the following pattern can be If the action that triggers the popup is unknown, the following pattern can be used.
used.
```js ```js
// Get all popups when they open // Get all popups when they open
@ -121,45 +108,45 @@ page.on('popup', async popup => {
``` ```
#### API reference #### API reference
- [page.on('popup')](./api.md#pageonpopup) - [page.on('popup')](api/class-page.md#pageonpopup)
[Playwright]: api.md#class-playwright "Playwright" [Playwright]: api/class-playwright.md "Playwright"
[Browser]: api.md#class-browser "Browser" [Browser]: api/class-browser.md "Browser"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api.md#class-page "Page" [Page]: api/class-page.md "Page"
[Frame]: api.md#class-frame "Frame" [Frame]: api/class-frame.md "Frame"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api.md#class-dialog "Dialog" [Dialog]: api/class-dialog.md "Dialog"
[Download]: api.md#class-download "Download" [Download]: api/class-download.md "Download"
[Video]: api.md#class-video "Video" [Video]: api/class-video.md "Video"
[FileChooser]: api.md#class-filechooser "FileChooser" [FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api.md#class-keyboard "Keyboard" [Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api.md#class-mouse "Mouse" [Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api.md#class-request "Request" [Request]: api/class-request.md "Request"
[Response]: api.md#class-response "Response" [Response]: api/class-response.md "Response"
[Selectors]: api.md#class-selectors "Selectors" [Selectors]: api/class-selectors.md "Selectors"
[Route]: api.md#class-route "Route" [Route]: api/class-route.md "Route"
[WebSocket]: api.md#class-websocket "WebSocket" [WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api.md#class-accessibility "Accessibility" [Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api.md#class-worker "Worker" [Worker]: api/class-worker.md "Worker"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api.md#class-browsertype "BrowserType" [BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api.md#class-logger "Logger" [Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api.md#class-cdpsession "CDPSession" [CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -1,51 +1,37 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: navigations
title: "Navigations"
---
# Navigations Playwright can navigate to URLs and handle navigations caused by page interactions. This guide covers common scenarios to wait for page navigations and loading to complete.
Playwright can navigate to URLs and handle navigations caused by page
interactions. This guide covers common scenarios to wait for page navigations
and loading to complete.
<!-- GEN:toc-top-level -->
- [Navigation lifecycle](#navigation-lifecycle) - [Navigation lifecycle](#navigation-lifecycle)
- [Scenarios initiated by browser UI](#scenarios-initiated-by-browser-ui) - [Scenarios initiated by browser UI](#scenarios-initiated-by-browser-ui)
- [Scenarios initiated by page interaction](#scenarios-initiated-by-page-interaction) - [Scenarios initiated by page interaction](#scenarios-initiated-by-page-interaction)
- [Advanced patterns](#advanced-patterns) - [Advanced patterns](#advanced-patterns)
<!-- GEN:stop -->
## Navigation lifecycle ## Navigation lifecycle
Playwright splits the process of showing a new document in a page into Playwright splits the process of showing a new document in a page into **navigation** and **loading**.
**navigation** and **loading**.
**Navigations** can be initiated by changing the page URL or by interacting with **Navigations** can be initiated by changing the page URL or by interacting with the page (e.g., clicking a link). Navigation ends when response headers have been parsed and session history is updated. The navigation intent may be canceled, for example, on hitting an unresolved DNS address or transformed into a file download. Only after the navigation succeeds, page starts **loading** the document.
the page (e.g., clicking a link). Navigation ends when response headers have
been parsed and session history is updated. The navigation intent may be
canceled, for example, on hitting an unresolved DNS address or transformed into
a file download. Only after the navigation succeeds, page starts **loading** the
document.
**Loading** covers getting the remaining response body over the network, **Loading** covers getting the remaining response body over the network, parsing, executing the scripts and firing load events:
parsing, executing the scripts and firing load events: - [page.url()](api/class-page.md#pageurl) is set to the new url
- [page.url()](./api.md#pageurl) is set to the new url
- document content is loaded over network and parsed - document content is loaded over network and parsed
- [page.on('domcontentloaded')](./api.md#pageondomcontentloaded) event is - [page.on('domcontentloaded')](api/class-page.md#pageondomcontentloaded) event is fired
fired
- page executes some scripts and loads resources like stylesheets and images - page executes some scripts and loads resources like stylesheets and images
- [page.on('load')](./api.md#pageonload) event is fired - [page.on('load')](api/class-page.md#pageonload) event is fired
- page executes dynamically loaded scripts - page executes dynamically loaded scripts
- `networkidle` is fired when no new network requests are made for 500 ms - `networkidle` is fired when no new network requests are made for 500 ms
## Scenarios initiated by browser UI ## Scenarios initiated by browser UI
Navigations can be initiated by changing the URL bar, reloading the page or Navigations can be initiated by changing the URL bar, reloading the page or going back or forward in session history.
going back or forward in session history.
### Auto-wait ### Auto-wait
Navigating to a URL auto-waits for the page to fire the `load` event. If the Navigating to a URL auto-waits for the page to fire the `load` event. If the page does a client-side redirect before `load`, `page.goto` will auto-wait for the redirected page to fire the `load` event.
page does a client-side redirect before `load`, `page.goto` will auto-wait for
the redirected page to fire the `load` event.
```js ```js
// Navigate the page // Navigate the page
@ -54,8 +40,7 @@ await page.goto('https://example.com');
### Custom wait ### Custom wait
Override the default behavior to wait until a specific event, like Override the default behavior to wait until a specific event, like `networkidle`.
`networkidle`.
```js ```js
// Navigate and wait until network is idle // Navigate and wait until network is idle
@ -64,11 +49,7 @@ await page.goto('https://example.com', { waitUntil: 'networkidle' });
### Wait for element ### Wait for element
In lazy-loaded pages, it can be useful to wait until an element is visible with In lazy-loaded pages, it can be useful to wait until an element is visible with [page.waitForSelector(selector[, options])](api/class-page.md#pagewaitforselectorselector-options). Alternatively, page interactions like [page.click(selector[, options])](api/class-page.md#pageclickselector-options) auto-wait for elements.
[page.waitForSelector(selector[, options])](./api.md#pagewaitforselectorselector-options).
Alternatively, page interactions like
[page.click(selector[, options])](./api.md#pageclickselector-options) auto-wait
for elements.
```js ```js
// Navigate and wait for element // Navigate and wait for element
@ -82,21 +63,18 @@ await page.click('text=Example Domain');
``` ```
#### API reference #### API reference
- [page.goto(url[, options])](./api.md#pagegotourl-options) - [page.goto(url[, options])](api/class-page.md#pagegotourl-options)
- [page.reload([options])](./api.md#pagereloadoptions) - [page.reload([options])](api/class-page.md#pagereloadoptions)
- [page.goBack([options])](./api.md#pagegobackoptions) - [page.goBack([options])](api/class-page.md#pagegobackoptions)
- [page.goForward([options])](./api.md#pagegoforwardoptions) - [page.goForward([options])](api/class-page.md#pagegoforwardoptions)
## Scenarios initiated by page interaction ## Scenarios initiated by page interaction
In the scenarios below, `page.click` initiates a navigation and then waits for In the scenarios below, `page.click` initiates a navigation and then waits for the navigation to complete.
the navigation to complete.
### Auto-wait ### Auto-wait
By default, `page.click` will wait for the navigation step to complete. This can By default, `page.click` will wait for the navigation step to complete. This can be combined with a page interaction on the navigated page which would auto-wait for an element.
be combined with a page interaction on the navigated page which would auto-wait
for an element.
```js ```js
// Click will auto-wait for navigation to complete // Click will auto-wait for navigation to complete
@ -107,9 +85,7 @@ await page.fill('#username', 'John Doe');
### Custom wait ### Custom wait
`page.click` can be combined with `page.click` can be combined with [page.waitForLoadState([state, options])](api/class-page.md#pagewaitforloadstatestate-options) to wait for a loading event.
[page.waitForLoadState([state, options])](./api.md#pagewaitforloadstatestate-options)
to wait for a loading event.
```js ```js
await page.click('button'); // Click triggers navigation await page.click('button'); // Click triggers navigation
@ -118,11 +94,7 @@ await page.waitForLoadState('networkidle'); // This resolves after 'networkidle'
### Wait for element ### Wait for element
In lazy-loaded pages, it can be useful to wait until an element is visible with In lazy-loaded pages, it can be useful to wait until an element is visible with [page.waitForSelector(selector[, options])](api/class-page.md#pagewaitforselectorselector-options). Alternatively, page interactions like [page.click(selector[, options])](api/class-page.md#pageclickselector-options) auto-wait for elements.
[page.waitForSelector(selector[, options])](./api.md#pagewaitforselectorselector-options).
Alternatively, page interactions like
[page.click(selector[, options])](./api.md#pageclickselector-options) auto-wait
for elements.
```js ```js
// Click triggers navigation // Click triggers navigation
@ -138,10 +110,7 @@ await page.fill('#username', 'John Doe');
### Asynchronous navigation ### Asynchronous navigation
Clicking an element could trigger asychronous processing before initiating the Clicking an element could trigger asychronous processing before initiating the navigation. In these cases, it is recommended to explicitly call [page.waitForNavigation([options])](api/class-page.md#pagewaitfornavigationoptions). For example:
navigation. In these cases, it is recommended to explicitly call
[page.waitForNavigation([options])](./api.md#pagewaitfornavigationoptions). For
example:
* Navigation is triggered from a `setTimeout` * Navigation is triggered from a `setTimeout`
* Page waits for network requests before navigation * Page waits for network requests before navigation
@ -152,15 +121,11 @@ await Promise.all([
]); ]);
``` ```
The `Promise.all` pattern prevents a race condition between `page.click` and The `Promise.all` pattern prevents a race condition between `page.click` and `page.waitForNavigation` when navigation happens quickly.
`page.waitForNavigation` when navigation happens quickly.
### Multiple navigations ### Multiple navigations
Clicking an element could trigger multiple navigations. In these cases, it is Clicking an element could trigger multiple navigations. In these cases, it is recommended to explicitly [page.waitForNavigation([options])](api/class-page.md#pagewaitfornavigationoptions) to a specific url. For example:
recommended to explicitly
[page.waitForNavigation([options])](./api.md#pagewaitfornavigationoptions) to a
specific url. For example:
* Client-side redirects issued after the `load` event * Client-side redirects issued after the `load` event
* Multiple pushes to history state * Multiple pushes to history state
@ -171,14 +136,11 @@ await Promise.all([
]); ]);
``` ```
The `Promise.all` pattern prevents a race condition between `page.click` and The `Promise.all` pattern prevents a race condition between `page.click` and `page.waitForNavigation` when navigation happens quickly.
`page.waitForNavigation` when navigation happens quickly.
### Loading a popup ### Loading a popup
When popup is opened, explicitly calling When popup is opened, explicitly calling [page.waitForLoadState([state, options])](api/class-page.md#pagewaitforloadstatestate-options) ensures that popup is loaded to the desired state.
[page.waitForLoadState([state, options])](./api.md#pagewaitforloadstatestate-options)
ensures that popup is loaded to the desired state.
```js ```js
const [ popup ] = await Promise.all([ const [ popup ] = await Promise.all([
@ -189,17 +151,15 @@ await popup.waitForLoadState('load');
``` ```
#### API reference #### API reference
- [page.click(selector[, options])](./api.md#pageclickselector-options) - [page.click(selector[, options])](api/class-page.md#pageclickselector-options)
- [page.waitForLoadState([state, options])](./api.md#pagewaitforloadstatestate-options) - [page.waitForLoadState([state, options])](api/class-page.md#pagewaitforloadstatestate-options)
- [page.waitForSelector(selector[, options])](./api.md#pagewaitforselectorselector-options) - [page.waitForSelector(selector[, options])](api/class-page.md#pagewaitforselectorselector-options)
- [page.waitForNavigation([options])](./api.md#pagewaitfornavigationoptions) - [page.waitForNavigation([options])](api/class-page.md#pagewaitfornavigationoptions)
- [page.waitForFunction(pageFunction[, arg, options])](./api.md#pagewaitforfunctionpagefunction-arg-options) - [page.waitForFunction(pageFunction[, arg, options])](api/class-page.md#pagewaitforfunctionpagefunction-arg-options)
## Advanced patterns ## Advanced patterns
For pages that have complicated loading patterns, For pages that have complicated loading patterns, [page.waitForFunction(pageFunction[, arg, options])](api/class-page.md#pagewaitforfunctionpagefunction-arg-options) is a powerful and extensible approach to define a custom wait criteria.
[page.waitForFunction(pageFunction[, arg, options])](./api.md#pagewaitforfunctionpagefunction-arg-options)
is a powerful and extensible approach to define a custom wait criteria.
```js ```js
await page.goto('http://example.com'); await page.goto('http://example.com');
@ -209,45 +169,45 @@ await page.screenshot();
``` ```
#### API reference #### API reference
- [page.waitForFunction(pageFunction[, arg, options])](./api.md#pagewaitforfunctionpagefunction-arg-options) - [page.waitForFunction(pageFunction[, arg, options])](api/class-page.md#pagewaitforfunctionpagefunction-arg-options)
[Playwright]: api.md#class-playwright "Playwright" [Playwright]: api/class-playwright.md "Playwright"
[Browser]: api.md#class-browser "Browser" [Browser]: api/class-browser.md "Browser"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api.md#class-page "Page" [Page]: api/class-page.md "Page"
[Frame]: api.md#class-frame "Frame" [Frame]: api/class-frame.md "Frame"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api.md#class-dialog "Dialog" [Dialog]: api/class-dialog.md "Dialog"
[Download]: api.md#class-download "Download" [Download]: api/class-download.md "Download"
[Video]: api.md#class-video "Video" [Video]: api/class-video.md "Video"
[FileChooser]: api.md#class-filechooser "FileChooser" [FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api.md#class-keyboard "Keyboard" [Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api.md#class-mouse "Mouse" [Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api.md#class-request "Request" [Request]: api/class-request.md "Request"
[Response]: api.md#class-response "Response" [Response]: api/class-response.md "Response"
[Selectors]: api.md#class-selectors "Selectors" [Selectors]: api/class-selectors.md "Selectors"
[Route]: api.md#class-route "Route" [Route]: api/class-route.md "Route"
[WebSocket]: api.md#class-websocket "WebSocket" [WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api.md#class-accessibility "Accessibility" [Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api.md#class-worker "Worker" [Worker]: api/class-worker.md "Worker"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api.md#class-browsertype "BrowserType" [BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api.md#class-logger "Logger" [Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api.md#class-cdpsession "CDPSession" [CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -1,21 +1,16 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: network
title: "Network"
---
# Network Playwright provides APIs to **monitor** and **modify** network traffic, both HTTP and HTTPS. Any requests that page does, including [XHRs](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) and [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) requests, can be tracked, modified and handled.
Playwright provides APIs to **monitor** and **modify** network traffic, both
HTTP and HTTPS. Any requests that page does, including
[XHRs](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) and
[fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) requests,
can be tracked, modified and handled.
<!-- GEN:toc-top-level -->
- [HTTP Authentication](#http-authentication) - [HTTP Authentication](#http-authentication)
- [Handle file downloads](#handle-file-downloads) - [Handle file downloads](#handle-file-downloads)
- [Network events](#network-events) - [Network events](#network-events)
- [Handle requests](#handle-requests) - [Handle requests](#handle-requests)
- [Modify requests](#modify-requests) - [Modify requests](#modify-requests)
- [Abort requests](#abort-requests) - [Abort requests](#abort-requests)
<!-- GEN:stop -->
<br/> <br/>
@ -33,7 +28,7 @@ await page.goto('https://example.com');
``` ```
#### API reference #### API reference
- [browser.newContext([options])](./api.md#browsernewcontextoptions) - [browser.newContext([options])](api/class-browser.md#browsernewcontextoptions)
<br/> <br/>
@ -47,11 +42,7 @@ const [ download ] = await Promise.all([
const path = await download.path(); const path = await download.path();
``` ```
For every attachment downloaded by the page, For every attachment downloaded by the page, [page.on('download')](api/class-page.md#pageondownload) event is emitted. If you create a browser context with the `acceptDownloads: true`, all these attachments are going to be downloaded into a temporary folder. You can obtain the download url, file system path and payload stream using the [Download] object from the event.
[page.on('download')](./api.md#pageondownload) event is emitted. If you create a
browser context with the `acceptDownloads: true`, all these attachments are
going to be downloaded into a temporary folder. You can obtain the download url,
file system path and payload stream using the [Download] object from the event.
#### Variations #### Variations
@ -61,14 +52,12 @@ If you have no idea what initiates the download, you can still handle the event:
page.on('download', download => download.path().then(console.log)); page.on('download', download => download.path().then(console.log));
``` ```
Note that handling the event forks the control flow and makes script harder to Note that handling the event forks the control flow and makes script harder to follow. Your scenario might end while you are downloading a file since your main control flow is not awaiting for this operation to resolve.
follow. Your scenario might end while you are downloading a file since your main
control flow is not awaiting for this operation to resolve.
#### API reference #### API reference
- [Download] - [Download]
- [page.on('download')](./api.md#pageondownload) - [page.on('download')](api/class-page.md#pageondownload)
- [page.waitForEvent(event[, optionsOrPredicate])](./api.md#pagewaitforeventevent-optionsorpredicate) - [page.waitForEvent(event[, optionsOrPredicate])](api/class-page.md#pagewaitforeventevent-optionsorpredicate)
<br/> <br/>
@ -123,10 +112,10 @@ const [response] = await Promise.all([
#### API reference #### API reference
- [Request] - [Request]
- [Response] - [Response]
- [page.on('request')](./api.md#pageonrequest) - [page.on('request')](api/class-page.md#pageonrequest)
- [page.on('response')](./api.md#pageonresponse) - [page.on('response')](api/class-page.md#pageonresponse)
- [page.waitForRequest(urlOrPredicate[, options])](./api.md#pagewaitforrequesturlorpredicate-options) - [page.waitForRequest(urlOrPredicate[, options])](api/class-page.md#pagewaitforrequesturlorpredicate-options)
- [page.waitForResponse(urlOrPredicate[, options])](./api.md#pagewaitforresponseurlorpredicate-options) - [page.waitForResponse(urlOrPredicate[, options])](api/class-page.md#pagewaitforresponseurlorpredicate-options)
<br/> <br/>
@ -140,8 +129,7 @@ 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 You can mock API endpoints via handling the network quests in your Playwright script.
script.
#### Variations #### Variations
@ -157,10 +145,10 @@ await page.goto('https://example.com');
``` ```
#### API reference #### API reference
- [browserContext.route(url, handler)](./api.md#browsercontextrouteurl-handler) - [browserContext.route(url, handler)](api/class-browsercontext.md#browsercontextrouteurl-handler)
- [browserContext.unroute(url[, handler])](./api.md#browsercontextunrouteurl-handler) - [browserContext.unroute(url[, handler])](api/class-browsercontext.md#browsercontextunrouteurl-handler)
- [page.route(url, handler)](./api.md#pagerouteurl-handler) - [page.route(url, handler)](api/class-page.md#pagerouteurl-handler)
- [page.unroute(url[, handler])](./api.md#pageunrouteurl-handler) - [page.unroute(url[, handler])](api/class-page.md#pageunrouteurl-handler)
- [Route] - [Route]
<br/> <br/>
@ -179,8 +167,7 @@ await page.route('**/*', route => {
await page.route('**/*', route => route.continue({method: 'POST'})); await page.route('**/*', route => route.continue({method: 'POST'}));
``` ```
You can continue requests with modifications. Example above removes an HTTP You can continue requests with modifications. Example above removes an HTTP header from the outgoing requests.
header from the outgoing requests.
## Abort requests ## Abort requests
@ -195,49 +182,49 @@ await page.route('**/*', route => {
``` ```
#### API reference #### API reference
- [page.route(url, handler)](./api.md#pagerouteurl-handler) - [page.route(url, handler)](api/class-page.md#pagerouteurl-handler)
- [browserContext.route(url, handler)](./api.md#browsercontextrouteurl-handler) - [browserContext.route(url, handler)](api/class-browsercontext.md#browsercontextrouteurl-handler)
- [route.abort([errorCode])](./api.md#routeaborterrorcode) - [route.abort([errorCode])](api/class-route.md#routeaborterrorcode)
<br/> <br/>
[Playwright]: api.md#class-playwright "Playwright" [Playwright]: api/class-playwright.md "Playwright"
[Browser]: api.md#class-browser "Browser" [Browser]: api/class-browser.md "Browser"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api.md#class-page "Page" [Page]: api/class-page.md "Page"
[Frame]: api.md#class-frame "Frame" [Frame]: api/class-frame.md "Frame"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api.md#class-dialog "Dialog" [Dialog]: api/class-dialog.md "Dialog"
[Download]: api.md#class-download "Download" [Download]: api/class-download.md "Download"
[Video]: api.md#class-video "Video" [Video]: api/class-video.md "Video"
[FileChooser]: api.md#class-filechooser "FileChooser" [FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api.md#class-keyboard "Keyboard" [Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api.md#class-mouse "Mouse" [Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api.md#class-request "Request" [Request]: api/class-request.md "Request"
[Response]: api.md#class-response "Response" [Response]: api/class-response.md "Response"
[Selectors]: api.md#class-selectors "Selectors" [Selectors]: api/class-selectors.md "Selectors"
[Route]: api.md#class-route "Route" [Route]: api/class-route.md "Route"
[WebSocket]: api.md#class-websocket "WebSocket" [WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api.md#class-accessibility "Accessibility" [Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api.md#class-worker "Worker" [Worker]: api/class-worker.md "Worker"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api.md#class-browsertype "BrowserType" [BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api.md#class-logger "Logger" [Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api.md#class-cdpsession "CDPSession" [CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -1,27 +1,20 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: pom
title: "Page Object Models"
---
# Page Object Models Large test suites can be structured to optimize ease of authoring and maintenance. Page object models are one such approach to structure your test suite.
Large test suites can be structured to optimize ease of authoring and
maintenance. Page object models are one such approach to structure your test
suite.
<!-- GEN:toc-top-level -->
- [Introduction](#introduction) - [Introduction](#introduction)
- [Implementation](#implementation) - [Implementation](#implementation)
<!-- GEN:stop -->
## Introduction ## Introduction
A page object represents a part of your web application. An e-commerce web A page object represents a part of your web application. An e-commerce web application might have a home page, a listings page and a checkout page. Each of them can be represented by page object models.
application might have a home page, a listings page and a checkout page. Each of
them can be represented by page object models.
Page objects **simplify authoring**. They create a higher-level API which suits Page objects **simplify authoring**. They create a higher-level API which suits your application.
your application.
Page objects **simplify maintenance**. They capture element selectors in one Page objects **simplify maintenance**. They capture element selectors in one place and create reusable code to avoid repetition.
place and create reusable code to avoid repetition.
## Implementation ## Implementation
@ -59,44 +52,44 @@ await searchPage.search('search query');
### API reference ### API reference
- [Page] - [Page]
[Playwright]: api.md#class-playwright "Playwright" [Playwright]: api/class-playwright.md "Playwright"
[Browser]: api.md#class-browser "Browser" [Browser]: api/class-browser.md "Browser"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api.md#class-page "Page" [Page]: api/class-page.md "Page"
[Frame]: api.md#class-frame "Frame" [Frame]: api/class-frame.md "Frame"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api.md#class-dialog "Dialog" [Dialog]: api/class-dialog.md "Dialog"
[Download]: api.md#class-download "Download" [Download]: api/class-download.md "Download"
[Video]: api.md#class-video "Video" [Video]: api/class-video.md "Video"
[FileChooser]: api.md#class-filechooser "FileChooser" [FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api.md#class-keyboard "Keyboard" [Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api.md#class-mouse "Mouse" [Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api.md#class-request "Request" [Request]: api/class-request.md "Request"
[Response]: api.md#class-response "Response" [Response]: api/class-response.md "Response"
[Selectors]: api.md#class-selectors "Selectors" [Selectors]: api/class-selectors.md "Selectors"
[Route]: api.md#class-route "Route" [Route]: api/class-route.md "Route"
[WebSocket]: api.md#class-websocket "WebSocket" [WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api.md#class-accessibility "Accessibility" [Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api.md#class-worker "Worker" [Worker]: api/class-worker.md "Worker"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api.md#class-browsertype "BrowserType" [BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api.md#class-logger "Logger" [Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api.md#class-cdpsession "CDPSession" [CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -1,19 +1,92 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: selectors
title: "Element selectors"
---
# Element selectors Selectors query elements on the web page for interactions, like [page.click(selector[, options])](api/class-page.md#pageclickselector-options), and to obtain `ElementHandle` through [page.$(selector)](api/class-page.md#pageselector). Built-in selectors auto-pierce [shadow DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM).
Selectors query elements on the web page for interactions, like - [Working with selectors](#working-with-selectors)
[page.click(selector[, options])](./api.md#pageclickselector-options), and to
obtain `ElementHandle` through [page.$(selector)](./api.md#pageselector).
Built-in selectors auto-pierce
[shadow DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM).
<!-- GEN:toc-top-level -->
- [Syntax](#syntax) - [Syntax](#syntax)
- [Best practices](#best-practices) - [Best practices](#best-practices)
- [Examples](#examples) - [Examples](#examples)
- [Selector engines](#selector-engines) - [Selector engines](#selector-engines)
<!-- GEN:stop -->
## Working with selectors
Selector describes an element in the page. It can be used to obtain `ElementHandle` (see [page.$(selector)](api/class-page.md#pageselector) for example) or shortcut element operations to avoid intermediate handle (see [page.click(selector[, options])](api/class-page.md#pageclickselector-options) for example).
Selector has the following format: `engine=body [>> engine=body]*`. Here `engine` is one of the supported [selector engines](./selectors.md) (e.g. `css` or `xpath`), and `body` is a selector body in the format of the particular engine. When multiple `engine=body` clauses are present (separated by `>>`), next one is queried relative to the previous one's result.
Playwright also supports the following CSS extensions:
* `:text("string")` - Matches elements that contain specific text node. Learn more about [text selector](./selectors.md#css-extension-text).
* `:visible` - Matches only visible elements. Learn more about [visible selector](./selectors.md#css-extension-visible).
* `:light(selector)` - Matches in the light DOM only as opposite to piercing open shadow roots. Learn more about [shadow piercing](./selectors.md#shadow-piercing).
<!--
* `:right-of(selector)`, `:left-of(selector)`, `:above(selector)`, `:below(selector)`, `:near(selector)`, `:within(selector)` - Match elements based on their relative position to another element. Learn more about [proximity selectors](./selectors.md#css-extension-proximity).
-->
For convenience, selectors in the wrong format are heuristically converted to the right format:
- selector starting with `//` or `..` is assumed to be `xpath=selector`;
- selector starting and ending with a quote (either `"` or `'`) is assumed to be `text=selector`;
- otherwise selector is assumed to be `css=selector`.
```js
// queries 'div' css selector
const handle = await page.$('css=div');
// queries '//html/body/div' xpath selector
const handle = await page.$('xpath=//html/body/div');
// queries '"foo"' text selector
const handle = await page.$('text="foo"');
// queries 'span' css selector inside the result of '//html/body/div' xpath selector
const handle = await page.$('xpath=//html/body/div >> css=span');
// converted to 'css=div'
const handle = await page.$('div');
// converted to 'xpath=//html/body/div'
const handle = await page.$('//html/body/div');
// converted to 'text="foo"'
const handle = await page.$('"foo"');
// queries '../span' xpath selector starting with the result of 'div' css selector
const handle = await page.$('div >> ../span');
// queries 'span' css selector inside the div handle
const handle = await divHandle.$('css=span');
```
### Working with Chrome Extensions
Playwright can be used for testing Chrome Extensions.
> **NOTE** Extensions in Chrome / Chromium currently only work in non-headless mode.
The following is code for getting a handle to the [background page](https://developer.chrome.com/extensions/background_pages) of an extension whose source is located in `./my-extension`:
```js
const { chromium } = require('playwright');
(async () => {
const pathToExtension = require('path').join(__dirname, 'my-extension');
const userDataDir = '/tmp/test-user-data-dir';
const browserContext = await chromium.launchPersistentContext(userDataDir,{
headless: false,
args: [
`--disable-extensions-except=${pathToExtension}`,
`--load-extension=${pathToExtension}`
]
});
const backgroundPage = browserContext.backgroundPages()[0];
// Test the background page as you would any other page.
await browserContext.close();
})();
```
## Syntax ## Syntax
@ -23,30 +96,23 @@ Selectors are defined by selector engine name and selector body, `engine=body`.
* Learn more about [custom selector engines](./extensibility.md) * Learn more about [custom selector engines](./extensibility.md)
* `body` refers to the query string for the respective engine * `body` refers to the query string for the respective engine
* For `text`, body is the text content * For `text`, body is the text content
* For `css`, body is a * For `css`, body is a [css selector](https://developer.mozilla.org/en/docs/Web/CSS/CSS_Selectors)
[css selector](https://developer.mozilla.org/en/docs/Web/CSS/CSS_Selectors)
Body format is assumed to ignore leading and trailing white spaces, so that Body format is assumed to ignore leading and trailing white spaces, so that extra whitespace can be added for readability.
extra whitespace can be added for readability.
### Short-forms ### Short-forms
For convenience, common selectors have short-forms: For convenience, common selectors have short-forms:
- Selector starting with `//` or `..` is assumed to be `xpath=selector` - Selector starting with `//` or `..` is assumed to be `xpath=selector`
- Example: `page.click('//html')` is converted to - Example: `page.click('//html')` is converted to `page.click('xpath=//html')`.
`page.click('xpath=//html')`. - Selector starting and ending with a quote (either `"` or `'`) is assumed to be `text=selector`
- Selector starting and ending with a quote (either `"` or `'`) is assumed to - Example: `page.click('"foo"')` is converted to `page.click('text="foo"')`.
be `text=selector`
- Example: `page.click('"foo"')` is converted to
`page.click('text="foo"')`.
- Otherwise, selector is assumed to be `css=selector` - Otherwise, selector is assumed to be `css=selector`
- Example: `page.click('div')` is converted to `page.click('css=div')`. - Example: `page.click('div')` is converted to `page.click('css=div')`.
### Chaining selectors ### Chaining selectors
Selectors defined as `engine=body` or in short-form can be combined with the Selectors defined as `engine=body` or in short-form can be combined with the `>>` token, e.g. `selector1 >> selector2 >> selectors3`. When selectors are chained, next one is queried relative to the previous one's result.
`>>` token, e.g. `selector1 >> selector2 >> selectors3`. When selectors are
chained, next one is queried relative to the previous one's result.
For example, For example,
@ -61,30 +127,21 @@ document
.querySelector('span[attr=value]') .querySelector('span[attr=value]')
``` ```
If a selector needs to include `>>` in the body, it should be escaped inside a If a selector needs to include `>>` in the body, it should be escaped inside a string to not be confused with chaining separator, e.g. `text="some >> text"`.
string to not be confused with chaining separator, e.g. `text="some >> text"`.
### Intermediate matches ### Intermediate matches
By default, chained selectors resolve to an element queried by the last By default, chained selectors resolve to an element queried by the last selector. A selector can be prefixed with `*` to capture elements that are queried by an intermediate selector.
selector. A selector can be prefixed with `*` to capture elements that are
queried by an intermediate selector.
For example, `css=article >> text=Hello` captures the element with the text For example, `css=article >> text=Hello` captures the element with the text `Hello`, and `*css=article >> text=Hello` (note the `*`) captures the `article` element that contains some element with the text `Hello`.
`Hello`, and `*css=article >> text=Hello` (note the `*`) captures the `article`
element that contains some element with the text `Hello`.
## Best practices ## Best practices
The choice of selectors determines the resiliency of automation scripts. To The choice of selectors determines the resiliency of automation scripts. To reduce the maintenance burden, we recommend prioritizing user-facing attributes and explicit contracts.
reduce the maintenance burden, we recommend prioritizing user-facing attributes
and explicit contracts.
### Prioritize user-facing attributes ### Prioritize user-facing attributes
Attributes like text content, input placeholder, accessibility roles and labels Attributes like text content, input placeholder, accessibility roles and labels are user-facing attributes that change rarely. These attributes are not impacted by DOM structure changes.
are user-facing attributes that change rarely. These attributes are not impacted
by DOM structure changes.
The following examples use the built-in [text] and [css] selector engines. The following examples use the built-in [text] and [css] selector engines.
@ -107,9 +164,7 @@ await page.click('css=nav >> text=Login');
### Define explicit contract ### Define explicit contract
When user-facing attributes change frequently, it is recommended to use explicit When user-facing attributes change frequently, it is recommended to use explicit test ids, like `data-test-id`. These `data-*` attributes are supported by the [css] and [id selectors][id].
test ids, like `data-test-id`. These `data-*` attributes are supported by the
[css] and [id selectors][id].
```html ```html
<button data-test-id="directions">Itinéraire</button> <button data-test-id="directions">Itinéraire</button>
@ -126,8 +181,7 @@ await page.click('data-test-id=directions');
### Avoid selectors tied to implementation ### Avoid selectors tied to implementation
[xpath] and [css] can be tied to the DOM structure or implementation. These [xpath] and [css] can be tied to the DOM structure or implementation. These selectors can break when the DOM structure changes.
selectors can break when the DOM structure changes.
```js ```js
// avoid long css or xpath chains // avoid long css or xpath chains
@ -167,32 +221,17 @@ const handle = await divHandle.$('css=span');
### css and css:light ### css and css:light
`css` is a default engine - any malformed selector not starting with `//` nor `css` is a default engine - any malformed selector not starting with `//` nor starting and ending with a quote is assumed to be a css selector. For example, Playwright converts `page.$('span > button')` to `page.$('css=span > button')`.
starting and ending with a quote is assumed to be a css selector. For example,
Playwright converts `page.$('span > button')` to `page.$('css=span > button')`.
Playwright augments standard CSS selectors in two ways, see below for more Playwright augments standard CSS selectors in two ways, see below for more details:
details:
* `css` engine pierces open shadow DOM by default. * `css` engine pierces open shadow DOM by default.
* Playwright adds a few custom pseudo-classes like `:visible`. * Playwright adds a few custom pseudo-classes like `:visible`.
#### Shadow piercing #### Shadow piercing
`css:light` engine is equivalent to `css:light` engine is equivalent to [`Document.querySelector`](https://developer.mozilla.org/en/docs/Web/API/Document/querySelector) and behaves according to the CSS spec. However, it does not pierce shadow roots, which may be inconvenient when working with [Shadow DOM and Web Components](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM). For that reason, `css` engine pierces shadow roots. More specifically, any [Descendant combinator](https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_combinator) or [Child combinator](https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator) pierces an arbitrary number of open shadow roots, including the implicit descendant combinator at the start of the selector.
[`Document.querySelector`](https://developer.mozilla.org/en/docs/Web/API/Document/querySelector)
and behaves according to the CSS spec. However, it does not pierce shadow roots,
which may be inconvenient when working with
[Shadow DOM and Web Components](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM).
For that reason, `css` engine pierces shadow roots. More specifically, any
[Descendant combinator](https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_combinator)
or
[Child combinator](https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator)
pierces an arbitrary number of open shadow roots, including the implicit
descendant combinator at the start of the selector.
`css` engine first searches for elements in the light dom in the iteration `css` engine first searches for elements in the light dom in the iteration order, and then recursively inside open shadow roots in the iteration order. It does not search inside closed shadow roots or iframes.
order, and then recursively inside open shadow roots in the iteration order. It
does not search inside closed shadow roots or iframes.
```html ```html
<article> <article>
@ -212,32 +251,19 @@ does not search inside closed shadow roots or iframes.
</article> </article>
``` ```
Note that `<open mode shadow root>` is not an html element, but rather a shadow Note that `<open mode shadow root>` is not an html element, but rather a shadow root created with `element.attachShadow({mode: 'open'})`.
root created with `element.attachShadow({mode: 'open'})`. - Both `"css=article div"` and `"css:light=article div"` match the first `<div>In the light dom</div>`.
- Both `"css=article div"` and `"css:light=article div"` match the first - Both `"css=article > div"` and `"css:light=article > div"` match two `div` elements that are direct children of the `article`.
`<div>In the light dom</div>`. - `"css=article .in-the-shadow"` matches the `<div class='in-the-shadow'>`, piercing the shadow root, while `"css:light=article .in-the-shadow"` does not match anything.
- Both `"css=article > div"` and `"css:light=article > div"` match two `div` - `"css:light=article div > span"` does not match anything, because both light-dom `div` elements do not contain a `span`.
elements that are direct children of the `article`. - `"css=article div > span"` matches the `<span class='content'>`, piercing the shadow root.
- `"css=article .in-the-shadow"` matches the `<div class='in-the-shadow'>`, - `"css=article > .in-the-shadow"` does not match anything, because `<div class='in-the-shadow'>` is not a direct child of `article`
piercing the shadow root, while `"css:light=article .in-the-shadow"` does
not match anything.
- `"css:light=article div > span"` does not match anything, because both
light-dom `div` elements do not contain a `span`.
- `"css=article div > span"` matches the `<span class='content'>`, piercing
the shadow root.
- `"css=article > .in-the-shadow"` does not match anything, because `<div
class='in-the-shadow'>` is not a direct child of `article`
- `"css:light=article > .in-the-shadow"` does not match anything. - `"css:light=article > .in-the-shadow"` does not match anything.
- `"css=article li#target"` matches the `<li id='target'>Deep in the - `"css=article li#target"` matches the `<li id='target'>Deep in the shadow</li>`, piercing two shadow roots.
shadow</li>`, piercing two shadow roots.
#### CSS extension: visible #### CSS extension: visible
The `:visible` pseudo-class matches elements that are visible as defined in the The `:visible` pseudo-class matches elements that are visible as defined in the [actionability](./actionability.md#visible) guide. For example, `input` matches all the inputs on the page, while `input:visible` matches only visible inputs. This is useful to distinguish elements that are very similar but differ in visibility.
[actionability](./actionability.md#visible) guide. For example, `input` matches
all the inputs on the page, while `input:visible` matches only visible inputs.
This is useful to distinguish elements that are very similar but differ in
visibility.
```js ```js
// Clicks the first button. // Clicks the first button.
@ -247,29 +273,17 @@ await page.click('button:visible');
``` ```
Use `:visible` with caution, because it has two major drawbacks: Use `:visible` with caution, because it has two major drawbacks:
* When elements change their visibility dynamically, `:visible` will give * When elements change their visibility dynamically, `:visible` will give upredictable results based on the timing.
upredictable results based on the timing. * `:visible` forces a layout and may lead to querying being slow, especially when used with `page.waitForSelector(selector[, options])` method.
* `:visible` forces a layout and may lead to querying being slow, especially
when used with `page.waitForSelector(selector[, options])` method.
#### CSS extension: text #### CSS extension: text
The `:text` pseudo-class matches elements that have a text node child with The `:text` pseudo-class matches elements that have a text node child with specific text. It is similar to the [text engine](#text-and-textlight). There are a few variations that support different arguments:
specific text. It is similar to the [text engine](#text-and-textlight). There * `:text("substring")` - Matches when element's text contains "substring" somewhere. Matching is case-insensitive. Matching also normalizes whitespace, for example it turns multiple spaces into one, trusn line breaks into spaces and ignores leading and trailing whitespace.
are a few variations that support different arguments: * `:text-is("string")` - Matches when element's text equals the "string". Matching is case-insensitive and normalizes whitespace.
* `:text("substring")` - Matches when element's text contains "substring"
somewhere. Matching is case-insensitive. Matching also normalizes
whitespace, for example it turns multiple spaces into one, trusn line breaks
into spaces and ignores leading and trailing whitespace.
* `:text-is("string")` - Matches when element's text equals the "string".
Matching is case-insensitive and normalizes whitespace.
* `button:text("Sign in")` - Text selector may be combined with regular CSS. * `button:text("Sign in")` - Text selector may be combined with regular CSS.
* `:text-matches("[+-]?\\d+")` - Matches text against a regular expression. * `:text-matches("[+-]?\\d+")` - Matches text against a regular expression. Note that special characters like back-slash `\`, quotes `"`, square brackets `[]` and more should be escaped. Learn more about [regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp).
Note that special characters like back-slash `\`, quotes `"`, square * `:text-matches("value", "i")` - Matches text against a regular expression with specified flags.
brackets `[]` and more should be escaped. Learn more about
[regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp).
* `:text-matches("value", "i")` - Matches text against a regular expression
with specified flags.
```js ```js
// Click a button with text "Sign in". // Click a button with text "Sign in".
@ -278,9 +292,7 @@ await page.click('button:text("Sign in")');
#### CSS extension: light #### CSS extension: light
`css` engine [pierces shadow](#shadow-piercing) by default. It is possible to `css` engine [pierces shadow](#shadow-piercing) by default. It is possible to disable this behavior by wrapping a selector in `:light` pseudo-class: `:light(section > button.class)` matches in light DOM only.
disable this behavior by wrapping a selector in `:light` pseudo-class:
`:light(section > button.class)` matches in light DOM only.
```js ```js
await page.click(':light(.article > .header)'); await page.click(':light(.article > .header)');
@ -290,27 +302,15 @@ await page.click(':light(.article > .header)');
#### CSS extension: proximity #### CSS extension: proximity
Playwright provides a few proximity selectors based on the page layout. These Playwright provides a few proximity selectors based on the page layout. These can be combined with regular CSS for better results, for example `input:right-of(:text("Password"))` matches an input field that is to the right of text "Password".
can be combined with regular CSS for better results, for example
`input:right-of(:text("Password"))` matches an input field that is to the right
of text "Password".
Note that Playwright uses some heuristics to determine whether one element Note that Playwright uses some heuristics to determine whether one element should be considered to the left/right/above/below/near/within another. Therefore, using proximity selectors may produce unpredictable results. For example, selector could stop matching when element moves by one pixel.
should be considered to the left/right/above/below/near/within another. * `:right-of(css > selector)` - Matches elements that are to the right of any element matching the inner selector.
Therefore, using proximity selectors may produce unpredictable results. For * `:left-of(css > selector)` - Matches elements that are to the left of any element matching the inner selector.
example, selector could stop matching when element moves by one pixel. * `:above(css > selector)` - Matches elements that are above any of the elements matching the inner selector.
* `:right-of(css > selector)` - Matches elements that are to the right of any * `:below(css > selector)` - Matches elements that are below any of the elements matching the inner selector.
element matching the inner selector. * `:near(css > selector)` - Matches elements that are near any of the elements matching the inner selector.
* `:left-of(css > selector)` - Matches elements that are to the left of any * `:within(css > selector)` - Matches elements that are within any of the elements matching the inner selector.
element matching the inner selector.
* `:above(css > selector)` - Matches elements that are above any of the
elements matching the inner selector.
* `:below(css > selector)` - Matches elements that are below any of the
elements matching the inner selector.
* `:near(css > selector)` - Matches elements that are near any of the elements
matching the inner selector.
* `:within(css > selector)` - Matches elements that are within any of the
elements matching the inner selector.
```js ```js
// Fill an input to the right of "Username". // Fill an input to the right of "Username".
@ -324,95 +324,70 @@ await page.click('button:near(.promo-card)');
### xpath ### xpath
XPath engine is equivalent to XPath engine is equivalent to [`Document.evaluate`](https://developer.mozilla.org/en/docs/Web/API/Document/evaluate). Example: `xpath=//html/body`.
[`Document.evaluate`](https://developer.mozilla.org/en/docs/Web/API/Document/evaluate).
Example: `xpath=//html/body`.
Malformed selector starting with `//` or `..` is assumed to be an xpath Malformed selector starting with `//` or `..` is assumed to be an xpath selector. For example, Playwright converts `page.$('//html/body')` to `page.$('xpath=//html/body')`.
selector. For example, Playwright converts `page.$('//html/body')` to
`page.$('xpath=//html/body')`.
Note that `xpath` does not pierce shadow roots. Note that `xpath` does not pierce shadow roots.
### text and text:light ### text and text:light
Text engine finds an element that contains a text node with the passed text. For Text engine finds an element that contains a text node with the passed text. For example, `page.click('text=Login')` clicks on a login button, and `page.waitForSelector('"lazy loaded text")` waits for the `"lazy loaded text"` to appear in the page.
example, `page.click('text=Login')` clicks on a login button, and - By default, the match is case-insensitive, ignores leading/trailing whitespace and searches for a substring. This means `text= Login` matches `<button>Button loGIN (click me)</button>`.
`page.waitForSelector('"lazy loaded text")` waits for the `"lazy loaded text"` - Text body can be escaped with single or double quotes for precise matching, insisting on exact match, including specified whitespace and case. This means `text="Login "` will only match `<button>Login </button>` with exactly one space after "Login". Quoted text follows the usual escaping rules, e.g. use `\"` to escape double quote in a double-quoted string: `text="foo\"bar"`.
to appear in the page. - Text body can also be a JavaScript-like regex wrapped in `/` symbols. This means `text=/^\\s*Login$/i` will match `<button> loGIN</button>` with any number of spaces before "Login" and no spaces after.
- By default, the match is case-insensitive, ignores leading/trailing - Input elements of the type `button` and `submit` are rendered with their value as text, and text engine finds them. For example, `text=Login` matches `<input type=button value="Login">`.
whitespace and searches for a substring. This means `text= Login` matches
`<button>Button loGIN (click me)</button>`.
- Text body can be escaped with single or double quotes for precise matching,
insisting on exact match, including specified whitespace and case. This
means `text="Login "` will only match `<button>Login </button>` with exactly
one space after "Login". Quoted text follows the usual escaping rules, e.g.
use `\"` to escape double quote in a double-quoted string:
`text="foo\"bar"`.
- Text body can also be a JavaScript-like regex wrapped in `/` symbols. This
means `text=/^\\s*Login$/i` will match `<button> loGIN</button>` with any
number of spaces before "Login" and no spaces after.
- Input elements of the type `button` and `submit` are rendered with their
value as text, and text engine finds them. For example, `text=Login` matches
`<input type=button value="Login">`.
Malformed selector starting and ending with a quote (either `"` or `'`) is Malformed selector starting and ending with a quote (either `"` or `'`) is assumed to be a text selector. For example, Playwright converts `page.click('"Login"')` to `page.click('text="Login"')`.
assumed to be a text selector. For example, Playwright converts
`page.click('"Login"')` to `page.click('text="Login"')`.
`text` engine open pierces shadow roots similarly to `css`, while `text:light` `text` engine open pierces shadow roots similarly to `css`, while `text:light` does not. Text engine first searches for elements in the light dom in the iteration order, and then recursively inside open shadow roots in the iteration order. It does not search inside closed shadow roots or iframes.
does not. Text engine first searches for elements in the light dom in the
iteration order, and then recursively inside open shadow roots in the iteration
order. It does not search inside closed shadow roots or iframes.
### id, data-testid, data-test-id, data-test and their :light counterparts ### id, data-testid, data-test-id, data-test and their :light counterparts
Attribute engines are selecting based on the corresponding attribute value. For Attribute engines are selecting based on the corresponding attribute value. For example: `data-test-id=foo` is equivalent to `css=[data-test-id="foo"]`, and `id:light=foo` is equivalent to `css:light=[id="foo"]`.
example: `data-test-id=foo` is equivalent to `css=[data-test-id="foo"]`, and
`id:light=foo` is equivalent to `css:light=[id="foo"]`.
[css]: #css-and-csslight [css]: #css-and-csslight
[text]: #text-and-textlight [text]: #text-and-textlight
[xpath]: #xpath [xpath]: #xpath
[id]: #id-data-testid-data-test-id-data-test-and-their-light-counterparts [id]: #id-data-testid-data-test-id-data-test-and-their-light-counterparts
[Playwright]: api.md#class-playwright "Playwright" [Playwright]: api/class-playwright.md "Playwright"
[Browser]: api.md#class-browser "Browser" [Browser]: api/class-browser.md "Browser"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api.md#class-page "Page" [Page]: api/class-page.md "Page"
[Frame]: api.md#class-frame "Frame" [Frame]: api/class-frame.md "Frame"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api.md#class-dialog "Dialog" [Dialog]: api/class-dialog.md "Dialog"
[Download]: api.md#class-download "Download" [Download]: api/class-download.md "Download"
[Video]: api.md#class-video "Video" [Video]: api/class-video.md "Video"
[FileChooser]: api.md#class-filechooser "FileChooser" [FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api.md#class-keyboard "Keyboard" [Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api.md#class-mouse "Mouse" [Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api.md#class-request "Request" [Request]: api/class-request.md "Request"
[Response]: api.md#class-response "Response" [Response]: api/class-response.md "Response"
[Selectors]: api.md#class-selectors "Selectors" [Selectors]: api/class-selectors.md "Selectors"
[Route]: api.md#class-route "Route" [Route]: api/class-route.md "Route"
[WebSocket]: api.md#class-websocket "WebSocket" [WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api.md#class-accessibility "Accessibility" [Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api.md#class-worker "Worker" [Worker]: api/class-worker.md "Worker"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api.md#class-browsertype "BrowserType" [BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api.md#class-logger "Logger" [Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api.md#class-cdpsession "CDPSession" [CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -1,138 +1,96 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: showcase
# Community Showcase title: "Community Showcase"
---
## Users ## Users
* [VS Code](https://github.com/microsoft/vscode): Playwright is used to run * [VS Code](https://github.com/microsoft/vscode): Playwright is used to run cross-browser tests on their web builds
cross-browser tests on their web builds * [TypeScript](https://github.com/microsoft/TypeScript): Playwright is used test typescript.js across browsers
* [TypeScript](https://github.com/microsoft/TypeScript): Playwright is used * [Elastic APM JS agent](https://github.com/elastic/apm-agent-rum-js): Playwright is used to run benchmark tests across browsers
test typescript.js across browsers * [Blockstack](https://github.com/blockstack/ux): Playwright is used to run cross-browser UI tests
* [Elastic APM JS agent](https://github.com/elastic/apm-agent-rum-js): * [Instakittens React admin](https://github.com/fredericbonnet/instakittens-react-admin): Playwright is used to run end-to-end test scenarios written with Cucumber
Playwright is used to run benchmark tests across browsers * [xterm.js](https://github.com/xtermjs/xterm.js): Playwright is used to run cross-browser integration tests
* [Blockstack](https://github.com/blockstack/ux): Playwright is used to run * [Accessibility Insights for Web](https://github.com/microsoft/accessibility-insights-web): Playwright is used with Jest and axe-core to run end-to-end functional and accessibility tests of a WebExtension-based browser extension
cross-browser UI tests
* [Instakittens React admin](https://github.com/fredericbonnet/instakittens-react-admin):
Playwright is used to run end-to-end test scenarios written with Cucumber
* [xterm.js](https://github.com/xtermjs/xterm.js): Playwright is used to run
cross-browser integration tests
* [Accessibility Insights for Web](https://github.com/microsoft/accessibility-insights-web):
Playwright is used with Jest and axe-core to run end-to-end functional and
accessibility tests of a WebExtension-based browser extension
## Tools ## Tools
* [CodeceptJS](https://github.com/Codeception/CodeceptJS): Write * [CodeceptJS](https://github.com/Codeception/CodeceptJS): Write scenario-driven Playwright tests with synchronous code
scenario-driven Playwright tests with synchronous code * [dom-to-playwright](https://github.com/Xiphe/dom-to-playwright) to copy a JSDOM snapshot into a Playwright page.
* [dom-to-playwright](https://github.com/Xiphe/dom-to-playwright) to copy a * [expected-condition-playwright](https://github.com/elaichenkov/expected-condition-playwright): Supplies a set of common expected conditions that can wait for certain states and conditions
JSDOM snapshot into a Playwright page. * [Headless Testing](https://headlesstesting.com/support/start/playwright.html): Run Playwright tests on browsers in the cloud
* [expected-condition-playwright](https://github.com/elaichenkov/expected-condition-playwright): * [Lumberjack](https://github.com/JakePartusch/lumberjack): Automated accessibility scanner to run checks on your entire website
Supplies a set of common expected conditions that can wait for certain * [mockiavelli](https://github.com/HLTech/mockiavelli) Request mocking library for Playwright to test SPA in isolation from backend APIs.
states and conditions * [Moon](https://github.com/aerokube/moon): Run Playwright tests in parallel in Kubernetes cluster (free up to 4 parallel sessions)
* [Headless Testing](https://headlesstesting.com/support/start/playwright.html): * [playwright-test](https://github.com/hugomrdias/playwright-test) Run unit tests and benchmarks in browsers with Node's seamless experience.
Run Playwright tests on browsers in the cloud * [playwright-video](https://github.com/qawolf/playwright-video): Capture a video while executing a Playwright script
* [Lumberjack](https://github.com/JakePartusch/lumberjack): Automated * [QA Wolf](https://github.com/qawolf/qawolf): Record and create Playwright tests and then run them in CI
accessibility scanner to run checks on your entire website * [Root Cause OSS](https://github.com/testimio/root-cause): Capture screenshots on every step and display in a viewer with logs for easy troubleshooting.
* [mockiavelli](https://github.com/HLTech/mockiavelli) Request mocking library * [test-real-styles](https://github.com/Xiphe/test-real-styles): Utility to test real styling of virtual DOM elements in a browser
for Playwright to test SPA in isolation from backend APIs. * [Testim Playground](https://www.testim.io/playground/): Record Playwright UI tests as code
* [Moon](https://github.com/aerokube/moon): Run Playwright tests in parallel * [Try Playwright](https://try.playwright.tech/): Interactive playground for Playwright to run examples directly from your browser
in Kubernetes cluster (free up to 4 parallel sessions) * [Applitools](https://applitools.com): Add AI-powered visual assertions and run your Playwright tests on all browser, device, and viewport combinations in parallel, without requiring any setup.
* [playwright-test](https://github.com/hugomrdias/playwright-test) Run unit
tests and benchmarks in browsers with Node's seamless experience.
* [playwright-video](https://github.com/qawolf/playwright-video): Capture a
video while executing a Playwright script
* [QA Wolf](https://github.com/qawolf/qawolf): Record and create Playwright
tests and then run them in CI
* [Root Cause OSS](https://github.com/testimio/root-cause): Capture
screenshots on every step and display in a viewer with logs for easy
troubleshooting.
* [test-real-styles](https://github.com/Xiphe/test-real-styles): Utility to
test real styling of virtual DOM elements in a browser
* [Testim Playground](https://www.testim.io/playground/): Record Playwright UI
tests as code
* [Try Playwright](https://try.playwright.tech/): Interactive playground for
Playwright to run examples directly from your browser
* [Applitools](https://applitools.com): Add AI-powered visual assertions and
run your Playwright tests on all browser, device, and viewport combinations
in parallel, without requiring any setup.
## Frameworks ## Frameworks
* [jest-playwright](https://github.com/mmarkelov/jest-playwright): Jest preset * [jest-playwright](https://github.com/mmarkelov/jest-playwright): Jest preset to run Playwright tests with Jest
to run Playwright tests with Jest * [query-selector-shadow-dom](https://github.com/Georgegriff/query-selector-shadow-dom): Custom selector engine to pierce shadow DOM roots
* [query-selector-shadow-dom](https://github.com/Georgegriff/query-selector-shadow-dom): * [Playwright Sharp](https://github.com/kblok/playwright-sharp): Work in progress port of Playwright to .NET
Custom selector engine to pierce shadow DOM roots * [playwright-fluent](https://github.com/hdorgeval/playwright-fluent): Fluent API around Playwright
* [Playwright Sharp](https://github.com/kblok/playwright-sharp): Work in * [robotframework-browser](https://robotframework-browser.org/) Robotframework library that uses Playwright to achieve good development ergonomics.
progress port of Playwright to .NET
* [playwright-fluent](https://github.com/hdorgeval/playwright-fluent): Fluent
API around Playwright
* [robotframework-browser](https://robotframework-browser.org/) Robotframework
library that uses Playwright to achieve good development ergonomics.
## Examples ## Examples
* [e2e Boilerplates](https://github.com/e2e-boilerplate?utf8=%E2%9C%93&q=playwright): * [e2e Boilerplates](https://github.com/e2e-boilerplate?utf8=%E2%9C%93&q=playwright): Project boilerplates for using Playwright with TypeScript, Cucumber, Jest, and other libraries
Project boilerplates for using Playwright with TypeScript, Cucumber, Jest, * [react-app-playwright](https://github.com/KyleADay/react-app-playwright): Using Playwright with a create-react-app project
and other libraries * [playwright-react-typescript-jest-example](https://github.com/azemetre/playwright-react-typescript-jest-example): Using Playwright + Jest with a custom webpack configuration for React + Typescript project
* [react-app-playwright](https://github.com/KyleADay/react-app-playwright): * [playwright-mocha](https://github.com/roggerfe/playwright-mocha): Using Playwright with Mocha and Chai
Using Playwright with a create-react-app project * [playwright-cljs](https://github.com/apeckham/playwright-cljs): Playwright examples in ClojureScript
* [playwright-react-typescript-jest-example](https://github.com/azemetre/playwright-react-typescript-jest-example): * [playwright-azure-functions](https://github.com/arjun27/playwright-azure-functions): Playwright setup on Azure Functions
Using Playwright + Jest with a custom webpack configuration for React + * [playwright-aws-lambda](https://github.com/austinkelleher/playwright-aws-lambda): Playwright setup on AWS Lambda
Typescript project * [playwright-jest-circus-allure](https://github.com/d-shch/playwright-jest-circus-allure): Example how to use allure-report and jest-circus with playwright
* [playwright-mocha](https://github.com/roggerfe/playwright-mocha): Using * [Heroku Playwright Example](https://github.com/mxschmitt/heroku-playwright-example): Example using Playwright on Heroku
Playwright with Mocha and Chai
* [playwright-cljs](https://github.com/apeckham/playwright-cljs): Playwright
examples in ClojureScript
* [playwright-azure-functions](https://github.com/arjun27/playwright-azure-functions):
Playwright setup on Azure Functions
* [playwright-aws-lambda](https://github.com/austinkelleher/playwright-aws-lambda):
Playwright setup on AWS Lambda
* [playwright-jest-circus-allure](https://github.com/d-shch/playwright-jest-circus-allure):
Example how to use allure-report and jest-circus with playwright
* [Heroku Playwright Example](https://github.com/mxschmitt/heroku-playwright-example):
Example using Playwright on Heroku
## Guides ## Guides
* [theheadless.dev](https://theheadless.dev): Practical guides and runnable * [theheadless.dev](https://theheadless.dev): Practical guides and runnable examples on Playwright (and Puppeteer)
examples on Playwright (and Puppeteer)
## Contributing ## Contributing
Did we miss something in this list? Send us a PR! Did we miss something in this list? Send us a PR!
[Playwright]: api.md#class-playwright "Playwright" [Playwright]: api/class-playwright.md "Playwright"
[Browser]: api.md#class-browser "Browser" [Browser]: api/class-browser.md "Browser"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api.md#class-page "Page" [Page]: api/class-page.md "Page"
[Frame]: api.md#class-frame "Frame" [Frame]: api/class-frame.md "Frame"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api.md#class-dialog "Dialog" [Dialog]: api/class-dialog.md "Dialog"
[Download]: api.md#class-download "Download" [Download]: api/class-download.md "Download"
[Video]: api.md#class-video "Video" [Video]: api/class-video.md "Video"
[FileChooser]: api.md#class-filechooser "FileChooser" [FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api.md#class-keyboard "Keyboard" [Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api.md#class-mouse "Mouse" [Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api.md#class-request "Request" [Request]: api/class-request.md "Request"
[Response]: api.md#class-response "Response" [Response]: api/class-response.md "Response"
[Selectors]: api.md#class-selectors "Selectors" [Selectors]: api/class-selectors.md "Selectors"
[Route]: api.md#class-route "Route" [Route]: api/class-route.md "Route"
[WebSocket]: api.md#class-websocket "WebSocket" [WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api.md#class-accessibility "Accessibility" [Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api.md#class-worker "Worker" [Worker]: api/class-worker.md "Worker"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api.md#class-browsertype "BrowserType" [BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api.md#class-logger "Logger" [Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api.md#class-cdpsession "CDPSession" [CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -1,28 +1,18 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: test-runners
title: "Test Runners"
---
# Test Runners With a few lines of code, you can hook up Playwright to your favorite JavaScript test runner.
With a few lines of code, you can hook up Playwright to your favorite JavaScript
test runner.
<!-- GEN:toc -->
- [Jest / Jasmine](#jest--jasmine) - [Jest / Jasmine](#jest--jasmine)
- [AVA](#ava) - [AVA](#ava)
- [Mocha](#mocha) - [Mocha](#mocha)
- [Multiple Browsers](#multiple-browsers) - [Multiple Browsers](#multiple-browsers)
<!-- GEN:stop -->
<br>
<br>
## Jest / Jasmine ## Jest / Jasmine
For Jest, For Jest, [jest-playwright](https://github.com/playwright-community/jest-playwright) can be used. However for a light-weight solution, requiring playwright directly works fine. Jest shares it's syntax with Jasmine, so this applies to Jasmine as well.
[jest-playwright](https://github.com/playwright-community/jest-playwright) can
be used. However for a light-weight solution, requiring playwright directly
works fine. Jest shares it's syntax with Jasmine, so this applies to Jasmine as
well.
```js ```js
const {chromium} = require('playwright'); const {chromium} = require('playwright');
@ -52,8 +42,7 @@ it('should work', async () => {
## AVA ## AVA
Tests run concurrently in AVA, so a single page variable cannot be shared Tests run concurrently in AVA, so a single page variable cannot be shared between tests. Instead, create new pages with a macro function.
between tests. Instead, create new pages with a macro function.
```js ```js
const {chromium} = require('playwright'); const {chromium} = require('playwright');
@ -80,8 +69,7 @@ test('should work', pageMacro, async (t, page) => {
## Mocha ## Mocha
Mocha looks very similar to the Jest/Jasmine setup, and functions in the same Mocha looks very similar to the Jest/Jasmine setup, and functions in the same way.
way.
```js ```js
const {chromium} = require('playwright'); const {chromium} = require('playwright');
@ -111,8 +99,7 @@ it('should work', async () => {
## Multiple Browsers ## Multiple Browsers
These simple examples can be extended to support multiple browsers using an These simple examples can be extended to support multiple browsers using an environment variable.
environment variable.
```js ```js
const {chromium, webkit, firefox} = require('playwright'); const {chromium, webkit, firefox} = require('playwright');
@ -124,44 +111,44 @@ beforeAll(async() => {
``` ```
Then set `BROWSER=firefox` to run your tests with firefox, or any other browser. Then set `BROWSER=firefox` to run your tests with firefox, or any other browser.
[Playwright]: api.md#class-playwright "Playwright" [Playwright]: api/class-playwright.md "Playwright"
[Browser]: api.md#class-browser "Browser" [Browser]: api/class-browser.md "Browser"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api.md#class-page "Page" [Page]: api/class-page.md "Page"
[Frame]: api.md#class-frame "Frame" [Frame]: api/class-frame.md "Frame"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api.md#class-dialog "Dialog" [Dialog]: api/class-dialog.md "Dialog"
[Download]: api.md#class-download "Download" [Download]: api/class-download.md "Download"
[Video]: api.md#class-video "Video" [Video]: api/class-video.md "Video"
[FileChooser]: api.md#class-filechooser "FileChooser" [FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api.md#class-keyboard "Keyboard" [Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api.md#class-mouse "Mouse" [Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api.md#class-request "Request" [Request]: api/class-request.md "Request"
[Response]: api.md#class-response "Response" [Response]: api/class-response.md "Response"
[Selectors]: api.md#class-selectors "Selectors" [Selectors]: api/class-selectors.md "Selectors"
[Route]: api.md#class-route "Route" [Route]: api/class-route.md "Route"
[WebSocket]: api.md#class-websocket "WebSocket" [WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api.md#class-accessibility "Accessibility" [Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api.md#class-worker "Worker" [Worker]: api/class-worker.md "Worker"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api.md#class-browsertype "BrowserType" [BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api.md#class-logger "Logger" [Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api.md#class-cdpsession "CDPSession" [CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -1,36 +1,24 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: troubleshooting
title: "Troubleshooting"
---
# Troubleshooting
<!-- GEN:toc -->
- [Browser dependencies](#browser-dependencies) - [Browser dependencies](#browser-dependencies)
- [Code transpilation issues](#code-transpilation-issues) - [Code transpilation issues](#code-transpilation-issues)
- [Node.js requirements](#nodejs-requirements) - [Node.js requirements](#nodejs-requirements)
* [ReferenceError: URL is not defined](#referenceerror-url-is-not-defined) - [Please file an issue](#please-file-an-issue)
<!-- GEN:stop -->
## Browser dependencies ## Browser dependencies
Playwright does self-inspection every time it runs to make sure the browsers can Playwright does self-inspection every time it runs to make sure the browsers can be launched successfully. If there are missing dependencies, playwright will print instructions to acquire them.
be launched successfully. If there are missing dependencies, playwright will
print instructions to acquire them.
We also provide [Ubuntu 18.04 dockerfile](docker/Dockerfile.bionic) and We also provide [Ubuntu 18.04 dockerfile](docker/Dockerfile.bionic) and [Ubuntu 20.04 dockerfile](docker/Dockerfile.focal) with the list of Debian dependencies.
[Ubuntu 20.04 dockerfile](docker/Dockerfile.focal) with the list of Debian
dependencies.
## Code transpilation issues ## Code transpilation issues
If you are using a JavaScript transpiler like babel or TypeScript, calling If you are using a JavaScript transpiler like babel or TypeScript, calling `evaluate()` with an async function might not work. This is because while `playwright` uses `Function.prototype.toString()` to serialize functions while transpilers could be changing the output code in such a way it's incompatible with `playwright`.
`evaluate()` with an async function might not work. This is because while
`playwright` uses `Function.prototype.toString()` to serialize functions while
transpilers could be changing the output code in such a way it's incompatible
with `playwright`.
Some workarounds to this problem would be to instruct the transpiler not to mess Some workarounds to this problem would be to instruct the transpiler not to mess up with the code, for example, configure TypeScript to use latest ECMAScript version (`"target": "es2018"`). Another workaround could be using string templates instead of functions:
up with the code, for example, configure TypeScript to use latest ECMAScript
version (`"target": "es2018"`). Another workaround could be using string
templates instead of functions:
```js ```js
await page.evaluate(`(async() => { await page.evaluate(`(async() => {
@ -42,51 +30,49 @@ await page.evaluate(`(async() => {
### ReferenceError: URL is not defined ### ReferenceError: URL is not defined
Playwright requires Node.js 10 or higher. Node.js 8 is not supported, and will Playwright requires Node.js 10 or higher. Node.js 8 is not supported, and will cause you to receive this error.
cause you to receive this error.
# Please file an issue # Please file an issue
Playwright is a new project, and we are watching the issues very closely. As we Playwright is a new project, and we are watching the issues very closely. As we solve common issues, this document will grow to include the common answers.
solve common issues, this document will grow to include the common answers. [Playwright]: api/class-playwright.md "Playwright"
[Playwright]: api.md#class-playwright "Playwright" [Browser]: api/class-browser.md "Browser"
[Browser]: api.md#class-browser "Browser" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [Page]: api/class-page.md "Page"
[Page]: api.md#class-page "Page" [Frame]: api/class-frame.md "Frame"
[Frame]: api.md#class-frame "Frame" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [Dialog]: api/class-dialog.md "Dialog"
[Dialog]: api.md#class-dialog "Dialog" [Download]: api/class-download.md "Download"
[Download]: api.md#class-download "Download" [Video]: api/class-video.md "Video"
[Video]: api.md#class-video "Video" [FileChooser]: api/class-filechooser.md "FileChooser"
[FileChooser]: api.md#class-filechooser "FileChooser" [Keyboard]: api/class-keyboard.md "Keyboard"
[Keyboard]: api.md#class-keyboard "Keyboard" [Mouse]: api/class-mouse.md "Mouse"
[Mouse]: api.md#class-mouse "Mouse" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Request]: api/class-request.md "Request"
[Request]: api.md#class-request "Request" [Response]: api/class-response.md "Response"
[Response]: api.md#class-response "Response" [Selectors]: api/class-selectors.md "Selectors"
[Selectors]: api.md#class-selectors "Selectors" [Route]: api/class-route.md "Route"
[Route]: api.md#class-route "Route" [WebSocket]: api/class-websocket.md "WebSocket"
[WebSocket]: api.md#class-websocket "WebSocket" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [Accessibility]: api/class-accessibility.md "Accessibility"
[Accessibility]: api.md#class-accessibility "Accessibility" [Worker]: api/class-worker.md "Worker"
[Worker]: api.md#class-worker "Worker" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserType]: api/class-browsertype.md "BrowserType"
[BrowserType]: api.md#class-browsertype "BrowserType" [Logger]: api/class-logger.md "Logger"
[Logger]: api.md#class-logger "Logger" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [CDPSession]: api/class-cdpsession.md "CDPSession"
[CDPSession]: api.md#class-cdpsession "CDPSession" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -1,22 +1,17 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: verification
title: "Verification"
---
# Verification
<!-- GEN:toc-top-level -->
- [Videos](#videos) - [Videos](#videos)
- [Screenshots](#screenshots) - [Screenshots](#screenshots)
- [Console logs](#console-logs) - [Console logs](#console-logs)
- [Page errors](#page-errors) - [Page errors](#page-errors)
- [Page events](#page-events) - [Page events](#page-events)
<!-- GEN:stop -->
<br/>
## Videos ## Videos
Playwright can record videos for all pages in a Playwright can record videos for all pages in a [browser context](core-concepts.md#browser-contexts). Videos are saved upon context closure, so make sure to await `browserContext.close()`.
[browser context](core-concepts.md#browser-contexts). Videos are saved upon
context closure, so make sure to await `browserContext.close()`.
```js ```js
// With browser.newContext() // With browser.newContext()
@ -40,9 +35,9 @@ const context = await browser.newContext({
#### API reference #### API reference
- [BrowserContext] - [BrowserContext]
- [browser.newContext([options])](./api.md#browsernewcontextoptions) - [browser.newContext([options])](api/class-browser.md#browsernewcontextoptions)
- [browser.newPage([options])](./api.md#browsernewpageoptions) - [browser.newPage([options])](api/class-browser.md#browsernewpageoptions)
- [browserContext.close()](./api.md#browsercontextclose) - [browserContext.close()](api/class-browsercontext.md#browsercontextclose)
## Screenshots ## Screenshots
@ -63,8 +58,8 @@ await elementHandle.screenshot({ path: 'screenshot.png' });
``` ```
#### API reference #### API reference
- [page.screenshot([options])](./api.md#pagescreenshotoptions) - [page.screenshot([options])](api/class-page.md#pagescreenshotoptions)
- [elementHandle.screenshot([options])](./api.md#elementhandlescreenshotoptions) - [elementHandle.screenshot([options])](api/class-elementhandle.md#elementhandlescreenshotoptions)
<br/> <br/>
@ -99,7 +94,7 @@ await msg.args[1].jsonValue() // 42
#### API reference #### API reference
- [ConsoleMessage] - [ConsoleMessage]
- [Page] - [Page]
- [page.on('console')](./api.md#pageonconsole) - [page.on('console')](api/class-page.md#pageonconsole)
<br/> <br/>
@ -119,7 +114,7 @@ await page.goto('data:text/html,<script>throw new Error("Test")</script>');
#### API reference #### API reference
- [Page] - [Page]
- [page.on('pageerror')](./api.md#pageonpageerror) - [page.on('pageerror')](api/class-page.md#pageonpageerror)
<br/> <br/>
@ -152,47 +147,47 @@ const [popup] = await Promise.all([
#### API reference #### API reference
- [Page] - [Page]
- [page.on('requestfailed')](./api.md#pageonrequestfailed) - [page.on('requestfailed')](api/class-page.md#pageonrequestfailed)
- [page.on('dialog')](./api.md#pageondialog) - [page.on('dialog')](api/class-page.md#pageondialog)
- [page.on('popup')](./api.md#pageonpopup) - [page.on('popup')](api/class-page.md#pageonpopup)
[Playwright]: api.md#class-playwright "Playwright" [Playwright]: api/class-playwright.md "Playwright"
[Browser]: api.md#class-browser "Browser" [Browser]: api/class-browser.md "Browser"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [BrowserContext]: api/class-browsercontext.md "BrowserContext"
[Page]: api.md#class-page "Page" [Page]: api/class-page.md "Page"
[Frame]: api.md#class-frame "Frame" [Frame]: api/class-frame.md "Frame"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [ElementHandle]: api/class-elementhandle.md "ElementHandle"
[JSHandle]: api.md#class-jshandle "JSHandle" [JSHandle]: api/class-jshandle.md "JSHandle"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Dialog]: api.md#class-dialog "Dialog" [Dialog]: api/class-dialog.md "Dialog"
[Download]: api.md#class-download "Download" [Download]: api/class-download.md "Download"
[Video]: api.md#class-video "Video" [Video]: api/class-video.md "Video"
[FileChooser]: api.md#class-filechooser "FileChooser" [FileChooser]: api/class-filechooser.md "FileChooser"
[Keyboard]: api.md#class-keyboard "Keyboard" [Keyboard]: api/class-keyboard.md "Keyboard"
[Mouse]: api.md#class-mouse "Mouse" [Mouse]: api/class-mouse.md "Mouse"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[Request]: api.md#class-request "Request" [Request]: api/class-request.md "Request"
[Response]: api.md#class-response "Response" [Response]: api/class-response.md "Response"
[Selectors]: api.md#class-selectors "Selectors" [Selectors]: api/class-selectors.md "Selectors"
[Route]: api.md#class-route "Route" [Route]: api/class-route.md "Route"
[WebSocket]: api.md#class-websocket "WebSocket" [WebSocket]: api/class-websocket.md "WebSocket"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Accessibility]: api.md#class-accessibility "Accessibility" [Accessibility]: api/class-accessibility.md "Accessibility"
[Worker]: api.md#class-worker "Worker" [Worker]: api/class-worker.md "Worker"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[BrowserType]: api.md#class-browsertype "BrowserType" [BrowserType]: api/class-browsertype.md "BrowserType"
[Logger]: api.md#class-logger "Logger" [Logger]: api/class-logger.md "Logger"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[CDPSession]: api.md#class-cdpsession "CDPSession" [CDPSession]: api/class-cdpsession.md "CDPSession"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

View file

@ -1,130 +1,83 @@
<!-- THIS FILE IS NOW GENERATED --> ---
id: why-playwright
title: "Why Playwright?"
---
# Why Playwright? Playwright enables fast, reliable and capable automation across all modern browsers. This guide covers those key differentiators to help you decide on the right tool for your automated tests.
Playwright enables fast, reliable and capable automation across all modern
browsers. This guide covers those key differentiators to help you decide on the
right tool for your automated tests.
<!-- GEN:toc-top-level -->
- [Support for all browsers](#support-for-all-browsers) - [Support for all browsers](#support-for-all-browsers)
- [Fast and reliable execution](#fast-and-reliable-execution) - [Fast and reliable execution](#fast-and-reliable-execution)
- [Powerful automation capabilities](#powerful-automation-capabilities) - [Powerful automation capabilities](#powerful-automation-capabilities)
- [Integrates with your workflow](#integrates-with-your-workflow) - [Integrates with your workflow](#integrates-with-your-workflow)
- [Limitations](#limitations) - [Limitations](#limitations)
<!-- GEN:stop -->
## Support for all browsers ## Support for all browsers
* **Test on Chromium, Firefox and WebKit**. Playwright has full API coverage * **Test on Chromium, Firefox and WebKit**. Playwright has full API coverage for all modern browsers, including Google Chrome and Microsoft Edge (with [Chromium](https://www.chromium.org/)), Apple Safari (with [WebKit](https://webkit.org/)) and Mozilla Firefox.
for all modern browsers, including Google Chrome and Microsoft Edge (with * **Cross-platform WebKit testing**. With Playwright, test how your app behaves in Apple Safari with WebKit builds for Windows, Linux and macOS. Test locally and on CI.
[Chromium](https://www.chromium.org/)), Apple Safari (with * **Test for mobile**. Use [device emulation](./emulation.md) to test your responsive web apps in mobile web browsers.
[WebKit](https://webkit.org/)) and Mozilla Firefox. * **Headless and headful**. Playwright supports headless (without browser UI) and headful (with browser UI) modes for all browsers and all platforms. Headful is great for debugging, and headless is faster and suited for CI/cloud executions.
* **Cross-platform WebKit testing**. With Playwright, test how your app
behaves in Apple Safari with WebKit builds for Windows, Linux and macOS.
Test locally and on CI.
* **Test for mobile**. Use [device emulation](./emulation.md) to test your
responsive web apps in mobile web browsers.
* **Headless and headful**. Playwright supports headless (without browser UI)
and headful (with browser UI) modes for all browsers and all platforms.
Headful is great for debugging, and headless is faster and suited for
CI/cloud executions.
## Fast and reliable execution ## Fast and reliable execution
* **Auto-wait APIs**. Playwright interactions * **Auto-wait APIs**. Playwright interactions [auto-wait for elements](./actionability.md) to be ready. This improves reliability and simplifies test authoring.
[auto-wait for elements](./actionability.md) to be ready. This improves * **Timeout-free automation**. Playwright receives browser signals, like network requests, page navigations and page load events to eliminate the need for sleep timeouts that cause flakiness.
reliability and simplifies test authoring. * **Lean parallelization with browser contexts**. Reuse a single browser instance for multiple parallelized, isolated execution environments with [browser contexts](core-concepts.md).
* **Timeout-free automation**. Playwright receives browser signals, like * **Resilient element selectors**. Playwright can rely on user-facing strings, like text content and accessibility labels to [select elements](./selectors.md). These strings are more resilient than selectors tightly-coupled to the DOM structure.
network requests, page navigations and page load events to eliminate the
need for sleep timeouts that cause flakiness.
* **Lean parallelization with browser contexts**. Reuse a single browser
instance for multiple parallelized, isolated execution environments with
[browser contexts](core-concepts.md).
* **Resilient element selectors**. Playwright can rely on user-facing strings,
like text content and accessibility labels to
[select elements](./selectors.md). These strings are more resilient than
selectors tightly-coupled to the DOM structure.
## Powerful automation capabilities ## Powerful automation capabilities
* **Multiple domains, pages and frames**. Playwright is an out-of-process * **Multiple domains, pages and frames**. Playwright is an out-of-process automation driver that is not limited by the scope of in-page JavaScript execution and can automate scenarios with [multiple pages](multi-pages.md).
automation driver that is not limited by the scope of in-page JavaScript * **Powerful network control**. Playwright introduces context-wide [network interception](./network.md) to stub and mock network requests.
execution and can automate scenarios with [multiple pages](multi-pages.md). * **Modern web features**. Playwright supports web components through [shadow-piercing selectors](./selectors.md), [geolocation, permissions](./emulation.md), web workers and other modern web APIs.
* **Powerful network control**. Playwright introduces context-wide * **Capabilities to cover all scenarios**. Support for [file downloads](./network.md) and [uploads](./input.md), out-of-process iframes, native [input events](./input.md), and even [dark mode](./emulation.md).
[network interception](./network.md) to stub and mock network requests.
* **Modern web features**. Playwright supports web components through
[shadow-piercing selectors](./selectors.md),
[geolocation, permissions](./emulation.md), web workers and other modern web
APIs.
* **Capabilities to cover all scenarios**. Support for
[file downloads](./network.md) and [uploads](./input.md), out-of-process
iframes, native [input events](./input.md), and even
[dark mode](./emulation.md).
## Integrates with your workflow ## Integrates with your workflow
* **One-line installation**. Running `npm i playwright` auto-downloads browser * **One-line installation**. Running `npm i playwright` auto-downloads browser dependencies for your team to be onboarded quickly.
dependencies for your team to be onboarded quickly. * **TypeScript support**. Playwright ships with built-in types for auto-completion and other benefits.
* **TypeScript support**. Playwright ships with built-in types for * **Debugging tools**. Playwright works with the [editor debugger and browser developer tools](./debug.md) to pause execution and inspect the web page.
auto-completion and other benefits. * **Language bindings**. Playwright is also available in [Python](https://github.com/microsoft/playwright-python) and [C#](https://github.com/microsoft/playwright-sharp). Learn about [supported languages](./languages.md).
* **Debugging tools**. Playwright works with the * **Deploy tests to CI**. First-party [Docker image](docker/README.md) and [GitHub Actions](https://github.com/microsoft/playwright-github-action) to deploy tests to [your preferred CI/CD provider](./ci.md).
[editor debugger and browser developer tools](./debug.md) to pause execution
and inspect the web page.
* **Language bindings**. Playwright is also available in
[Python](https://github.com/microsoft/playwright-python) and
[C#](https://github.com/microsoft/playwright-sharp). Learn about
[supported languages](./languages.md).
* **Deploy tests to CI**. First-party [Docker image](docker/README.md) and
[GitHub Actions](https://github.com/microsoft/playwright-github-action) to
deploy tests to [your preferred CI/CD provider](./ci.md).
## Limitations ## Limitations
* **Legacy Edge and IE11 support**. Playwright does not support legacy * **Legacy Edge and IE11 support**. Playwright does not support legacy Microsoft Edge or IE11 ([deprecation notice](https://techcommunity.microsoft.com/t5/microsoft-365-blog/microsoft-365-apps-say-farewell-to-internet-explorer-11-and/ba-p/1591666)). The new Microsoft Edge (on Chromium) is supported.
Microsoft Edge or IE11 * **Java language bindings**: The Playwright API cannot be used in Java or Ruby today. This is a temporary limitation as Playwright is built to support bindings for any language.
([deprecation notice](https://techcommunity.microsoft.com/t5/microsoft-365-blog/microsoft-365-apps-say-farewell-to-internet-explorer-11-and/ba-p/1591666)). * **Test on real mobile devices**: Playwright uses desktop browsers to emulate mobile devices. If you are interested in running on real mobile devices, please [upvote this issue](https://github.com/microsoft/playwright/issues/1122).
The new Microsoft Edge (on Chromium) is supported. [Playwright]: api/class-playwright.md "Playwright"
* **Java language bindings**: The Playwright API cannot be used in Java or [Browser]: api/class-browser.md "Browser"
Ruby today. This is a temporary limitation as Playwright is built to support [BrowserContext]: api/class-browsercontext.md "BrowserContext"
bindings for any language. [Page]: api/class-page.md "Page"
* **Test on real mobile devices**: Playwright uses desktop browsers to emulate [Frame]: api/class-frame.md "Frame"
mobile devices. If you are interested in running on real mobile devices, [ElementHandle]: api/class-elementhandle.md "ElementHandle"
please [JSHandle]: api/class-jshandle.md "JSHandle"
[upvote this issue](https://github.com/microsoft/playwright/issues/1122). [ConsoleMessage]: api/class-consolemessage.md "ConsoleMessage"
[Playwright]: api.md#class-playwright "Playwright" [Dialog]: api/class-dialog.md "Dialog"
[Browser]: api.md#class-browser "Browser" [Download]: api/class-download.md "Download"
[BrowserContext]: api.md#class-browsercontext "BrowserContext" [Video]: api/class-video.md "Video"
[Page]: api.md#class-page "Page" [FileChooser]: api/class-filechooser.md "FileChooser"
[Frame]: api.md#class-frame "Frame" [Keyboard]: api/class-keyboard.md "Keyboard"
[ElementHandle]: api.md#class-elementhandle "ElementHandle" [Mouse]: api/class-mouse.md "Mouse"
[JSHandle]: api.md#class-jshandle "JSHandle" [Touchscreen]: api/class-touchscreen.md "Touchscreen"
[ConsoleMessage]: api.md#class-consolemessage "ConsoleMessage" [Request]: api/class-request.md "Request"
[Dialog]: api.md#class-dialog "Dialog" [Response]: api/class-response.md "Response"
[Download]: api.md#class-download "Download" [Selectors]: api/class-selectors.md "Selectors"
[Video]: api.md#class-video "Video" [Route]: api/class-route.md "Route"
[FileChooser]: api.md#class-filechooser "FileChooser" [WebSocket]: api/class-websocket.md "WebSocket"
[Keyboard]: api.md#class-keyboard "Keyboard" [TimeoutError]: api/class-timeouterror.md "TimeoutError"
[Mouse]: api.md#class-mouse "Mouse" [Accessibility]: api/class-accessibility.md "Accessibility"
[Touchscreen]: api.md#class-touchscreen "Touchscreen" [Worker]: api/class-worker.md "Worker"
[Request]: api.md#class-request "Request" [BrowserServer]: api/class-browserserver.md "BrowserServer"
[Response]: api.md#class-response "Response" [BrowserType]: api/class-browsertype.md "BrowserType"
[Selectors]: api.md#class-selectors "Selectors" [Logger]: api/class-logger.md "Logger"
[Route]: api.md#class-route "Route" [ChromiumBrowser]: api/class-chromiumbrowser.md "ChromiumBrowser"
[WebSocket]: api.md#class-websocket "WebSocket" [ChromiumBrowserContext]: api/class-chromiumbrowsercontext.md "ChromiumBrowserContext"
[TimeoutError]: api.md#class-timeouterror "TimeoutError" [ChromiumCoverage]: api/class-chromiumcoverage.md "ChromiumCoverage"
[Accessibility]: api.md#class-accessibility "Accessibility" [CDPSession]: api/class-cdpsession.md "CDPSession"
[Worker]: api.md#class-worker "Worker" [FirefoxBrowser]: api/class-firefoxbrowser.md "FirefoxBrowser"
[BrowserServer]: api.md#class-browserserver "BrowserServer" [WebKitBrowser]: api/class-webkitbrowser.md "WebKitBrowser"
[BrowserType]: api.md#class-browsertype "BrowserType"
[Logger]: api.md#class-logger "Logger"
[ChromiumBrowser]: api.md#class-chromiumbrowser "ChromiumBrowser"
[ChromiumBrowserContext]: api.md#class-chromiumbrowsercontext "ChromiumBrowserContext"
[ChromiumCoverage]: api.md#class-chromiumcoverage "ChromiumCoverage"
[CDPSession]: api.md#class-cdpsession "CDPSession"
[FirefoxBrowser]: api.md#class-firefoxbrowser "FirefoxBrowser"
[WebKitBrowser]: api.md#class-webkitbrowser "WebKitBrowser"
[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array" [Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"
[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer" [Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"
[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess" [ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"
[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element" [Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"
[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error" [Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"
[EvaluationArgument]: #evaluationargument "Evaluation Argument" [Evaluation Argument]: ./core-concepts.md#evaluationargument "Evaluation Argument"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map" [Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object" [Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise" [Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"

131
types/types.d.ts vendored
View file

@ -151,7 +151,7 @@ export interface Page {
* *
* Shortcut for main frame's * Shortcut for main frame's
* [frame.$(selector)](https://github.com/microsoft/playwright/blob/master/docs/api.md#frameselector). * [frame.$(selector)](https://github.com/microsoft/playwright/blob/master/docs/api.md#frameselector).
* @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
*/ */
$<K extends keyof HTMLElementTagNameMap>(selector: K): Promise<ElementHandleForTag<K> | null>; $<K extends keyof HTMLElementTagNameMap>(selector: K): Promise<ElementHandleForTag<K> | null>;
$(selector: string): Promise<ElementHandle<SVGElement | HTMLElement> | null>; $(selector: string): Promise<ElementHandle<SVGElement | HTMLElement> | null>;
@ -162,7 +162,7 @@ export interface Page {
* *
* Shortcut for main frame's * Shortcut for main frame's
* [frame.$$(selector)](https://github.com/microsoft/playwright/blob/master/docs/api.md#frameselector). * [frame.$$(selector)](https://github.com/microsoft/playwright/blob/master/docs/api.md#frameselector).
* @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
*/ */
$$<K extends keyof HTMLElementTagNameMap>(selector: K): Promise<ElementHandleForTag<K>[]>; $$<K extends keyof HTMLElementTagNameMap>(selector: K): Promise<ElementHandleForTag<K>[]>;
$$(selector: string): Promise<ElementHandle<SVGElement | HTMLElement>[]>; $$(selector: string): Promise<ElementHandle<SVGElement | HTMLElement>[]>;
@ -185,7 +185,7 @@ export interface Page {
* *
* Shortcut for main frame's * Shortcut for main frame's
* [frame.$eval(selector, pageFunction[, arg])](https://github.com/microsoft/playwright/blob/master/docs/api.md#frameevalselector-pagefunction-arg). * [frame.$eval(selector, pageFunction[, arg])](https://github.com/microsoft/playwright/blob/master/docs/api.md#frameevalselector-pagefunction-arg).
* @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param pageFunction Function to be evaluated in browser context * @param pageFunction Function to be evaluated in browser context
* @param arg Optional argument to pass to `pageFunction` * @param arg Optional argument to pass to `pageFunction`
*/ */
@ -208,7 +208,7 @@ export interface Page {
* const divsCounts = await page.$$eval('div', (divs, min) => divs.length >= min, 10); * const divsCounts = await page.$$eval('div', (divs, min) => divs.length >= min, 10);
* ``` * ```
* *
* @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param pageFunction Function to be evaluated in browser context * @param pageFunction Function to be evaluated in browser context
* @param arg Optional argument to pass to `pageFunction` * @param arg Optional argument to pass to `pageFunction`
*/ */
@ -278,7 +278,7 @@ export interface Page {
* })(); * })();
* ``` * ```
* *
* @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
waitForSelector<K extends keyof HTMLElementTagNameMap>(selector: K, options?: PageWaitForSelectorOptionsNotHidden): Promise<ElementHandleForTag<K>>; waitForSelector<K extends keyof HTMLElementTagNameMap>(selector: K, options?: PageWaitForSelectorOptionsNotHidden): Promise<ElementHandleForTag<K>>;
@ -1393,7 +1393,7 @@ export interface Page {
* *
* Shortcut for main frame's * Shortcut for main frame's
* [frame.check(selector[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#framecheckselector-options). * [frame.check(selector[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#framecheckselector-options).
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
check(selector: string, options?: { check(selector: string, options?: {
@ -1435,7 +1435,7 @@ export interface Page {
* *
* Shortcut for main frame's * Shortcut for main frame's
* [frame.click(selector[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#frameclickselector-options). * [frame.click(selector[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#frameclickselector-options).
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
click(selector: string, options?: { click(selector: string, options?: {
@ -1546,7 +1546,7 @@ export interface Page {
* *
* Shortcut for main frame's * Shortcut for main frame's
* [frame.dblclick(selector[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#framedblclickselector-options). * [frame.dblclick(selector[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#framedblclickselector-options).
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
dblclick(selector: string, options?: { dblclick(selector: string, options?: {
@ -1628,7 +1628,7 @@ export interface Page {
* await page.dispatchEvent('#source', 'dragstart', { dataTransfer }); * await page.dispatchEvent('#source', 'dragstart', { dataTransfer });
* ``` * ```
* *
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param type DOM event type: `"click"`, `"dragstart"`, etc. * @param type DOM event type: `"click"`, `"dragstart"`, etc.
* @param eventInit Optional event-specific initialization properties. * @param eventInit Optional event-specific initialization properties.
* @param options * @param options
@ -1773,7 +1773,7 @@ export interface Page {
* *
* Shortcut for main frame's * Shortcut for main frame's
* [frame.fill(selector, value[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#framefillselector-value-options) * [frame.fill(selector, value[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#framefillselector-value-options)
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param value Value to fill for the `<input>`, `<textarea>` or `[contenteditable]` element. * @param value Value to fill for the `<input>`, `<textarea>` or `[contenteditable]` element.
* @param options * @param options
*/ */
@ -1802,7 +1802,7 @@ export interface Page {
* *
* Shortcut for main frame's * Shortcut for main frame's
* [frame.focus(selector[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#framefocusselector-options). * [frame.focus(selector[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#framefocusselector-options).
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
focus(selector: string, options?: { focus(selector: string, options?: {
@ -1849,7 +1849,7 @@ export interface Page {
/** /**
* Returns element attribute value. * Returns element attribute value.
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param name Attribute name to get the value for. * @param name Attribute name to get the value for.
* @param options * @param options
*/ */
@ -1991,7 +1991,7 @@ export interface Page {
* *
* Shortcut for main frame's * Shortcut for main frame's
* [frame.hover(selector[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#framehoverselector-options). * [frame.hover(selector[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#framehoverselector-options).
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
hover(selector: string, options?: { hover(selector: string, options?: {
@ -2029,7 +2029,7 @@ export interface Page {
/** /**
* Returns `element.innerHTML`. * Returns `element.innerHTML`.
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
innerHTML(selector: string, options?: { innerHTML(selector: string, options?: {
@ -2046,7 +2046,7 @@ export interface Page {
/** /**
* Returns `element.innerText`. * Returns `element.innerText`.
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
innerText(selector: string, options?: { innerText(selector: string, options?: {
@ -2259,7 +2259,7 @@ export interface Page {
* await browser.close(); * await browser.close();
* ``` * ```
* *
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`. * @param key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
* @param options * @param options
*/ */
@ -2442,7 +2442,7 @@ export interface Page {
* *
* Shortcut for main frame's * Shortcut for main frame's
* [frame.selectOption(selector, values[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#frameselectoptionselector-values-options) * [frame.selectOption(selector, values[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#frameselectoptionselector-values-options)
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param values Options to select. If the `<select>` has the `multiple` attribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are equivalent to `{value:'string'}`. Option * @param values Options to select. If the `<select>` has the `multiple` attribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are equivalent to `{value:'string'}`. Option
* is considered matching if all specified properties match. * is considered matching if all specified properties match.
* @param options * @param options
@ -2567,7 +2567,7 @@ export interface Page {
* *
* Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then they * Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then they
* are resolved relative to the the current working directory. For empty array, clears the selected files. * are resolved relative to the the current working directory. For empty array, clears the selected files.
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param files * @param files
* @param options * @param options
*/ */
@ -2668,7 +2668,7 @@ export interface Page {
* *
* Shortcut for main frame's * Shortcut for main frame's
* [frame.tap(selector[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#frametapselector-options). * [frame.tap(selector[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#frametapselector-options).
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
tap(selector: string, options?: { tap(selector: string, options?: {
@ -2713,7 +2713,7 @@ export interface Page {
/** /**
* Returns `element.textContent`. * Returns `element.textContent`.
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
textContent(selector: string, options?: { textContent(selector: string, options?: {
@ -2751,7 +2751,7 @@ export interface Page {
* *
* Shortcut for main frame's * Shortcut for main frame's
* [frame.type(selector, text[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#frametypeselector-text-options). * [frame.type(selector, text[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#frametypeselector-text-options).
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param text A text to type into a focused element. * @param text A text to type into a focused element.
* @param options * @param options
*/ */
@ -2797,7 +2797,7 @@ export interface Page {
* *
* Shortcut for main frame's * Shortcut for main frame's
* [frame.uncheck(selector[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#frameuncheckselector-options). * [frame.uncheck(selector[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#frameuncheckselector-options).
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
uncheck(selector: string, options?: { uncheck(selector: string, options?: {
@ -3328,8 +3328,9 @@ export interface Frame {
* Returns the ElementHandle pointing to the frame element. * Returns the ElementHandle pointing to the frame element.
* *
* The method finds an element matching the specified selector within the frame. See * The method finds an element matching the specified selector within the frame. See
* [Working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. If no elements match the selector, returns `null`. * [Working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details. If no elements match the selector,
* @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * returns `null`.
* @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
*/ */
$<K extends keyof HTMLElementTagNameMap>(selector: K): Promise<ElementHandleForTag<K> | null>; $<K extends keyof HTMLElementTagNameMap>(selector: K): Promise<ElementHandleForTag<K> | null>;
$(selector: string): Promise<ElementHandle<SVGElement | HTMLElement> | null>; $(selector: string): Promise<ElementHandle<SVGElement | HTMLElement> | null>;
@ -3338,9 +3339,9 @@ export interface Frame {
* Returns the ElementHandles pointing to the frame elements. * Returns the ElementHandles pointing to the frame elements.
* *
* The method finds all elements matching the specified selector within the frame. See * The method finds all elements matching the specified selector within the frame. See
* [Working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. If no elements match the selector, returns empty * [Working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details. If no elements match the selector,
* array. * returns empty array.
* @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
*/ */
$$<K extends keyof HTMLElementTagNameMap>(selector: K): Promise<ElementHandleForTag<K>[]>; $$<K extends keyof HTMLElementTagNameMap>(selector: K): Promise<ElementHandleForTag<K>[]>;
$$(selector: string): Promise<ElementHandle<SVGElement | HTMLElement>[]>; $$(selector: string): Promise<ElementHandle<SVGElement | HTMLElement>[]>;
@ -3349,8 +3350,8 @@ export interface Frame {
* Returns the return value of `pageFunction` * Returns the return value of `pageFunction`
* *
* The method finds an element matching the specified selector within the frame and passes it as a first argument to * The method finds an element matching the specified selector within the frame and passes it as a first argument to
* `pageFunction`. See [Working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. If no elements match the * `pageFunction`. See [Working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details. If no elements
* selector, the method throws an error. * match the selector, the method throws an error.
* *
* If `pageFunction` returns a [Promise], then `frame.$eval` would wait for the promise to resolve and return its value. * If `pageFunction` returns a [Promise], then `frame.$eval` would wait for the promise to resolve and return its value.
* *
@ -3362,7 +3363,7 @@ export interface Frame {
* const html = await frame.$eval('.main-container', (e, suffix) => e.outerHTML + suffix, 'hello'); * const html = await frame.$eval('.main-container', (e, suffix) => e.outerHTML + suffix, 'hello');
* ``` * ```
* *
* @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param pageFunction Function to be evaluated in browser context * @param pageFunction Function to be evaluated in browser context
* @param arg Optional argument to pass to `pageFunction` * @param arg Optional argument to pass to `pageFunction`
*/ */
@ -3375,7 +3376,8 @@ export interface Frame {
* Returns the return value of `pageFunction` * Returns the return value of `pageFunction`
* *
* The method finds all elements matching the specified selector within the frame and passes an array of matched elements * The method finds all elements matching the specified selector within the frame and passes an array of matched elements
* as a first argument to `pageFunction`. See [Working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * as a first argument to `pageFunction`. See [Working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more
* details.
* *
* If `pageFunction` returns a [Promise], then `frame.$$eval` would wait for the promise to resolve and return its value. * If `pageFunction` returns a [Promise], then `frame.$$eval` would wait for the promise to resolve and return its value.
* *
@ -3385,7 +3387,7 @@ export interface Frame {
* const divsCounts = await frame.$$eval('div', (divs, min) => divs.length >= min, 10); * const divsCounts = await frame.$$eval('div', (divs, min) => divs.length >= min, 10);
* ``` * ```
* *
* @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param pageFunction Function to be evaluated in browser context * @param pageFunction Function to be evaluated in browser context
* @param arg Optional argument to pass to `pageFunction` * @param arg Optional argument to pass to `pageFunction`
*/ */
@ -3453,7 +3455,7 @@ export interface Frame {
* })(); * })();
* ``` * ```
* *
* @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
waitForSelector<K extends keyof HTMLElementTagNameMap>(selector: K, options?: PageWaitForSelectorOptionsNotHidden): Promise<ElementHandleForTag<K>>; waitForSelector<K extends keyof HTMLElementTagNameMap>(selector: K, options?: PageWaitForSelectorOptionsNotHidden): Promise<ElementHandleForTag<K>>;
@ -3530,7 +3532,7 @@ export interface Frame {
* *
* When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. * When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
* Passing zero timeout disables this. * Passing zero timeout disables this.
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
check(selector: string, options?: { check(selector: string, options?: {
@ -3571,7 +3573,7 @@ export interface Frame {
* *
* When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. * When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
* Passing zero timeout disables this. * Passing zero timeout disables this.
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
click(selector: string, options?: { click(selector: string, options?: {
@ -3649,7 +3651,7 @@ export interface Frame {
* Passing zero timeout disables this. * Passing zero timeout disables this.
* *
* > **NOTE** `frame.dblclick()` dispatches two `click` events and a single `dblclick` event. * > **NOTE** `frame.dblclick()` dispatches two `click` events and a single `dblclick` event.
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
dblclick(selector: string, options?: { dblclick(selector: string, options?: {
@ -3731,7 +3733,7 @@ export interface Frame {
* await frame.dispatchEvent('#source', 'dragstart', { dataTransfer }); * await frame.dispatchEvent('#source', 'dragstart', { dataTransfer });
* ``` * ```
* *
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param type DOM event type: `"click"`, `"dragstart"`, etc. * @param type DOM event type: `"click"`, `"dragstart"`, etc.
* @param eventInit Optional event-specific initialization properties. * @param eventInit Optional event-specific initialization properties.
* @param options * @param options
@ -3756,7 +3758,7 @@ export interface Frame {
* *
* To send fine-grained keyboard events, use * To send fine-grained keyboard events, use
* [frame.type(selector, text[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#frametypeselector-text-options). * [frame.type(selector, text[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#frametypeselector-text-options).
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param value Value to fill for the `<input>`, `<textarea>` or `[contenteditable]` element. * @param value Value to fill for the `<input>`, `<textarea>` or `[contenteditable]` element.
* @param options * @param options
*/ */
@ -3782,7 +3784,7 @@ export interface Frame {
/** /**
* This method fetches an element with `selector` and focuses it. If there's no element matching `selector`, the method * This method fetches an element with `selector` and focuses it. If there's no element matching `selector`, the method
* waits until a matching element appears in the DOM. * waits until a matching element appears in the DOM.
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
focus(selector: string, options?: { focus(selector: string, options?: {
@ -3817,7 +3819,7 @@ export interface Frame {
/** /**
* Returns element attribute value. * Returns element attribute value.
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param name Attribute name to get the value for. * @param name Attribute name to get the value for.
* @param options * @param options
*/ */
@ -3895,7 +3897,7 @@ export interface Frame {
* *
* When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. * When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
* Passing zero timeout disables this. * Passing zero timeout disables this.
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
hover(selector: string, options?: { hover(selector: string, options?: {
@ -3933,7 +3935,7 @@ export interface Frame {
/** /**
* Returns `element.innerHTML`. * Returns `element.innerHTML`.
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
innerHTML(selector: string, options?: { innerHTML(selector: string, options?: {
@ -3950,7 +3952,7 @@ export interface Frame {
/** /**
* Returns `element.innerText`. * Returns `element.innerText`.
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
innerText(selector: string, options?: { innerText(selector: string, options?: {
@ -4007,7 +4009,7 @@ export interface Frame {
* *
* Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When speficied with the * Shortcuts such as `key: "Control+o"` or `key: "Control+Shift+T"` are supported as well. When speficied with the
* modifier, modifier is pressed and being held while the subsequent key is being pressed. * modifier, modifier is pressed and being held while the subsequent key is being pressed.
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`. * @param key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
* @param options * @param options
*/ */
@ -4052,7 +4054,7 @@ export interface Frame {
* frame.selectOption('select#colors', 'red', 'green', 'blue'); * frame.selectOption('select#colors', 'red', 'green', 'blue');
* ``` * ```
* *
* @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param values Options to select. If the `<select>` has the `multiple` attribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are equivalent to `{value:'string'}`. Option * @param values Options to select. If the `<select>` has the `multiple` attribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are equivalent to `{value:'string'}`. Option
* is considered matching if all specified properties match. * is considered matching if all specified properties match.
* @param options * @param options
@ -4138,7 +4140,7 @@ export interface Frame {
* *
* Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then they * Sets the value of the file input to these file paths or files. If some of the `filePaths` are relative paths, then they
* are resolved relative to the the current working directory. For empty array, clears the selected files. * are resolved relative to the the current working directory. For empty array, clears the selected files.
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param files * @param files
* @param options * @param options
*/ */
@ -4205,7 +4207,7 @@ export interface Frame {
* Passing zero timeout disables this. * Passing zero timeout disables this.
* *
* > **NOTE** `frame.tap()` requires that the `hasTouch` option of the browser context be set to true. * > **NOTE** `frame.tap()` requires that the `hasTouch` option of the browser context be set to true.
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
tap(selector: string, options?: { tap(selector: string, options?: {
@ -4250,7 +4252,7 @@ export interface Frame {
/** /**
* Returns `element.textContent`. * Returns `element.textContent`.
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
textContent(selector: string, options?: { textContent(selector: string, options?: {
@ -4283,7 +4285,7 @@ export interface Frame {
* await frame.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user * await frame.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user
* ``` * ```
* *
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param text A text to type into a focused element. * @param text A text to type into a focused element.
* @param options * @param options
*/ */
@ -4326,7 +4328,7 @@ export interface Frame {
* *
* When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError]. * When all steps combined have not finished during the specified `timeout`, this method rejects with a [TimeoutError].
* Passing zero timeout disables this. * Passing zero timeout disables this.
* @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
uncheck(selector: string, options?: { uncheck(selector: string, options?: {
@ -5331,17 +5333,18 @@ export interface JSHandle<T = any> {
export interface ElementHandle<T=Node> extends JSHandle<T> { export interface ElementHandle<T=Node> extends JSHandle<T> {
/** /**
* The method finds an element matching the specified selector in the `ElementHandle`'s subtree. See * The method finds an element matching the specified selector in the `ElementHandle`'s subtree. See
* [Working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. If no elements match the selector, returns `null`. * [Working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details. If no elements match the selector,
* @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * returns `null`.
* @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
*/ */
$<K extends keyof HTMLElementTagNameMap>(selector: K): Promise<ElementHandleForTag<K> | null>; $<K extends keyof HTMLElementTagNameMap>(selector: K): Promise<ElementHandleForTag<K> | null>;
$(selector: string): Promise<ElementHandle<SVGElement | HTMLElement> | null>; $(selector: string): Promise<ElementHandle<SVGElement | HTMLElement> | null>;
/** /**
* The method finds all elements matching the specified selector in the `ElementHandle`s subtree. See * The method finds all elements matching the specified selector in the `ElementHandle`s subtree. See
* [Working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. If no elements match the selector, returns empty * [Working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details. If no elements match the selector,
* array. * returns empty array.
* @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
*/ */
$$<K extends keyof HTMLElementTagNameMap>(selector: K): Promise<ElementHandleForTag<K>[]>; $$<K extends keyof HTMLElementTagNameMap>(selector: K): Promise<ElementHandleForTag<K>[]>;
$$(selector: string): Promise<ElementHandle<SVGElement | HTMLElement>[]>; $$(selector: string): Promise<ElementHandle<SVGElement | HTMLElement>[]>;
@ -5350,8 +5353,8 @@ export interface ElementHandle<T=Node> extends JSHandle<T> {
* Returns the return value of `pageFunction` * Returns the return value of `pageFunction`
* *
* The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a first * The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a first
* argument to `pageFunction`. See [Working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. If no elements match * argument to `pageFunction`. See [Working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details. If no
* the selector, the method throws an error. * elements match the selector, the method throws an error.
* *
* If `pageFunction` returns a [Promise], then `frame.$eval` would wait for the promise to resolve and return its value. * If `pageFunction` returns a [Promise], then `frame.$eval` would wait for the promise to resolve and return its value.
* *
@ -5363,7 +5366,7 @@ export interface ElementHandle<T=Node> extends JSHandle<T> {
* expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10'); * expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');
* ``` * ```
* *
* @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param pageFunction Function to be evaluated in browser context * @param pageFunction Function to be evaluated in browser context
* @param arg Optional argument to pass to `pageFunction` * @param arg Optional argument to pass to `pageFunction`
*/ */
@ -5376,8 +5379,8 @@ export interface ElementHandle<T=Node> extends JSHandle<T> {
* Returns the return value of `pageFunction` * Returns the return value of `pageFunction`
* *
* The method finds all elements matching the specified selector in the `ElementHandle`'s subtree and passes an array of * The method finds all elements matching the specified selector in the `ElementHandle`'s subtree and passes an array of
* matched elements as a first argument to `pageFunction`. See [Working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more * matched elements as a first argument to `pageFunction`. See
* details. * [Working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* *
* If `pageFunction` returns a [Promise], then `frame.$$eval` would wait for the promise to resolve and return its value. * If `pageFunction` returns a [Promise], then `frame.$$eval` would wait for the promise to resolve and return its value.
* *
@ -5395,7 +5398,7 @@ export interface ElementHandle<T=Node> extends JSHandle<T> {
* expect(await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText))).toEqual(['Hello!', 'Hi!']); * expect(await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText))).toEqual(['Hello!', 'Hi!']);
* ``` * ```
* *
* @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param pageFunction Function to be evaluated in browser context * @param pageFunction Function to be evaluated in browser context
* @param arg Optional argument to pass to `pageFunction` * @param arg Optional argument to pass to `pageFunction`
*/ */
@ -5422,7 +5425,7 @@ export interface ElementHandle<T=Node> extends JSHandle<T> {
* > **NOTE** This method does not work across navigations, use * > **NOTE** This method does not work across navigations, use
* [page.waitForSelector(selector[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#pagewaitforselectorselector-options) * [page.waitForSelector(selector[, options])](https://github.com/microsoft/playwright/blob/master/docs/api.md#pagewaitforselectorselector-options)
* instead. * instead.
* @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more details. * @param selector A selector to query for. See [working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more details.
* @param options * @param options
*/ */
waitForSelector<K extends keyof HTMLElementTagNameMap>(selector: K, options?: ElementHandleWaitForSelectorOptionsNotHidden): Promise<ElementHandleForTag<K>>; waitForSelector<K extends keyof HTMLElementTagNameMap>(selector: K, options?: ElementHandleWaitForSelectorOptionsNotHidden): Promise<ElementHandleForTag<K>>;
@ -8212,8 +8215,8 @@ export interface Response {
} }
/** /**
* Selectors can be used to install custom selector engines. See [Working with selectors](https://github.com/microsoft/playwright/blob/master/docs/api.md#working-with-selectors) for more * Selectors can be used to install custom selector engines. See
* information. * [Working with selectors](https://github.com/microsoft/playwright/blob/master/docs/selectors.md#working-with-selectors) for more information.
*/ */
export interface Selectors { export interface Selectors {
/** /**

View file

@ -16,21 +16,20 @@
* limitations under the License. * limitations under the License.
*/ */
const fs = require('fs');
const ts = require('typescript'); const ts = require('typescript');
const path = require('path'); const path = require('path');
const Source = require('./doclint/Source');
async function checkDeps() { async function checkDeps() {
const root = path.normalize(path.join(__dirname, '..')); const root = path.normalize(path.join(__dirname, '..'));
const src = path.normalize(path.join(__dirname, '..', 'src')); const src = path.normalize(path.join(__dirname, '..', 'src'));
const sources = await Source.readdir(src);
const program = ts.createProgram({ const program = ts.createProgram({
options: { options: {
allowJs: true, allowJs: true,
target: ts.ScriptTarget.ESNext, target: ts.ScriptTarget.ESNext,
strict: true, strict: true,
}, },
rootNames: sources.map(source => source.filePath()), rootNames: listAllFiles(src),
}); });
const sourceFiles = program.getSourceFiles(); const sourceFiles = program.getSourceFiles();
const errors = []; const errors = [];
@ -92,6 +91,19 @@ async function checkDeps() {
} }
} }
function listAllFiles(dir) {
const dirs = fs.readdirSync(dir, { withFileTypes: true });
const result = [];
dirs.map(d => {
const res = path.resolve(dir, d.name);
if (d.isDirectory())
result.push(...listAllFiles(res));
else
result.push(res);
});
return result;
}
const DEPS = {}; const DEPS = {};
DEPS['src/protocol/'] = ['src/utils/']; DEPS['src/protocol/'] = ['src/utils/'];

View file

@ -91,14 +91,11 @@ class MDOutline {
} }
/** /**
* @param {string} content * @param {MarkdownNode[]} nodes
* @return {string}
*/ */
renderLinksInText(content) { renderLinksInText(nodes) {
const nodes = md.parse(content);
this._patchLinks(nodes); this._patchLinks(nodes);
return md.render(nodes, 80); }
}
generateSourceCodeComments() { generateSourceCodeComments() {
for (const clazz of this.classesArray) for (const clazz of this.classesArray)

View file

@ -1,128 +0,0 @@
/**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const path = require('path');
const util = require('util');
const fs = require('fs');
const readFileAsync = util.promisify(fs.readFile);
const statAsync = util.promisify(fs.stat);
const readdirAsync = util.promisify(fs.readdir);
const writeFileAsync = util.promisify(fs.writeFile);
const PROJECT_DIR = path.join(__dirname, '..', '..');
async function recursiveReadDir(dirPath, exclude) {
const files = [];
if (exclude.includes(dirPath))
return files;
for (const file of await readdirAsync(dirPath)) {
const fullPath = path.join(dirPath, file);
if ((await statAsync(fullPath)).isDirectory())
files.push(...await recursiveReadDir(fullPath, exclude))
else
files.push(fullPath);
}
return files;
}
class Source {
/**
* @param {string} filePath
* @param {string} text
*/
constructor(filePath, text) {
this._filePath = filePath;
this._projectPath = path.relative(PROJECT_DIR, filePath);
this._name = path.basename(filePath);
this._text = text;
this._originalText = text;
}
/**
* @return {string}
*/
filePath() {
return this._filePath;
}
/**
* @return {string}
*/
projectPath() {
return this._projectPath;
}
/**
* @return {string}
*/
name() {
return this._name;
}
/**
* @param {string} text
*/
setText(text) {
this._text = text;
}
/**
* @return {string}
*/
text() {
return this._text;
}
/**
* @return {boolean}
*/
hasUpdatedText() {
return this._text !== this._originalText;
}
async save() {
await writeFileAsync(this.filePath(), this.text());
}
async saveAs(path) {
await writeFileAsync(path, this.text());
}
/**
* @param {string} filePath
* @return {!Promise<Source>}
*/
static async readFile(filePath) {
filePath = path.resolve(filePath);
const text = await readFileAsync(filePath, {encoding: 'utf8'});
return new Source(filePath, text);
}
/**
* @param {string} dirPath
* @param {string=} extension
* @param {Array<string>=} exclude
* @return {!Promise<!Array<!Source>>}
*/
static async readdir(dirPath, extension = '', exclude = []) {
extension = extension.toLowerCase();
const filePaths = (await recursiveReadDir(dirPath, exclude)).filter(fileName => fileName.toLowerCase().endsWith(extension));
return Promise.all(filePaths.map(filePath => Source.readFile(filePath)));
}
}
module.exports = Source;

View file

@ -20,26 +20,19 @@
const playwright = require('../../'); const playwright = require('../../');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const Source = require('./Source');
const md = require('../markdown'); const md = require('../markdown');
const { spawnSync } = require('child_process');
const preprocessor = require('./preprocessor');
const { MDOutline } = require('./MDBuilder'); const { MDOutline } = require('./MDBuilder');
const missingDocs = require('./missingDocs');
const Documentation = require('./Documentation'); const Documentation = require('./Documentation');
const missingDocs = require('./missingDocs');
/** @typedef {import('./Documentation').Type} Type */ /** @typedef {import('./Documentation').Type} Type */
/** @typedef {import('../markdown').MarkdownNode} MarkdownNode */ /** @typedef {import('../markdown').MarkdownNode} MarkdownNode */
const PROJECT_DIR = path.join(__dirname, '..', '..'); const PROJECT_DIR = path.join(__dirname, '..', '..');
const VERSION = require(path.join(PROJECT_DIR, 'package.json')).version;
const RED_COLOR = '\x1b[31m';
const YELLOW_COLOR = '\x1b[33m';
const RESET_COLOR = '\x1b[0m';
const links = new Map(); const links = new Map();
const rLinks = new Map(); const rLinks = new Map();
const dirtyFiles = new Set();
run().catch(e => { run().catch(e => {
console.error(e); console.error(e);
@ -47,153 +40,160 @@ run().catch(e => {
});; });;
async function run() { async function run() {
const startTime = Date.now();
/** @type {!Array<string>} */
const errors = [];
let changedFiles = false;
const header = fs.readFileSync(path.join(PROJECT_DIR, 'docs-src', 'api-header.md')).toString();
let footer = fs.readFileSync(path.join(PROJECT_DIR, 'docs-src', 'api-footer.md')).toString();
const links = fs.readFileSync(path.join(PROJECT_DIR, 'docs-src', 'api-links.md')).toString();
const outline = new MDOutline(path.join(PROJECT_DIR, 'docs-src', 'api-body.md'), path.join(PROJECT_DIR, 'docs-src', 'api-params.md')); const outline = new MDOutline(path.join(PROJECT_DIR, 'docs-src', 'api-body.md'), path.join(PROJECT_DIR, 'docs-src', 'api-params.md'));
const generatedComment = '<!-- THIS FILE IS NOW GENERATED -->'; outline.setLinkRenderer(item => {
const { clazz, member, param, option } = item;
if (param)
return `\`${param}\``;
if (option)
return `\`${option}\``;
if (clazz)
return `[${clazz.name}]`;
return createMemberLink(member);
});
let generatedLinksSuffix; let generatedLinksSuffix;
const api = await Source.readFile(path.join(PROJECT_DIR, 'docs', 'api.md')); {
const docs = await (await Source.readdir(path.join(PROJECT_DIR, 'docs'), '.md')).filter(s => s.name() !== 'api.md'); const links = fs.readFileSync(path.join(PROJECT_DIR, 'docs-src', 'links.md')).toString();
const localLinks = [];
for (const clazz of outline.classesArray)
localLinks.push(`[${clazz.name}]: api/class-${clazz.name.toLowerCase()}.md "${clazz.name}"`);
generatedLinksSuffix = localLinks.join('\n') + '\n' + links;
}
// Produce api.md // Produce api.md
{ {
outline.setLinkRenderer(item => { for (const clazz of outline.classesArray) {
const { clazz, member, param, option } = item;
if (param)
return `\`${param}\``;
if (option)
return `\`${option}\``;
if (clazz)
return `[${clazz.name}]`;
return createMemberLink(member);
});
{
const localLinks = [];
for (const clazz of outline.classesArray)
localLinks.push(`[${clazz.name}]: api.md#class-${clazz.name.toLowerCase()} "${clazz.name}"`);
generatedLinksSuffix = localLinks.join('\n') + '\n' + links;
}
{
/** @type {MarkdownNode[]} */ /** @type {MarkdownNode[]} */
const result = []; const result = [];
for (const clazz of outline.classesArray) { result.push({
// Iterate over classes, create header node. type: 'text',
/** @type {MarkdownNode} */ text: `---
const classNode = { type: 'h3', text: `class: ${clazz.name}` }; id: class-${clazz.name.toLowerCase()}
result.push(classNode); title: "class: ${clazz.name}"
// Append class comments ---
classNode.children = (clazz.spec || []).map(c => md.clone(c)); `});
classNode.children.push({ result.push(...(clazz.spec || []).map(c => md.clone(c)));
type: 'text', result.push({
text: '' type: 'text',
}); text: ''
classNode.children.push(...generateToc(clazz)); });
if (clazz.extends && clazz.extends !== 'EventEmitter' && clazz.extends !== 'Error') { result.push(...generateClassToc(clazz));
const superClass = outline.documentation.classes.get(clazz.extends); if (clazz.extends && clazz.extends !== 'EventEmitter' && clazz.extends !== 'Error') {
classNode.children.push(...generateToc(superClass)); const superClass = outline.documentation.classes.get(clazz.extends);
} result.push(...generateClassToc(superClass));
for (const member of clazz.membersArray) {
// Iterate members
/** @type {MarkdownNode} */
const memberNode = { type: 'h4', children: [] };
if (member.kind === 'event') {
memberNode.text = `${clazz.varName}.on('${member.name}')`;
} else if (member.kind === 'property') {
memberNode.text = `${clazz.varName}.${member.name}`;
} else if (member.kind === 'method') {
// Patch method signatures
memberNode.text = `${clazz.varName}.${member.name}(${member.signature})`;
for (const arg of member.argsArray) {
if (arg.type)
memberNode.children.push(renderProperty(`\`${arg.name}\``, arg.type, arg.spec));
}
}
// Append type
if (member.type && member.type.name !== 'void') {
let name;
switch (member.kind) {
case 'event': name = 'type:'; break;
case 'property': name = 'type:'; break;
case 'method': name = 'returns:'; break;
}
memberNode.children.push(renderProperty(name, member.type));
}
// Append member doc
memberNode.children.push(...(member.spec || []).map(c => md.clone(c)));
classNode.children.push(memberNode);
}
} }
footer = outline.renderLinksInText(footer);
api.setText([generatedComment, header, md.render(result), footer, generatedLinksSuffix].join('\n')); for (const member of clazz.membersArray) {
// Iterate members
/** @type {MarkdownNode} */
const memberNode = { type: 'h4', children: [] };
if (member.kind === 'event') {
memberNode.text = `${clazz.varName}.on('${member.name}')`;
} else if (member.kind === 'property') {
memberNode.text = `${clazz.varName}.${member.name}`;
} else if (member.kind === 'method') {
// Patch method signatures
memberNode.text = `${clazz.varName}.${member.name}(${member.signature})`;
for (const arg of member.argsArray) {
if (arg.type)
memberNode.children.push(renderProperty(`\`${arg.name}\``, arg.type, arg.spec));
}
}
// Append type
if (member.type && member.type.name !== 'void') {
let name;
switch (member.kind) {
case 'event': name = 'type:'; break;
case 'property': name = 'type:'; break;
case 'method': name = 'returns:'; break;
}
memberNode.children.push(renderProperty(name, member.type));
}
// Append member doc
memberNode.children.push(...(member.spec || []).map(c => md.clone(c)));
result.push(memberNode);
}
writeAssumeNoop(path.join(PROJECT_DIR, 'docs', `class-${clazz.name.toLowerCase()}.md`), [md.render(result), generatedLinksSuffix].join('\n'), dirtyFiles);
} }
} }
// Produce other docs // Produce other docs
{ {
for (const doc of docs) { for (const name of fs.readdirSync(path.join(PROJECT_DIR, 'docs-src'))) {
if (!fs.existsSync(path.join(PROJECT_DIR, 'docs-src', doc.name()))) if (name === 'links.md' || name.startsWith('api-'))
continue; continue;
const content = fs.readFileSync(path.join(PROJECT_DIR, 'docs-src', doc.name())).toString(); const content = fs.readFileSync(path.join(PROJECT_DIR, 'docs-src', name)).toString();
doc.setText([generatedComment, outline.renderLinksInText(content), generatedLinksSuffix].join('\n')); const nodes = md.parse(content);
outline.renderLinksInText(nodes);
for (const node of nodes) {
if (node.text === '<!-- TOC -->')
node.text = md.generateToc(nodes);
}
writeAssumeNoop(path.join(PROJECT_DIR, 'docs', name), [md.render(nodes), generatedLinksSuffix].join('\n'), dirtyFiles);
} }
} }
// Documentation checks. // Patch README.md
{ {
const readme = await Source.readFile(path.join(PROJECT_DIR, 'README.md')); const versions = await getBrowserVersions();
const binReadme = await Source.readFile(path.join(PROJECT_DIR, 'bin', 'README.md')); const params = new Map();
const contributing = await Source.readFile(path.join(PROJECT_DIR, 'CONTRIBUTING.md')); const { chromium, firefox, webkit } = versions;
const mdSources = [readme, binReadme, api, contributing, ...docs]; params.set('chromium-version', chromium);
params.set('firefox-version', firefox);
params.set('webkit-version', webkit);
params.set('chromium-version-badge', `[![Chromium version](https://img.shields.io/badge/chromium-${chromium}-blue.svg?logo=google-chrome)](https://www.chromium.org/Home)`);
params.set('firefox-version-badge', `[![Firefox version](https://img.shields.io/badge/firefox-${firefox}-blue.svg?logo=mozilla-firefox)](https://www.mozilla.org/en-US/firefox/new/)`);
params.set('webkit-version-badge', `[![WebKit version](https://img.shields.io/badge/webkit-${webkit}-blue.svg?logo=safari)](https://webkit.org/)`);
const browserVersions = await getBrowserVersions(); let content = fs.readFileSync(path.join(PROJECT_DIR, 'README.md')).toString();
errors.push(...(await preprocessor.runCommands(mdSources, { content = content.replace(/<!-- GEN:([^ ]+) -->([^<]*)<!-- GEN:stop -->/ig, (match, p1) => {
libversion: VERSION, if (!params.has(p1)) {
chromiumVersion: browserVersions.chromium, console.log(`ERROR: Invalid generate parameter "${p1}" in "${match}"`);
firefoxVersion: browserVersions.firefox, process.exit(1);
webkitVersion: browserVersions.webkit, }
}))); return `<!-- GEN:${p1} -->${params.get(p1)}<!-- GEN:stop -->`;
});
writeAssumeNoop(path.join(PROJECT_DIR, 'README.md'), content, dirtyFiles);
}
errors.push(...preprocessor.findInvalidLinks(PROJECT_DIR, mdSources, getRepositoryFiles())); // Check for missing docs
const jsSources = await Source.readdir(path.join(PROJECT_DIR, 'src', 'client'), '', []); {
errors.push(...missingDocs(outline, jsSources, path.join(PROJECT_DIR, 'src', 'client', 'api.ts'))); const srcClient = path.join(PROJECT_DIR, 'src', 'client');
const sources = fs.readdirSync(srcClient).map(n => path.join(srcClient, n));
for (const source of mdSources) { const errors = missingDocs(outline, sources, path.join(srcClient, 'api.ts'));
if (!source.hasUpdatedText()) if (errors.length) {
continue; console.log('============================');
await source.save(); console.log('ERROR: missing documentation:');
changedFiles = true; errors.forEach(e => console.log(e));
console.log('============================')
process.exit(1);
} }
} }
// Report results. if (dirtyFiles.size) {
if (errors.length) { console.log('============================')
for (let i = 0; i < errors.length; ++i) { console.log('ERROR: generated markdown files have changed, this is only error if happens in CI:');
const error = errors[i].split('\n').join('\n '); [...dirtyFiles].forEach(f => console.log(f));
console.log(` ${i + 1}) ${RED_COLOR}${error}${RESET_COLOR}`); console.log('============================')
} process.exit(1);
} }
let clearExit = errors.length === 0; process.exit(0);
if (changedFiles) { }
if (clearExit)
console.log(`${YELLOW_COLOR}Some files were updated.${RESET_COLOR}`); /**
clearExit = false; * @param {string} name
* @param {string} content
* @param {Set<string>} dirtyFiles
*/
function writeAssumeNoop(name, content, dirtyFiles) {
const oldContent = fs.readFileSync(name).toString();
if (oldContent !== content) {
fs.writeFileSync(name, content);
dirtyFiles.add(name);
} }
console.log(`${errors.length} failures.`);
const runningTime = Date.now() - startTime;
console.log(`DocLint Finished in ${runningTime / 1000} seconds`);
process.exit(clearExit ? 0 : 1);
} }
async function getBrowserVersions() { async function getBrowserVersions() {
@ -207,12 +207,6 @@ async function getBrowserVersions() {
return result; return result;
} }
function getRepositoryFiles() {
const out = spawnSync('git', ['ls-files'], {cwd: PROJECT_DIR});
const files = out.stdout.toString().trim().split('\n').filter(f => !f.startsWith('docs-src'));
return files.map(file => path.join(PROJECT_DIR, file));
}
/** /**
* @param {string} file * @param {string} file
* @param {string} text * @param {string} text
@ -237,7 +231,7 @@ function createLink(file, text) {
* @return {string} * @return {string}
*/ */
function createMemberLink(member) { function createMemberLink(member) {
const file = `./api.md`; const file = `api/class-${member.clazz.name.toLowerCase()}.md`;
if (member.kind === 'property') if (member.kind === 'property')
return createLink(file, `${member.clazz.varName}.${member.name}`); return createLink(file, `${member.clazz.varName}.${member.name}`);
@ -252,7 +246,7 @@ function createMemberLink(member) {
* @param {Documentation.Class} clazz * @param {Documentation.Class} clazz
* @return {MarkdownNode[]} * @return {MarkdownNode[]}
*/ */
function generateToc(clazz) { function generateClassToc(clazz) {
/** @type {MarkdownNode[]} */ /** @type {MarkdownNode[]} */
const result = []; const result = [];
for (const member of clazz.membersArray) { for (const member of clazz.membersArray) {

View file

@ -82,16 +82,16 @@ function paramsForMember(member) {
} }
/** /**
* @param {!Array<!import('../Source')>} sources * @param {string[]} rootNames
*/ */
function listMethods(sources, apiFileName) { function listMethods(rootNames, apiFileName) {
const program = ts.createProgram({ const program = ts.createProgram({
options: { options: {
allowJs: true, allowJs: true,
target: ts.ScriptTarget.ESNext, target: ts.ScriptTarget.ESNext,
strict: true strict: true
}, },
rootNames: sources.map(source => source.filePath()) rootNames
}); });
const checker = program.getTypeChecker(); const checker = program.getTypeChecker();
const apiClassNames = new Set(); const apiClassNames = new Set();

View file

@ -1,259 +0,0 @@
/**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//@ts-check
const path = require('path');
function runCommands(sources, {libversion, chromiumVersion, firefoxVersion, webkitVersion}) {
// Release version is everything that doesn't include "-".
const isReleaseVersion = !libversion.includes('-');
const errors = [];
for (const source of sources) {
const text = source.text();
const commandStartRegex = /<!--\s*gen:([a-z-]+)\s*-->/ig;
const commandEndRegex = /<!--\s*gen:stop\s*-->/ig;
let start;
const sourceEdits = new SourceEdits(source);
// Extract all commands from source
while (start = commandStartRegex.exec(text)) { // eslint-disable-line no-cond-assign
commandEndRegex.lastIndex = commandStartRegex.lastIndex;
const end = commandEndRegex.exec(text);
if (!end) {
errors.push(`Failed to find 'gen:stop' for command ${start[0]}`);
return errors;
}
const commandName = start[1];
const from = commandStartRegex.lastIndex;
const to = end.index;
commandStartRegex.lastIndex = commandEndRegex.lastIndex;
let newText = null;
if (commandName === 'chromium-version')
newText = chromiumVersion;
else if (commandName === 'firefox-version')
newText = firefoxVersion;
else if (commandName === 'webkit-version')
newText = webkitVersion;
else if (commandName === 'chromium-version-badge')
newText = `[![Chromium version](https://img.shields.io/badge/chromium-${chromiumVersion}-blue.svg?logo=google-chrome)](https://www.chromium.org/Home)`;
else if (commandName === 'firefox-version-badge')
newText = `[![Firefox version](https://img.shields.io/badge/firefox-${firefoxVersion}-blue.svg?logo=mozilla-firefox)](https://www.mozilla.org/en-US/firefox/new/)`;
else if (commandName === 'version')
newText = isReleaseVersion ? 'v' + libversion : 'Tip-Of-Tree';
else if (commandName === 'toc')
newText = generateTableOfContents(source.text(), to, false /* topLevelOnly */);
else if (commandName === 'toc-top-level')
newText = generateTableOfContents(source.text(), to, true /* topLevelOnly */);
if (newText === null)
errors.push(`Unknown command 'gen:${commandName}'`);
else
sourceEdits.edit(from, to, newText);
}
sourceEdits.commit(errors);
}
return errors;
};
function getTOCEntriesForText(text) {
const ids = new Set();
const titles = [];
const titleRegex = /^(#+)\s+(.*)$/;
let insideCodeBlock = false;
let offset = 0;
text.split('\n').forEach((aLine, lineNumber) => {
const line = aLine.trim();
if (line.startsWith('```'))
insideCodeBlock = !insideCodeBlock;
else if (!insideCodeBlock && line.match(titleRegex))
titles.push({line, offset: offset + lineNumber});
offset += aLine.length;
});
let tocEntries = [];
for (const {line, offset} of titles) {
const [, nesting, name] = line.match(titleRegex);
const delinkifiedName = name.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1');
const id = delinkifiedName.trim().toLowerCase().replace(/\s/g, '-').replace(/[^-_0-9a-zа-яё]/ig, '');
let dedupId = id;
let counter = 0;
while (ids.has(dedupId))
dedupId = id + '-' + (++counter);
ids.add(dedupId);
tocEntries.push({
level: nesting.length,
name: delinkifiedName,
id: dedupId,
offset,
});
}
return tocEntries;
}
function findInvalidLinks(projectRoot, sources, allowedFilePaths) {
const pathToHashLinks = new Map();
for (const source of sources) {
const text = source.text();
const hashLinks = new Set(getTOCEntriesForText(text).map(entry => entry.id));
pathToHashLinks.set(source.filePath(), hashLinks);
}
const errors = [];
for (const source of sources) {
const allRelativePaths = [];
for (const filepath of allowedFilePaths) {
allRelativePaths.push('/' + path.relative(projectRoot, filepath));
allRelativePaths.push(path.relative(path.dirname(source.filePath()), filepath));
}
let offset = 0;
const lines = source.text().split('\n');
lines.forEach((line, lineNumber) => {
const linkRegex = /\]\(([^\)]*)\)/gm;
let match;
while (match = linkRegex.exec(line)) {
const hrefOffset = offset + lineNumber + match.index + 2; // +2 since we have to skip ](
const [, href] = match;
if (href.startsWith('http://') || href.startsWith('https://') || href.startsWith('mailto:'))
continue;
const [relativePath, hash] = href.split('#');
let resolvedPath = resolveLinkPath(source, relativePath);
let hashLinks = pathToHashLinks.get(resolvedPath);
if (!hashLinks) {
const newRelativePath = autocorrectText(relativePath, allRelativePaths);
if (relativePath !== newRelativePath)
errors.push(`Bad link in ${source.projectPath()}:${lineNumber + 1}: file ${relativePath} does not exist, did you mean ${newRelativePath}?`);
continue;
}
if (!hash || hashLinks.has(hash))
continue;
const newHashLink = autocorrectText(hash, [...hashLinks]);
if (hash !== newHashLink)
errors.push(`Bad link in ${source.projectPath()}:${lineNumber + 1}: hash "#${hash}" does not exist in "${path.relative(projectRoot, resolvedPath)}", did you mean ${newHashLink}?`);
}
offset += line.length;
});
}
return errors;
function resolveLinkPath(source, relativePath) {
if (!relativePath)
return source.filePath();
if (relativePath.startsWith('/'))
return path.resolve(projectRoot, '.' + relativePath);
return path.resolve(path.dirname(source.filePath()), relativePath);
}
}
class SourceEdits {
constructor(source) {
this._source = source;
this._edits = [];
}
edit(from, to, newText) {
this._edits.push({from, to, newText});
}
commit(errors = []) {
if (!this._edits.length)
return;
this._edits.sort((a, b) => a.from - b.from);
for (const edit of this._edits) {
if (edit.from > edit.to) {
errors.push('INTERNAL ERROR: incorrect edit!');
return;
}
}
for (let i = 0; i < this._edits.length - 1; ++i) {
if (this._edits[i].to > this._edits[i + 1].from) {
errors.push('INTERNAL ERROR: edits are overlapping!');
return;
}
}
this._edits.reverse();
let text = this._source.text();
for (const edit of this._edits)
text = text.substring(0, edit.from) + edit.newText + text.substring(edit.to);
this._source.setText(text);
}
}
function autocorrectText(text, options, maxCorrectionsRatio = 0.5) {
if (!options.length)
return null;
const scores = options.map(option => ({option, score: levenshteinDistance(text, option)}));
scores.sort((a, b) => a.score - b.score);
if (scores[0].score > text.length * maxCorrectionsRatio)
return null;
return scores[0].option;
}
function levenshteinDistance(a, b) {
const N = a.length, M = b.length;
const d = new Int32Array(N * M);
for (let i = 0; i < N * M; ++i)
d[i] = 0;
for (let j = 0; j < M; ++j)
d[j] = j;
for (let i = 0; i < N; ++i)
d[i * M] = i;
for (let i = 1; i < N; ++i) {
for (let j = 1; j < M; ++j) {
const cost = a[i] === b[j] ? 0 : 1;
d[i * M + j] = Math.min(
d[(i - 1) * M + j] + 1, // d[i-1][j] + 1
d[i * M + j - 1] + 1, // d[i][j - 1] + 1
d[(i - 1) * M + j - 1] + cost // d[i - 1][j - 1] + cost
);
}
}
return d[N * M - 1];
}
function generateTableOfContents(text, offset, topLevelOnly) {
const allTocEntries = getTOCEntriesForText(text);
let tocEntries = [];
let nesting = 0;
for (const tocEntry of allTocEntries) {
if (tocEntry.offset < offset)
continue;
if (tocEntries.length) {
nesting += tocEntry.level - tocEntries[tocEntries.length - 1].level;
if (nesting < 0)
break;
}
tocEntries.push(tocEntry);
}
const minLevel = Math.min(...tocEntries.map(entry => entry.level));
tocEntries.forEach(entry => entry.level -= minLevel);
if (topLevelOnly)
tocEntries = tocEntries.filter(entry => !entry.level);
return '\n' + tocEntries.map(entry => {
const prefix = entry.level % 2 === 0 ? '-' : '*';
const padding = ' '.repeat(entry.level);
return `${padding}${prefix} [${entry.name}](#${entry.id})`;
}).join('\n') + '\n';
}
module.exports = {findInvalidLinks, runCommands};

View file

@ -18,7 +18,6 @@
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const missingDocs = require('../missingDocs'); const missingDocs = require('../missingDocs');
const Source = require('../Source');
const { folio } = require('folio'); const { folio } = require('folio');
const { MDOutline } = require('../MDBuilder'); const { MDOutline } = require('../MDBuilder');
@ -27,8 +26,8 @@ const { test, expect } = folio;
test('missing docs', async ({}) => { test('missing docs', async ({}) => {
const outline = new MDOutline(path.join(__dirname, 'test-api.md')); const outline = new MDOutline(path.join(__dirname, 'test-api.md'));
const tsSources = [ const tsSources = [
await Source.readFile(path.join(__dirname, 'test-api.ts')), path.join(__dirname, 'test-api.ts'),
await Source.readFile(path.join(__dirname, 'test-api-class.ts')), path.join(__dirname, 'test-api-class.ts'),
]; ];
const errors = missingDocs(outline, tsSources, path.join(__dirname, 'test-api.ts')); const errors = missingDocs(outline, tsSources, path.join(__dirname, 'test-api.ts'));
expect(errors).toEqual([ expect(errors).toEqual([

View file

@ -1,197 +0,0 @@
/**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const {runCommands} = require('../preprocessor');
const Source = require('../Source');
const { folio } = require('folio');
const { describe, it, expect } = folio;
describe('runCommands', function() {
const OPTIONS_REL = {
libversion: '1.3.0',
chromiumVersion: '80.0.4004.0',
firefoxVersion: '73.0b3',
};
const OPTIONS_DEV = {
libversion: '1.3.0-post',
chromiumVersion: '<CRVERSION>',
firefoxVersion: '<FFVERSION>',
};
it('should throw for unknown command', function() {
const source = new Source('doc.md', `
<!-- gen:unknown-command -->something<!-- gen:stop -->
`);
const errors = runCommands([source], OPTIONS_REL);
expect(source.hasUpdatedText()).toBe(false);
expect(errors.length).toBe(1);
expect(errors[0]).toContain('Unknown command');
});
describe('gen:version', function() {
it('should work', function() {
const source = new Source('doc.md', `
Playwright <!-- gen:version -->XXX<!-- gen:stop -->
`);
const errors = runCommands([source], OPTIONS_REL);
expect(errors.length).toBe(0);
expect(source.hasUpdatedText()).toBe(true);
expect(source.text()).toBe(`
Playwright <!-- gen:version -->v1.3.0<!-- gen:stop -->
`);
});
it('should work for pre-release versions', function() {
const source = new Source('doc.md', `
Playwright <!-- gen:version -->XXX<!-- gen:stop -->
`);
const errors = runCommands([source], OPTIONS_DEV);
expect(errors.length).toBe(0);
expect(source.hasUpdatedText()).toBe(true);
expect(source.text()).toBe(`
Playwright <!-- gen:version -->Tip-Of-Tree<!-- gen:stop -->
`);
});
it('should tolerate different writing', function() {
const source = new Source('doc.md', `Playwright v<!-- gEn:version -->WHAT
<!-- GEN:stop -->`);
runCommands([source], OPTIONS_REL);
expect(source.text()).toBe(`Playwright v<!-- gEn:version -->v1.3.0<!-- GEN:stop -->`);
});
it('should not tolerate missing gen:stop', function() {
const source = new Source('doc.md', `<!--GEN:version-->`);
const errors = runCommands([source], OPTIONS_REL);
expect(source.hasUpdatedText()).toBe(false);
expect(errors.length).toBe(1);
expect(errors[0]).toContain(`Failed to find 'gen:stop'`);
});
});
describe('gen:toc', function() {
it('should work', () => {
const source = new Source('doc.md', `<!-- gen:toc -->XXX<!-- gen:stop -->
### class: page
#### page.$
#### page.$$`);
const errors = runCommands([source], OPTIONS_REL);
expect(errors.length).toBe(0);
expect(source.hasUpdatedText()).toBe(true);
expect(source.text()).toBe(`<!-- gen:toc -->
- [class: page](#class-page)
* [page.$](#page)
* [page.$$](#page-1)
<!-- gen:stop -->
### class: page
#### page.$
#### page.$$`);
});
it('should work with code blocks', () => {
const source = new Source('doc.md', `<!-- gen:toc -->XXX<!-- gen:stop -->
### class: page
\`\`\`bash
# yo comment
\`\`\`
`);
const errors = runCommands([source], OPTIONS_REL);
expect(errors.length).toBe(0);
expect(source.hasUpdatedText()).toBe(true);
expect(source.text()).toBe(`<!-- gen:toc -->
- [class: page](#class-page)
<!-- gen:stop -->
### class: page
\`\`\`bash
# yo comment
\`\`\`
`);
});
it('should work with links in titles', () => {
const source = new Source('doc.md', `<!-- gen:toc -->XXX<!-- gen:stop -->
### some [link](#foobar) here
`);
const errors = runCommands([source], OPTIONS_REL);
expect(errors.length).toBe(0);
expect(source.hasUpdatedText()).toBe(true);
expect(source.text()).toBe(`<!-- gen:toc -->
- [some link here](#some-link-here)
<!-- gen:stop -->
### some [link](#foobar) here
`);
});
it('should be able to create sub-table-of-contents', () => {
const source = new Source('doc.md', `
## First
<!-- gen:toc -->XXX<!-- gen:stop -->
### first.1
### first.2
#### first.2.1
## Second
`);
const errors = runCommands([source], OPTIONS_REL);
expect(errors.length).toBe(0);
expect(source.hasUpdatedText()).toBe(true);
expect(source.text()).toBe(`
## First
<!-- gen:toc -->
- [first.1](#first1)
- [first.2](#first2)
* [first.2.1](#first21)
<!-- gen:stop -->
### first.1
### first.2
#### first.2.1
## Second
`);
});
});
it('should work with multiple commands', function() {
const source = new Source('doc.md', `
<!-- gen:version -->xxx<!-- gen:stop -->
<!-- gen:version -->zzz<!-- gen:stop -->
`);
const errors = runCommands([source], OPTIONS_REL);
expect(errors.length).toBe(0);
expect(source.hasUpdatedText()).toBe(true);
expect(source.text()).toBe(`
<!-- gen:version -->v1.3.0<!-- gen:stop -->
<!-- gen:version -->v1.3.0<!-- gen:stop -->
`);
});
describe('gen:chromium-version', function() {
it('should work', function() {
const source = new Source('doc.md', `
Playwright <!-- gen:chromium-version -->XXX<!-- gen:stop -->
`);
const errors = runCommands([source], OPTIONS_REL);
expect(errors.length).toBe(0);
expect(source.hasUpdatedText()).toBe(true);
expect(source.text()).toBe(`
Playwright <!-- gen:chromium-version -->80.0.4004.0<!-- gen:stop -->
`);
});
});
describe('gen:firefox-version', function() {
it('should work', function() {
const source = new Source('doc.md', `
Playwright <!-- gen:firefox-version -->XXX<!-- gen:stop -->
`);
const errors = runCommands([source], OPTIONS_REL);
expect(errors.length).toBe(0);
expect(source.hasUpdatedText()).toBe(true);
expect(source.text()).toBe(`
Playwright <!-- gen:firefox-version -->73.0b3<!-- gen:stop -->
`);
});
});
});

View file

@ -17,7 +17,7 @@
// @ts-check // @ts-check
/** @typedef {{ /** @typedef {{
* type: 'text' | 'li' | 'code' | 'h0' | 'h1' | 'h2' | 'h3' | 'h4', * type: 'text' | 'li' | 'code' | 'properties' | 'h0' | 'h1' | 'h2' | 'h3' | 'h4',
* text?: string, * text?: string,
* codeLang?: string, * codeLang?: string,
* lines?: string[], * lines?: string[],
@ -42,7 +42,7 @@ function flattenWrappedLines(content) {
|| trimmedLine.startsWith('*') || trimmedLine.startsWith('*')
|| line.match(/\[[^\]]+\]:.*/) || line.match(/\[[^\]]+\]:.*/)
|| singleLineExpression; || singleLineExpression;
if (trimmedLine.startsWith('```')) { if (trimmedLine.startsWith('```') || trimmedLine.startsWith('---')) {
inCodeBlock = !inCodeBlock; inCodeBlock = !inCodeBlock;
flushLastParagraph = true; flushLastParagraph = true;
} }
@ -133,6 +133,23 @@ function buildTree(lines) {
continue; continue;
} }
if (content.startsWith('---')) {
/** @type {MarkdownNode} */
const node = {
type: 'properties',
lines: [],
};
line = lines[++i];
while (!line.trim().startsWith('---')) {
if (!line.startsWith(indent))
throw new Error('Bad header block ' + line);
node.lines.push(line.substring(indent.length));
line = lines[++i];
}
appendNode(indent, node);
continue;
}
const liType = content.match(/^(-|1.|\*) /); const liType = content.match(/^(-|1.|\*) /);
const node = /** @type {MarkdownNode} */({ type: 'text', text: content }); const node = /** @type {MarkdownNode} */({ type: 'text', text: content });
if (liType) { if (liType) {
@ -203,6 +220,7 @@ function innerRenderMdNode(indent, node, lastNode, result, maxColumns) {
if (!bothTables && !bothGen && !bothComments && !bothLinks && lastNode && lastNode.text) if (!bothTables && !bothGen && !bothComments && !bothLinks && lastNode && lastNode.text)
newLine(); newLine();
result.push(wrapText(node.text, maxColumns, indent)); result.push(wrapText(node.text, maxColumns, indent));
return;
} }
if (node.type === 'code') { if (node.type === 'code') {
@ -212,6 +230,16 @@ function innerRenderMdNode(indent, node, lastNode, result, maxColumns) {
result.push(indent + line); result.push(indent + line);
result.push(`${indent}\`\`\``); result.push(`${indent}\`\`\``);
newLine(); newLine();
return;
}
if (node.type === 'properties') {
result.push(`${indent}---`);
for (const line of node.lines)
result.push(indent + line);
result.push(`${indent}---`);
newLine();
return;
} }
if (node.type === 'li') { if (node.type === 'li') {
@ -283,7 +311,7 @@ function clone(node) {
/** /**
* @param {MarkdownNode[]} nodes * @param {MarkdownNode[]} nodes
* @param {function(MarkdownNode): void} visitor * @param {function(MarkdownNode, number): void} visitor
*/ */
function visitAll(nodes, visitor) { function visitAll(nodes, visitor) {
for (const node of nodes) for (const node of nodes)
@ -292,12 +320,29 @@ function visitAll(nodes, visitor) {
/** /**
* @param {MarkdownNode} node * @param {MarkdownNode} node
* @param {function(MarkdownNode): void} visitor * @param {function(MarkdownNode, number): void} visitor
*/ */
function visit(node, visitor) { function visit(node, visitor, depth = 0) {
visitor(node); visitor(node, depth);
for (const n of node.children || []) for (const n of node.children || [])
visit(n, visitor); visit(n, visitor, depth + 1);
} }
module.exports = { parse, render, clone, visitAll, visit }; /**
* @param {MarkdownNode[]} nodes
* @returns {string}
*/
function generateToc(nodes) {
const result = [];
visitAll(nodes, (node, depth) => {
if (node.type === 'h1' || node.type === 'h2') {
let link = node.text.toLowerCase();
link = link.replace(/[ ]+/g, '-');
link = link.replace(/[^\w-]/g, '');
result.push(`${' '.repeat(depth * 2)}- [${node.text}](#${link})`);
}
});
return result.join('\n');
}
module.exports = { parse, render, clone, visitAll, visit, generateToc };