diff --git a/docs/api.md b/docs/api.md index 4772659ba7..1a02a24fb1 100644 --- a/docs/api.md +++ b/docs/api.md @@ -6,18 +6,16 @@ - [Playwright module](#playwright-module) -- [class: BrowserType](#class-browsertype) - [class: Browser](#class-browser) -- [class: BrowserApp](#class-browserapp) - [class: BrowserContext](#class-browsercontext) +- [class: Page](#class-page) +- [class: Frame](#class-frame) +- [class: ElementHandle](#class-elementhandle) +- [class: JSHandle](#class-jshandle) - [class: ConsoleMessage](#class-consolemessage) - [class: Dialog](#class-dialog) -- [class: ElementHandle](#class-elementhandle) -- [class: Frame](#class-frame) -- [class: JSHandle](#class-jshandle) - [class: Keyboard](#class-keyboard) - [class: Mouse](#class-mouse) -- [class: Page](#class-page) - [class: Request](#class-request) - [class: Response](#class-response) - [class: WebSocket](#class-websocket) @@ -25,6 +23,8 @@ - [class: Accessibility](#class-accessibility) - [class: Coverage](#class-coverage) - [class: Worker](#class-worker) +- [class: BrowserApp](#class-browserapp) +- [class: BrowserType](#class-browsertype) - [class: ChromiumBrowser](#class-chromiumbrowser) - [class: ChromiumSession](#class-chromiumsession) - [class: ChromiumTarget](#class-chromiumtarget) @@ -68,7 +68,7 @@ This object can be used to launch or connect to Chromium, returning instances of #### playwright.devices - returns: <[Object]> -Returns a list of devices to be used with [`page.emulate(options)`](#pageemulateoptions). Actual list of +Returns a list of devices to be used with [`browser.newContext(options)`](#browsernewcontextoptions). Actual list of devices can be found in [src/deviceDescriptors.ts](https://github.com/Microsoft/playwright/blob/master/src/deviceDescriptors.ts). ```js @@ -118,150 +118,6 @@ This object can be used to launch or connect to Firefox, returning instances of This object can be used to launch or connect to WebKit, returning instances of [WebKitBrowser]. -### 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 context = await browser.newContext(); - const page = await context.newPage('http://example.com'); - // other actions... - await browser.close(); -})(); -``` - - -- [browserType.connect(options)](#browsertypeconnectoptions) -- [browserType.defaultArgs([options])](#browsertypedefaultargsoptions) -- [browserType.devices](#browsertypedevices) -- [browserType.errors](#browsertypeerrors) -- [browserType.executablePath()](#browsertypeexecutablepath) -- [browserType.launch([options])](#browsertypelaunchoptions) -- [browserType.launchBrowserApp([options])](#browsertypelaunchbrowserappoptions) - - -#### browserType.connect(options) -- `options` <[Object]> - - `browserWSEndpoint` [string]> A browser websocket endpoint to connect to. - - `slowMo` <[number]> Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. - - `browserURL` [string]> **Chromium-only** A browser url to connect to, in format `http://${host}:${port}`. Use interchangeably with `browserWSEndpoint` to let Playwright fetch it from [metadata endpoint](https://chromedevtools.github.io/devtools-protocol/#how-do-i-access-the-browser-target). - - `transport` <[ConnectionTransport]> **Experimental** Specify a custom transport object for Playwright to use. -- returns: <[Promise]<[Browser]>> - -This methods attaches Playwright to an existing browser instance. - -#### browserType.defaultArgs([options]) -- `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields: - - `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`. - - `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/). - - `userDataDir` <[string]> Path to a [User Data Directory](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md). - - `devtools` <[boolean]> **Chromium-only** Whether to auto-open a Developer Tools panel for each tab. If this option is `true`, the `headless` option will be set `false`. -- returns: <[Array]<[string]>> - -The default flags that browser will be launched with. - -#### browserType.devices -- returns: <[Object]> - -Returns a list of devices to be used with [`page.emulate(options)`](#pageemulateoptions). Actual list of -devices can be found in [src/deviceDescriptors.ts](https://github.com/Microsoft/playwright/blob/master/src/deviceDescriptors.ts). - -```js -const { webkit } = require('playwright'); -const iPhone = webkit.devices['iPhone 6']; - -(async () => { - const browser = await webkit.launch(); - const context = await browser.newContext({ - viewport: iPhone.viewport, - userAgent: iPhone.userAgent - }); - const page = await context.newPage('http://example.com'); - // other actions... - await browser.close(); -})(); -``` - -#### browserType.errors -- returns: <[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])](#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 [`browserType.errors`](#browsertypeerrors) or [`playwright.errors`](#playwrighterrors). - -An example of handling a timeout error: -```js -const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'. -try { - await page.waitForSelector('.foo'); -} catch (e) { - if (e instanceof webkit.errors.TimeoutError) { - // Do something if this is a timeout. - } -} -``` - -#### browserType.executablePath() -- returns: <[string]> A path where Playwright expects to find a bundled browser. - -#### browserType.launch([options]) -- `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields: - - `headless` <[boolean]> Whether to run browser in headless mode. More details for [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode). Defaults to `true` unless the `devtools` option is `true`. - - `executablePath` <[string]> Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). **BEWARE**: Playwright is only [guaranteed to work](https://github.com/Microsoft/playwright/#q-why-doesnt-playwright-vxxx-work-with-chromium-vyyy) with the bundled Chromium, Firefox or WebKit, use at your own risk. - - `slowMo` <[number]> Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. - - `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/). - - `ignoreDefaultArgs` <[boolean]|[Array]<[string]>> If `true`, then do not use [`browserType.defaultArgs()`](#browsertypedefaultargsoptions). If an array is given, then filter out the given default arguments. Dangerous option; use with care. Defaults to `false`. - - `handleSIGINT` <[boolean]> Close the browser process on Ctrl-C. Defaults to `true`. - - `handleSIGTERM` <[boolean]> Close the browser process on SIGTERM. Defaults to `true`. - - `handleSIGHUP` <[boolean]> Close the browser process on SIGHUP. Defaults to `true`. - - `timeout` <[number]> Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. - - `dumpio` <[boolean]> Whether to pipe the browser process stdout and stderr into `process.stdout` and `process.stderr`. Defaults to `false`. - - `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). - - `env` <[Object]> Specify environment variables that will be visible to the browser. Defaults to `process.env`. - - `webSocket` <[boolean]> Connects to the browser over a WebSocket instead of a pipe. 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`. -- returns: <[Promise]<[Browser]>> Promise which resolves to browser instance. - - -You can use `ignoreDefaultArgs` to filter out `--mute-audio` from default arguments: -```js -const browser = await chromium.launch({ // Or 'firefox' or 'webkit'. - ignoreDefaultArgs: ['--mute-audio'] -}); -``` - -> **Chromium-only** Playwright can also be used to control the Chrome browser, but it works best with the version of Chromium it is bundled with. There is no guarantee it will work with any other version. Use `executablePath` option with extreme caution. -> -> If Google Chrome (rather than Chromium) is preferred, a [Chrome Canary](https://www.google.com/chrome/browser/canary.html) or [Dev Channel](https://www.chromium.org/getting-involved/dev-channel) build is suggested. -> -> In [browserType.launch([options])](#browsertypelaunchoptions) above, any mention of Chromium also applies to Chrome. -> -> See [`this article`](https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/) for a description of the differences between Chromium and Chrome. [`This article`](https://chromium.googlesource.com/chromium/src/+/lkgr/docs/chromium_browser_vs_google_chrome.md) describes some differences for Linux users. - -#### browserType.launchBrowserApp([options]) -- `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields: - - `headless` <[boolean]> Whether to run browser in headless mode. More details for [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode). Defaults to `true` unless the `devtools` option is `true`. - - `executablePath` <[string]> Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). **BEWARE**: Playwright is only [guaranteed to work](https://github.com/Microsoft/playwright/#q-why-doesnt-playwright-vxxx-work-with-chromium-vyyy) with the bundled Chromium, Firefox or WebKit, use at your own risk. - - `slowMo` <[number]> Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. - - `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/). - - `ignoreDefaultArgs` <[boolean]|[Array]<[string]>> If `true`, then do not use [`browserType.defaultArgs()`](#browsertypedefaultargsoptions). If an array is given, then filter out the given default arguments. Dangerous option; use with care. Defaults to `false`. - - `handleSIGINT` <[boolean]> Close the browser process on Ctrl-C. Defaults to `true`. - - `handleSIGTERM` <[boolean]> Close the browser process on SIGTERM. Defaults to `true`. - - `handleSIGHUP` <[boolean]> Close the browser process on SIGHUP. Defaults to `true`. - - `timeout` <[number]> Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. - - `dumpio` <[boolean]> Whether to pipe the browser process stdout and stderr into `process.stdout` and `process.stderr`. Defaults to `false`. - - `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). - - `env` <[Object]> Specify environment variables that will be visible to the browser. Defaults to `process.env`. - - `webSocket` <[boolean]> Connects to the browser over a WebSocket instead of a pipe. 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`. -- returns: <[Promise]<[BrowserApp]>> Promise which resolves to the browser app instance. ### class: Browser @@ -370,46 +226,6 @@ Creates a new browser context. It won't share cookies/cache with other browser c })(); ``` -### class: BrowserApp - - -- [event: 'close'](#event-close) -- [browserApp.close()](#browserappclose) -- [browserApp.connectOptions()](#browserappconnectoptions) -- [browserApp.kill()](#browserappkill) -- [browserApp.process()](#browserappprocess) -- [browserApp.wsEndpoint()](#browserappwsendpoint) - - -#### event: 'close' - -Emitted when the browser app closes. - -#### browserApp.close() -- returns: <[Promise]> - -Closes the browser gracefully and makes sure the process is terminated. - -#### browserApp.connectOptions() -- returns: <[Object]> - - `browserWSEndpoint` [string]> a browser websocket endpoint to connect to. - - `slowMo` <[number]> - - `transport` <[ConnectionTransport]> **Experimental** A custom transport object which should be used to connect. - -This options object can be passed to [browserType.connect(options)](#browsertypeconnectoptions) to establish connection to the browser. - -#### browserApp.kill() - -Kills the browser process. - -#### browserApp.process() -- returns: [ChildProcess]> Spawned browser application process. - -#### browserApp.wsEndpoint() -- returns: [string]> Browser websocket url. - -Browser websocket endpoint which can be used as an argument to [browserType.connect(options)] to establish connection to the browser. - ### class: BrowserContext * extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter) @@ -557,1214 +373,6 @@ const context = browser.defaultContext(); await context.setPermissions('https://html5demos.com', ['geolocation']); ``` -### class: ConsoleMessage - -[ConsoleMessage] objects are dispatched by page via the ['console'](#event-console) event. - - -- [consoleMessage.args()](#consolemessageargs) -- [consoleMessage.location()](#consolemessagelocation) -- [consoleMessage.text()](#consolemessagetext) -- [consoleMessage.type()](#consolemessagetype) - - -#### consoleMessage.args() -- returns: <[Array]<[JSHandle]>> - -#### consoleMessage.location() -- returns: <[Object]> - - `url` <[string]> URL of the resource if known or `undefined` otherwise. - - `lineNumber` <[number]> 0-based line number in the resource if known or `undefined` otherwise. - - `columnNumber` <[number]> 0-based column number in the resource if known or `undefined` otherwise. - -#### 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'`. - -### class: Dialog - -[Dialog] objects are dispatched by page via the ['dialog'](#event-dialog) event. - -An example of using `Dialog` class: -```js -const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'. - -(async () => { - const browser = await chromium.launch(); - const context = await browser.newContext(); - const page = await context.newPage(); - page.on('dialog', async dialog => { - console.log(dialog.message()); - await dialog.dismiss(); - await browser.close(); - }); - page.evaluate(() => alert('1')); -})(); -``` - - -- [dialog.accept([promptText])](#dialogacceptprompttext) -- [dialog.defaultValue()](#dialogdefaultvalue) -- [dialog.dismiss()](#dialogdismiss) -- [dialog.message()](#dialogmessage) -- [dialog.type()](#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. -- returns: <[Promise]> Promise which resolves 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]> Promise which resolves when the dialog has been dismissed. - -#### dialog.message() -- returns: <[string]> A message displayed in the dialog. - -#### dialog.type() -- returns: <[string]> Dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`. - -### class: ElementHandle -* extends: [JSHandle] - -ElementHandle represents an in-page DOM element. ElementHandles can be created with the [page.$](#pageselector) method. - -```js -const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'. - -(async () => { - const browser = await chromium.launch(); - const context = await browser.newContext(); - const page = await context.newPage('https://example.com'); - const hrefElement = await page.$('a'); - await hrefElement.click(); - // ... -})(); -``` - -ElementHandle prevents DOM element from garbage collection unless the handle is [disposed](#elementhandledispose). ElementHandles are auto-disposed when their origin frame gets navigated. - -ElementHandle instances can be used as arguments in [`page.$eval()`](#pageevalselector-pagefunction-args) and [`page.evaluate()`](#pageevaluatepagefunction-args) methods. - - -- [elementHandle.$(selector)](#elementhandleselector) -- [elementHandle.$$(selector)](#elementhandleselector-1) -- [elementHandle.$$eval(selector, pageFunction[, ...args])](#elementhandleevalselector-pagefunction-args) -- [elementHandle.$eval(selector, pageFunction[, ...args])](#elementhandleevalselector-pagefunction-args-1) -- [elementHandle.boundingBox()](#elementhandleboundingbox) -- [elementHandle.click([options])](#elementhandleclickoptions) -- [elementHandle.contentFrame()](#elementhandlecontentframe) -- [elementHandle.dblclick([options])](#elementhandledblclickoptions) -- [elementHandle.fill(value)](#elementhandlefillvalue) -- [elementHandle.focus()](#elementhandlefocus) -- [elementHandle.hover([options])](#elementhandlehoveroptions) -- [elementHandle.ownerFrame()](#elementhandleownerframe) -- [elementHandle.press(key[, options])](#elementhandlepresskey-options) -- [elementHandle.screenshot([options])](#elementhandlescreenshotoptions) -- [elementHandle.scrollIntoViewIfNeeded()](#elementhandlescrollintoviewifneeded) -- [elementHandle.select(...values)](#elementhandleselectvalues) -- [elementHandle.setInputFiles(...files)](#elementhandlesetinputfilesfiles) -- [elementHandle.toString()](#elementhandletostring) -- [elementHandle.tripleclick([options])](#elementhandletripleclickoptions) -- [elementHandle.type(text[, options])](#elementhandletypetext-options) -- [elementHandle.visibleRatio()](#elementhandlevisibleratio) - - -- [jsHandle.asElement()](#jshandleaselement) -- [jsHandle.dispose()](#jshandledispose) -- [jsHandle.evaluate(pageFunction[, ...args])](#jshandleevaluatepagefunction-args) -- [jsHandle.evaluateHandle(pageFunction[, ...args])](#jshandleevaluatehandlepagefunction-args) -- [jsHandle.getProperties()](#jshandlegetproperties) -- [jsHandle.getProperty(propertyName)](#jshandlegetpropertypropertyname) -- [jsHandle.jsonValue()](#jshandlejsonvalue) - - -#### elementHandle.$(selector) -- `selector` <[string]> A selector to query element for -- returns: <[Promise][ElementHandle]>> - -The method runs `element.querySelector` within the page. If no element matches the selector, the return value resolves to `null`. - -#### elementHandle.$$(selector) -- `selector` <[string]> A selector to query element for -- returns: <[Promise]<[Array]<[ElementHandle]>>> - -The method runs `element.querySelectorAll` within the page. If no elements match the selector, the return value resolves to `[]`. - -#### elementHandle.$$eval(selector, pageFunction[, ...args]) -- `selector` <[string]> A selector to query page for -- `pageFunction` <[function]\([Array]<[Element]>\)> Function to be evaluated in browser context -- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction` -- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction` - -This method runs `document.querySelectorAll` within the element and passes it as the first argument to `pageFunction`. If there's no element matching `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: -```html -