# Playwright API v0.9.22 ##### Table of Contents - [Playwright module](#playwright-module) - [class: BrowserType](#class-browsertype) - [class: Browser](#class-browser) - [class: BrowserApp](#class-browserapp) - [class: BrowserContext](#class-browsercontext) - [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) - [class: TimeoutError](#class-timeouterror) - [class: Accessibility](#class-accessibility) - [class: Coverage](#class-coverage) - [class: Worker](#class-worker) - [class: ChromiumBrowser](#class-chromiumbrowser) - [class: ChromiumSession](#class-chromiumsession) - [class: ChromiumTarget](#class-chromiumtarget) - [class: FirefoxBrowser](#class-firefoxbrowser) - [class: WebKitBrowser](#class-webkitbrowser) - [Working with selectors](#working-with-selectors) - [Working with Chrome Extensions](#working-with-chrome-extensions) ### Playwright module 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 context = await browser.newContext(); const page = await context.newPage('http://example.com'); // other actions... await browser.close(); })(); ``` Playwright automatically downloads browser executables during installation, see [Downloaded browsers](#downloaded-browsers) for more information. - [playwright.chromium](#playwrightchromium) - [playwright.devices](#playwrightdevices) - [playwright.errors](#playwrighterrors) - [playwright.firefox](#playwrightfirefox) - [playwright.webkit](#playwrightwebkit) #### playwright.chromium - returns: <[BrowserType]> This object can be used to launch or connect to Chromium, returning instances of [ChromiumBrowser]. #### playwright.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, devices } = require('playwright'); const iPhone = 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(); })(); ``` #### playwright.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 try { await page.waitForSelector('.foo'); } catch (e) { if (e instanceof playwright.errors.TimeoutError) { // Do something if this is a timeout. } } ``` #### playwright.firefox - returns: <[BrowserType]> This object can be used to launch or connect to Firefox, returning instances of [FirefoxBrowser]. #### playwright.webkit - returns: <[BrowserType]> 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` 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` **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 * 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`](#browsertypelaunchoptions) or [`browserType.connect`](#browsertypeconnectoptions). 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 context = await browser.newContext(); const page = await context.newPage('https://example.com'); await browser.close(); })(); ``` An example of launching a browser executable and connecting to a [Browser] later: ```js const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'. (async () => { const browserApp = await webkit.launchBrowserApp({ webSocket: true }); const connectOptions = browserApp.connectOptions(); // Use connect options later to establish a connection. const browser = await webkit.connect(connectOptions); // Close browser instance. await browserApp.close(); })(); ``` See [ChromiumBrowser], [FirefoxBrowser] and [WebKitBrowser] for browser-specific features. Note that [browserType.connect(options)](#browsertypeconnectoptions) and [browserType.launch(options)](#browsertypelaunchoptions) always return a specific browser instance, based on the browser being connected to or launched. - [event: 'disconnected'](#event-disconnected) - [browser.browserContexts()](#browserbrowsercontexts) - [browser.close()](#browserclose) - [browser.defaultContext()](#browserdefaultcontext) - [browser.disconnect()](#browserdisconnect) - [browser.isConnected()](#browserisconnected) - [browser.newContext(options)](#browsernewcontextoptions) #### event: '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.disconnect`](#browserdisconnect) method was called. #### browser.browserContexts() - returns: <[Array]<[BrowserContext]>> Returns an array of all open browser contexts. In a newly created browser, this will return a single instance of [BrowserContext]. #### browser.close() - returns: <[Promise]> Closes browser and all of its pages (if any were opened). The [Browser] object itself is considered to be disposed and cannot be used anymore. #### browser.defaultContext() - returns: <[BrowserContext]> Returns the default browser context. The default browser context can not be closed. #### browser.disconnect() - returns: <[Promise]> Disconnects Browser from the browser application, but leaves the application process running. After calling `disconnect`, the [Browser] object is considered disposed and cannot be used anymore. #### browser.isConnected() - returns: <[boolean]> Indicates that the browser is connected. #### browser.newContext(options) - `options` <[Object]> - `ignoreHTTPSErrors` Whether to ignore HTTPS errors during navigation. Defaults to `false`. - `bypassCSP` Toggles bypassing page's Content-Security-Policy. - `viewport` Sets a consistent viewport for each page. Defaults to an 800x600 viewport. `null` disables the default viewport. - `width` <[number]> page width in pixels. - `height` <[number]> page height in pixels. - `deviceScaleFactor` <[number]> Specify device scale factor (can be thought of as dpr). Defaults to `1`. - `isMobile` <[boolean]> Whether the `meta viewport` tag is taken into account. Defaults to `false`. - `userAgent` Specific user agent to use in this page - `javaScriptEnabled` Whether or not to enable or disable JavaScript in the page. Defaults to true. - `timezoneId` Changes the timezone of the page. 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. - `geolocation` <[Object]> - `latitude` <[number]> Latitude between -90 and 90. - `longitude` <[number]> Longitude between -180 and 180. - `accuracy` <[number]> Optional non-negative accuracy value. - `permissions` <[Object]> A map from origin keys to permissions values. See [browserContext.setPermissions]((#browsercontextsetpermissionsorigin-permissions)) for more details. - 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('https://example.com'); })(); ``` ### 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` 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: Spawned browser application process. #### browserApp.wsEndpoint() - returns: 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) 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('https://example.com'); // Dispose context once it's no longer needed. await context.close(); ``` - [browserContext.clearCookies()](#browsercontextclearcookies) - [browserContext.clearPermissions()](#browsercontextclearpermissions) - [browserContext.close()](#browsercontextclose) - [browserContext.cookies([...urls])](#browsercontextcookiesurls) - [browserContext.newPage(url)](#browsercontextnewpageurl) - [browserContext.pages()](#browsercontextpages) - [browserContext.setCookies(cookies)](#browsercontextsetcookiescookies) - [browserContext.setGeolocation(geolocation)](#browsercontextsetgeolocationgeolocation) - [browserContext.setPermissions(origin, permissions[])](#browsercontextsetpermissionsorigin-permissions) #### browserContext.clearCookies() - returns: <[Promise]> Clears context bookies. #### browserContext.clearPermissions() - returns: <[Promise]> Clears all permission overrides for the browser context. ```js const context = browser.defaultContext(); context.setPermissions('https://example.com', ['clipboard-read']); // do stuff .. context.clearPermissions(); ``` #### browserContext.close() - returns: <[Promise]> Closes the browser context. All the targets that belong to the browser context will be closed. > **NOTE** only incognito browser contexts can be closed. #### browserContext.cookies([...urls]) - `...urls` <...[string]> - returns: <[Promise]<[Array]<[Object]>>> - `name` <[string]> - `value` <[string]> - `domain` <[string]> - `path` <[string]> - `expires` <[number]> Unix time in seconds. - `size` <[number]> - `httpOnly` <[boolean]> - `secure` <[boolean]> - `session` <[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. > **NOTE** the default browser context cannot be closed. #### browserContext.newPage(url) - `url` Optional url to navigate the page to. - returns: <[Promise]<[Page]>> Creates a new page in the browser context and optionally navigates it to the specified URL. #### browserContext.pages() - returns: <[Promise]<[Array]<[Page]>>> Promise which resolves to an array of all open pages. Non visible pages, such as `"background_page"`, will not be listed here. You can find them using [target.page()](#targetpage). An array of all pages inside the browser context. #### browserContext.setCookies(cookies) - `cookies` <[Array]<[Object]>> - `name` <[string]> **required** - `value` <[string]> **required** - `url` <[string]> either url or domain / path are **required** - `domain` <[string]> either url or domain / path are **required** - `path` <[string]> either url or domain / path are **required** - `expires` <[number]> Unix time in seconds. - `httpOnly` <[boolean]> - `secure` <[boolean]> - `sameSite` <"Strict"|"Lax"|"None"> - returns: <[Promise]> ```js await browserContext.setCookies([cookieObject1, cookieObject2]); ``` #### browserContext.setGeolocation(geolocation) - `geolocation` <[Object]> - `latitude` <[number]> Latitude between -90 and 90. - `longitude` <[number]> Longitude between -180 and 180. - `accuracy` <[number]> Optional non-negative accuracy value. - returns: <[Promise]> Sets the page's geolocation. Passing null or undefined emulates position unavailable. ```js await browserContext.setGeolocation({latitude: 59.95, longitude: 30.31667}); ``` > **NOTE** Consider using [browserContext.setPermissions](#browsercontextsetpermissions-permissions) to grant permissions for the page to read its geolocation. #### browserContext.setPermissions(origin, permissions[]) - `origin` <[string]> The [origin] to grant permissions to, e.g. "https://example.com". - `permissions` <[Array]<[string]>> An array of permissions to grant. All permissions that are not listed here will be automatically denied. 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'` - returns: <[Promise]> ```js 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]> 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
Hello!
Hi!
``` ```js const feedHandle = await page.$('.feed'); expect(await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText))).toEqual(['Hello!', 'Hi!']); ``` #### elementHandle.$eval(selector, pageFunction[, ...args]) - `selector` <[string]> A selector to query page for - `pageFunction` <[function]\([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.querySelector` 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: ```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.boundingBox() - returns: <[Promise]> - 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 (relative to the main frame), or `null` if the element is not visible. #### 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. - `relativePoint` <[Object]> A point to click relative to the top-left corner of element padding box. If not specified, clicks to some visible point of the element. - x <[number]> - y <[number]> - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the click, and then restores current modifiers back. If not specified, currently pressed modifiers are used. - returns: <[Promise]> Promise which resolves when the element is successfully clicked. Promise gets rejected if the element is detached from DOM. This method scrolls element into view if needed, and then uses [page.mouse](#pagemouse) to click in the center of the element. If the element is detached from DOM, the method throws an error. #### elementHandle.contentFrame() - returns: <[Promise]> Resolves to 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. - `relativePoint` <[Object]> A point to double click relative to the top-left corner of element padding box. If not specified, double clicks to some visible point of the element. - x <[number]> - y <[number]> - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the double click, and then restores current modifiers back. If not specified, currently pressed modifiers are used. - returns: <[Promise]> Promise which resolves when the element is successfully double clicked. Promise gets rejected if the element is detached from DOM. This method scrolls element into view if needed, and then uses [page.mouse](#pagemouse) to click in the center of the element. If the element is detached from DOM, the method throws an error. Bear in mind that if the first click of the `dblclick()` triggers a navigation event, there will be an exception. > **NOTE** `elementHandle.dblclick()` dispatches two `click` events and a single `dblclick` event. #### elementHandle.fill(value) - `value` <[string]> Value to set for the ``, `