# Playwright API Tip-Of-Tree ##### Table of Contents - [class: Playwright](#class-playwright) * [playwright.createBrowserFetcher([options])](#playwrightcreatebrowserfetcheroptions) * [playwright.devices](#playwrightdevices) * [playwright.errors](#playwrighterrors) * [playwright.executablePath()](#playwrightexecutablepath) - [class: Browser](#class-browser) * [event: 'disconnected'](#event-disconnected) * [browser.browserContexts()](#browserbrowsercontexts) * [browser.close()](#browserclose) * [browser.defaultContext()](#browserdefaultcontext) * [browser.disconnect()](#browserdisconnect) * [browser.isConnected()](#browserisconnected) * [browser.newContext(options)](#browsernewcontextoptions) - [class: BrowserContext](#class-browsercontext) * [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) - [class: BrowserFetcher](#class-browserfetcher) * [browserFetcher.canDownload([revision])](#browserfetchercandownloadrevision) * [browserFetcher.download([revision, progressCallback])](#browserfetcherdownloadrevision-progresscallback) * [browserFetcher.localRevisions()](#browserfetcherlocalrevisions) * [browserFetcher.remove([revision])](#browserfetcherremoverevision) * [browserFetcher.revisionInfo([revision])](#browserfetcherrevisioninforevision) - [class: ConsoleMessage](#class-consolemessage) * [consoleMessage.args()](#consolemessageargs) * [consoleMessage.location()](#consolemessagelocation) * [consoleMessage.text()](#consolemessagetext) * [consoleMessage.type()](#consolemessagetype) - [class: Dialog](#class-dialog) * [dialog.accept([promptText])](#dialogacceptprompttext) * [dialog.defaultValue()](#dialogdefaultvalue) * [dialog.dismiss()](#dialogdismiss) * [dialog.message()](#dialogmessage) * [dialog.type()](#dialogtype) - [class: ElementHandle](#class-elementhandle) * [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.$x(expression)](#elementhandlexexpression) * [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) - [class: Frame](#class-frame) * [frame.$(selector)](#frameselector) * [frame.$$(selector)](#frameselector-1) * [frame.$$eval(selector, pageFunction[, ...args])](#frameevalselector-pagefunction-args) * [frame.$eval(selector, pageFunction[, ...args])](#frameevalselector-pagefunction-args-1) * [frame.$wait(selector, pageFunction[, options[, ...args]])](#framewaitselector-pagefunction-options-args) * [frame.$x(expression)](#framexexpression) * [frame.addScriptTag(options)](#frameaddscripttagoptions) * [frame.addStyleTag(options)](#frameaddstyletagoptions) * [frame.childFrames()](#framechildframes) * [frame.click(selector[, options])](#frameclickselector-options) * [frame.content()](#framecontent) * [frame.dblclick(selector[, options])](#framedblclickselector-options) * [frame.evaluate(pageFunction[, ...args])](#frameevaluatepagefunction-args) * [frame.evaluateHandle(pageFunction[, ...args])](#frameevaluatehandlepagefunction-args) * [frame.fill(selector, value, options)](#framefillselector-value-options) * [frame.focus(selector, options)](#framefocusselector-options) * [frame.goto(url[, options])](#framegotourl-options) * [frame.hover(selector[, options])](#framehoverselector-options) * [frame.isDetached()](#frameisdetached) * [frame.name()](#framename) * [frame.parentFrame()](#frameparentframe) * [frame.select(selector, value, options)](#frameselectselector-value-options) * [frame.setContent(html[, options])](#framesetcontenthtml-options) * [frame.title()](#frametitle) * [frame.tripleclick(selector[, options])](#frametripleclickselector-options) * [frame.type(selector, text[, options])](#frametypeselector-text-options) * [frame.url()](#frameurl) * [frame.waitFor(selectorOrFunctionOrTimeout[, options[, ...args]])](#framewaitforselectororfunctionortimeout-options-args) * [frame.waitForFunction(pageFunction[, options[, ...args]])](#framewaitforfunctionpagefunction-options-args) * [frame.waitForLoadState([options])](#framewaitforloadstateoptions) * [frame.waitForNavigation([options])](#framewaitfornavigationoptions) * [frame.waitForSelector(selector[, options])](#framewaitforselectorselector-options) - [class: JSHandle](#class-jshandle) * [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) - [class: Keyboard](#class-keyboard) * [keyboard.down(key[, options])](#keyboarddownkey-options) * [keyboard.press(key[, options])](#keyboardpresskey-options) * [keyboard.sendCharacters(text)](#keyboardsendcharacterstext) * [keyboard.type(text[, options])](#keyboardtypetext-options) * [keyboard.up(key)](#keyboardupkey) - [class: Mouse](#class-mouse) * [mouse.click(x, y[, options])](#mouseclickx-y-options) * [mouse.dblclick(x, y[, options])](#mousedblclickx-y-options) * [mouse.down([options])](#mousedownoptions) * [mouse.move(x, y[, options])](#mousemovex-y-options) * [mouse.tripleclick(x, y[, options])](#mousetripleclickx-y-options) * [mouse.up([options])](#mouseupoptions) - [class: Page](#class-page) * [event: 'close'](#event-close) * [event: 'console'](#event-console) * [event: 'dialog'](#event-dialog) * [event: 'domcontentloaded'](#event-domcontentloaded) * [event: 'filechooser'](#event-filechooser) * [event: 'frameattached'](#event-frameattached) * [event: 'framedetached'](#event-framedetached) * [event: 'framenavigated'](#event-framenavigated) * [event: 'load'](#event-load) * [event: 'pageerror'](#event-pageerror) * [event: 'popup'](#event-popup) * [event: 'request'](#event-request) * [event: 'requestfailed'](#event-requestfailed) * [event: 'requestfinished'](#event-requestfinished) * [event: 'response'](#event-response) * [event: 'workercreated'](#event-workercreated) * [event: 'workerdestroyed'](#event-workerdestroyed) * [page.$(selector)](#pageselector) * [page.$$(selector)](#pageselector-1) * [page.$$eval(selector, pageFunction[, ...args])](#pageevalselector-pagefunction-args) * [page.$eval(selector, pageFunction[, ...args])](#pageevalselector-pagefunction-args-1) * [page.$wait(selector, pageFunction[, options[, ...args]])](#pagewaitselector-pagefunction-options-args) * [page.$x(expression)](#pagexexpression) * [page.accessibility](#pageaccessibility) * [page.addScriptTag(options)](#pageaddscripttagoptions) * [page.addStyleTag(options)](#pageaddstyletagoptions) * [page.authenticate(credentials)](#pageauthenticatecredentials) * [page.browserContext()](#pagebrowsercontext) * [page.click(selector[, options])](#pageclickselector-options) * [page.close([options])](#pagecloseoptions) * [page.content()](#pagecontent) * [page.coverage](#pagecoverage) * [page.dblclick(selector[, options])](#pagedblclickselector-options) * [page.emulateMedia(options)](#pageemulatemediaoptions) * [page.evaluate(pageFunction[, ...args])](#pageevaluatepagefunction-args) * [page.evaluateHandle(pageFunction[, ...args])](#pageevaluatehandlepagefunction-args) * [page.evaluateOnNewDocument(pageFunction[, ...args])](#pageevaluateonnewdocumentpagefunction-args) * [page.exposeFunction(name, playwrightFunction)](#pageexposefunctionname-playwrightfunction) * [page.fill(selector, value, options)](#pagefillselector-value-options) * [page.focus(selector, options)](#pagefocusselector-options) * [page.frames()](#pageframes) * [page.goBack([options])](#pagegobackoptions) * [page.goForward([options])](#pagegoforwardoptions) * [page.goto(url[, options])](#pagegotourl-options) * [page.hover(selector[, options])](#pagehoverselector-options) * [page.isClosed()](#pageisclosed) * [page.keyboard](#pagekeyboard) * [page.mainFrame()](#pagemainframe) * [page.mouse](#pagemouse) * [page.pdf([options])](#pagepdfoptions) * [page.reload([options])](#pagereloadoptions) * [page.screenshot([options])](#pagescreenshotoptions) * [page.select(selector, value, options)](#pageselectselector-value-options) * [page.setCacheEnabled([enabled])](#pagesetcacheenabledenabled) * [page.setContent(html[, options])](#pagesetcontenthtml-options) * [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) * [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) * [page.setExtraHTTPHeaders(headers)](#pagesetextrahttpheadersheaders) * [page.setOfflineMode(enabled)](#pagesetofflinemodeenabled) * [page.setRequestInterception(enabled)](#pagesetrequestinterceptionenabled) * [page.setViewport(viewport)](#pagesetviewportviewport) * [page.title()](#pagetitle) * [page.tripleclick(selector[, options])](#pagetripleclickselector-options) * [page.type(selector, text[, options])](#pagetypeselector-text-options) * [page.url()](#pageurl) * [page.viewport()](#pageviewport) * [page.waitFor(selectorOrFunctionOrTimeout[, options[, ...args]])](#pagewaitforselectororfunctionortimeout-options-args) * [page.waitForEvent(event[, optionsOrPredicate])](#pagewaitforeventevent-optionsorpredicate) * [page.waitForFunction(pageFunction[, options[, ...args]])](#pagewaitforfunctionpagefunction-options-args) * [page.waitForLoadState([options])](#pagewaitforloadstateoptions) * [page.waitForNavigation([options])](#pagewaitfornavigationoptions) * [page.waitForRequest(urlOrPredicate[, options])](#pagewaitforrequesturlorpredicate-options) * [page.waitForResponse(urlOrPredicate[, options])](#pagewaitforresponseurlorpredicate-options) * [page.waitForSelector(selector[, options])](#pagewaitforselectorselector-options) * [page.workers()](#pageworkers) - [class: Request](#class-request) * [request.abort([errorCode])](#requestaborterrorcode) * [request.continue([overrides])](#requestcontinueoverrides) * [request.failure()](#requestfailure) * [request.frame()](#requestframe) * [request.fulfill(response)](#requestfulfillresponse) * [request.headers()](#requestheaders) * [request.isNavigationRequest()](#requestisnavigationrequest) * [request.method()](#requestmethod) * [request.postData()](#requestpostdata) * [request.redirectChain()](#requestredirectchain) * [request.resourceType()](#requestresourcetype) * [request.response()](#requestresponse) * [request.url()](#requesturl) - [class: Response](#class-response) * [response.buffer()](#responsebuffer) * [response.frame()](#responseframe) * [response.headers()](#responseheaders) * [response.json()](#responsejson) * [response.ok()](#responseok) * [response.remoteAddress()](#responseremoteaddress) * [response.request()](#responserequest) * [response.status()](#responsestatus) * [response.statusText()](#responsestatustext) * [response.text()](#responsetext) * [response.url()](#responseurl) - [class: TimeoutError](#class-timeouterror) - [class: Accessibility](#class-accessibility) * [accessibility.snapshot([options])](#accessibilitysnapshotoptions) - [class: Coverage](#class-coverage) * [coverage.startCSSCoverage([options])](#coveragestartcsscoverageoptions) * [coverage.startJSCoverage([options])](#coveragestartjscoverageoptions) * [coverage.stopCSSCoverage()](#coveragestopcsscoverage) * [coverage.stopJSCoverage()](#coveragestopjscoverage) - [class: Worker](#class-worker) * [worker.evaluate(pageFunction[, ...args])](#workerevaluatepagefunction-args) * [worker.evaluateHandle(pageFunction[, ...args])](#workerevaluatehandlepagefunction-args) * [worker.url()](#workerurl) - [class: ChromiumPlaywright](#class-chromiumplaywright) * [chromiumPlaywright.connect(options)](#chromiumplaywrightconnectoptions) * [chromiumPlaywright.defaultArgs([options])](#chromiumplaywrightdefaultargsoptions) * [chromiumPlaywright.launch([options])](#chromiumplaywrightlaunchoptions) * [chromiumPlaywright.launchServer([options])](#chromiumplaywrightlaunchserveroptions) - [class: ChromiumBrowser](#class-chromiumbrowser) * [event: 'targetchanged'](#event-targetchanged) * [event: 'targetcreated'](#event-targetcreated) * [event: 'targetdestroyed'](#event-targetdestroyed) * [chromiumBrowser.browserTarget()](#chromiumbrowserbrowsertarget) * [chromiumBrowser.pageTarget(page)](#chromiumbrowserpagetargetpage) * [chromiumBrowser.serviceWorker(target)](#chromiumbrowserserviceworkertarget) * [chromiumBrowser.startTracing(page, [options])](#chromiumbrowserstarttracingpage-options) * [chromiumBrowser.stopTracing()](#chromiumbrowserstoptracing) * [chromiumBrowser.targets(context)](#chromiumbrowsertargetscontext) * [chromiumBrowser.waitForTarget(predicate[, options])](#chromiumbrowserwaitfortargetpredicate-options) - [class: ChromiumBrowserServer](#class-chromiumbrowserserver) * [chromiumBrowserServer.close()](#chromiumbrowserserverclose) * [chromiumBrowserServer.connect()](#chromiumbrowserserverconnect) * [chromiumBrowserServer.connectOptions()](#chromiumbrowserserverconnectoptions) * [chromiumBrowserServer.process()](#chromiumbrowserserverprocess) * [chromiumBrowserServer.wsEndpoint()](#chromiumbrowserserverwsendpoint) - [class: ChromiumSession](#class-chromiumsession) * [chromiumSession.detach()](#chromiumsessiondetach) * [chromiumSession.send(method[, params])](#chromiumsessionsendmethod-params) - [class: ChromiumTarget](#class-chromiumtarget) * [chromiumTarget.browserContext()](#chromiumtargetbrowsercontext) * [chromiumTarget.createCDPSession()](#chromiumtargetcreatecdpsession) * [chromiumTarget.opener()](#chromiumtargetopener) * [chromiumTarget.page()](#chromiumtargetpage) * [chromiumTarget.type()](#chromiumtargettype) * [chromiumTarget.url()](#chromiumtargeturl) - [class: FirefoxPlaywright](#class-firefoxplaywright) * [firefoxPlaywright.connect(options)](#firefoxplaywrightconnectoptions) * [firefoxPlaywright.defaultArgs([options])](#firefoxplaywrightdefaultargsoptions) * [firefoxPlaywright.launch([options])](#firefoxplaywrightlaunchoptions) * [firefoxPlaywright.launchServer([options])](#firefoxplaywrightlaunchserveroptions) - [class: FirefoxBrowser](#class-firefoxbrowser) - [class: FirefoxBrowserServer](#class-firefoxbrowserserver) * [firefoxBrowserServer.close()](#firefoxbrowserserverclose) * [firefoxBrowserServer.connect()](#firefoxbrowserserverconnect) * [firefoxBrowserServer.connectOptions()](#firefoxbrowserserverconnectoptions) * [firefoxBrowserServer.process()](#firefoxbrowserserverprocess) * [firefoxBrowserServer.wsEndpoint()](#firefoxbrowserserverwsendpoint) - [class: WebKitPlaywright](#class-webkitplaywright) * [webkitPlaywright.defaultArgs([options])](#webkitplaywrightdefaultargsoptions) * [webkitPlaywright.launch([options])](#webkitplaywrightlaunchoptions) * [webkitPlaywright.launchServer([options])](#webkitplaywrightlaunchserveroptions) - [class: WebKitBrowser](#class-webkitbrowser) - [class: WebKitBrowserServer](#class-webkitbrowserserver) * [webKitBrowserServer.close()](#webkitbrowserserverclose) * [webKitBrowserServer.connect()](#webkitbrowserserverconnect) * [webKitBrowserServer.connectOptions()](#webkitbrowserserverconnectoptions) * [webKitBrowserServer.process()](#webkitbrowserserverprocess) - [Working with selectors](#working-with-selectors) - [Working with Chrome Extensions](#working-with-chrome-extensions) - [Download defaults](#download-defaults) ### 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.createBrowserFetcher([options]) - `options` <[Object]> - `host` <[string]> A download host to be used. - `path` <[string]> A path for the downloads folder. - `platform` <[string]> Defaults to the current platform. - returns: <[BrowserFetcher]> See [Download defaults](#download-defaults) for default values. #### 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'); (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 disconnecting from and reconnecting to a [Browser]: ```js const playwright = require('playwright'); (async () => { const browserServer = await playwright.launchServer(); const browserWSEndpoint = browserServer.wsEndpoint(); // Use the endpoint to establish a connection const browser = await playwright.connect({browserWSEndpoint}); // Close Chromium await browser.close(); })(); ``` #### 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() 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` 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.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: 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() - 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: BrowserFetcher BrowserFetcher can download and manage different versions of Chromium/Firefox/WebKit. BrowserFetcher operates on revision strings that specify a precise version of the browser, e.g. `"533271"`. Chromium revision strings can be obtained from [omahaproxy.appspot.com](http://omahaproxy.appspot.com/). An example of using BrowserFetcher to download a specific version of Chromium and running Playwright against it: ```js const browserFetcher = playwright.createBrowserFetcher(); const revisionInfo = await browserFetcher.download('533271'); const browser = await playwright.launch({executablePath: revisionInfo.executablePath}); ``` > **NOTE** BrowserFetcher is not designed to work concurrently with other > instances of BrowserFetcher that share the same downloads directory. #### browserFetcher.canDownload([revision]) - `revision` <[string]> a revision to check availability. Defaults to preferred revision. - returns: <[Promise]<[boolean]>> returns `true` if the revision could be downloaded from the host. The method initiates a HEAD request to check if the revision is available. #### browserFetcher.download([revision, progressCallback]) - `revision` <[string]> a revision to download. Defaults to preferred revision. - `progressCallback` <[function]([number], [number])> A function that will be called with two arguments: - `downloadedBytes` <[number]> how many bytes have been downloaded - `totalBytes` <[number]> how large is the total download. - returns: <[Promise]<[Object]>> Resolves with revision information when the revision is downloaded and extracted - `revision` <[string]> the revision the info was created from - `folderPath` <[string]> path to the extracted revision folder - `executablePath` <[string]> path to the revision executable - `url` <[string]> URL this revision can be downloaded from - `local` <[boolean]> whether the revision is locally available on disk The method initiates a GET request to download the revision from the host. See [Download defaults](#download-defaults) for approximate download size. #### browserFetcher.localRevisions() - returns: <[Promise]<[Array]<[string]>>> A list of all revisions available locally on disk. #### browserFetcher.remove([revision]) - `revision` <[string]> a revision to remove. Defaults to preferred revision. The method will throw if the revision has not been downloaded. - returns: <[Promise]> Resolves when the revision has been removed. #### browserFetcher.revisionInfo([revision]) - `revision` <[string]> a revision to get info for. Defaults to preferred revision. - returns: <[Object]> - `revision` <[string]> the revision the info was created from - `folderPath` <[string]> path to the extracted revision folder - `executablePath` <[string]> path to the revision executable - `url` <[string]> URL this revision can be downloaded from - `local` <[boolean]> whether the revision is locally available on disk ### class: ConsoleMessage [ConsoleMessage] objects are dispatched by page via the ['console'](#event-console) event. #### 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'); (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]) - `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'); (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) - `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.$x(expression) - `expression` <[string]> Expression to [evaluate](https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate). - returns: <[Promise]<[Array]<[ElementHandle]>>> The method evaluates the XPath expression relative to the elementHandle. If there are no such elements, the method will resolve to an empty array. #### 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 ``, `