# Playwright API Tip-Of-Tree ##### Table of Contents - [class: Playwright](#class-playwright) - [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: ChromiumPlaywright](#class-chromiumplaywright) - [class: ChromiumBrowser](#class-chromiumbrowser) - [class: ChromiumSession](#class-chromiumsession) - [class: ChromiumTarget](#class-chromiumtarget) - [class: FirefoxPlaywright](#class-firefoxplaywright) - [class: FirefoxBrowser](#class-firefoxbrowser) - [class: WebKitPlaywright](#class-webkitplaywright) - [class: WebKitBrowser](#class-webkitbrowser) - [Working with selectors](#working-with-selectors) - [Working with Chrome Extensions](#working-with-chrome-extensions) - [Downloaded browsers](#downloaded-browsers) ### 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 playwright = require('playwright').chromium; // Or 'firefox' or 'webkit'. (async () => { const browser = await playwright.launch(); const context = await browser.newContext(); const page = await context.newPage('http://example.com'); // other actions... await browser.close(); })(); ``` See [chromiumPlaywright.launch([options])](#chromiumplaywrightlaunchoptions), [firefoxPlaywright.launch([options])](#firefoxplaywrightlaunchoptions) or [webkitPlaywright.launch([options])](#webkitplaywrightlaunchoptions) for browser-specific launch methods. Playwright automatically downloads browser executables during installation, see [Downloaded browsers](#downloaded-browsers) for more information. - [playwright.devices](#playwrightdevices) - [playwright.errors](#playwrighterrors) - [playwright.executablePath()](#playwrightexecutablepath) #### 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 [lib/deviceDescriptors.js](https://github.com/Microsoft/playwright/blob/master/src/deviceDescriptors.ts). ```js const playwright = require('playwright').firefox; // Or 'chromium' or 'webkit'. const iPhone = playwright.devices['iPhone 6']; (async () => { const browser = await playwright.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 [`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.executablePath() - returns: <[string]> A path where Playwright expects to find bundled browser. ### 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 [`playwright.launch`](#playwrightlaunchoptions) or [`playwright.connect`](#playwrightconnectoptions). An example of using a [Browser] to create a [Page]: ```js const playwright = require('playwright').firefox; // Or 'chromium' or 'webkit'. (async () => { const browser = await playwright.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 playwright = require('playwright').webkit; // Or 'chromium' or 'firefox'. (async () => { const browserApp = await playwright.launchBrowserApp(); const connectOptions = browserApp.connectOptions(); // Use connect options later to establish a connection. const browser = await playwright.connect(connectOptions); // Close browser instance. await browserApp.close(); })(); ``` - [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 Playwright gets disconnected from the browser instance. This might happen because of one of the following: - Browser 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 Playwright from the browser, but leaves the browser 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` [boolean]> Whether to ignore HTTPS errors during navigation. Defaults to `false`. - `bypassCSP` [boolean]> Toggles bypassing page's Content-Security-Policy. - `viewport` [Object]> 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` [string]> Specific user agent to use in this page - `javaScriptEnabled` [boolean]> Whether or not to enable or disable JavaScript in the page. Defaults to true. - `timezoneId` [string]> 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.launch(); // 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 - [browserApp.close()](#browserappclose) - [browserApp.connectOptions()](#browserappconnectoptions) - [browserApp.process()](#browserappprocess) - [browserApp.wsEndpoint()](#browserappwsendpoint) #### 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](#browserwsendpoint) 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 [chromiumPlaywright.connect(options)](#chromiumplaywrightconnectoptions), [firefoxPlaywright.connect(options)](#firefoxplaywrightconnectoptions) or [webkitPlaywright.connect(options)](#webkitplaywrightconnectoptions) to establish connection to the browser. #### browserApp.process() - returns: [ChildProcess]> Spawned browser server process. #### browserApp.wsEndpoint() - returns: [string]> Browser websocket url. Browser websocket endpoint which can be used as an argument to [chromiumPlaywright.connect(options)](#chromiumplaywrightconnectoptions), [firefoxPlaywright.connect(options)](#firefoxplaywrightconnectoptions) or [webkitPlaywright.connect(options)](#webkitplaywrightconnectoptions) to establish connection to the browser. Learn more about [Chromium devtools protocol](https://chromedevtools.github.io/devtools-protocol) and the [browser endpoint](https://chromedevtools.github.io/devtools-protocol/#how-do-i-access-the-browser-target). ### 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` [string]> 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 playwright = require('playwright').chromium; // Or 'firefox' or 'webkit'. (async () => { const browser = await playwright.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 playwright = require('playwright').chromium; // Or 'firefox' or 'webkit'. (async () => { const browser = await playwright.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) #### 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