From f82039495c42d55224a6b5457313ba1e639f1c10 Mon Sep 17 00:00:00 2001 From: Pavel Feldman Date: Fri, 20 Dec 2019 20:48:33 -0800 Subject: [PATCH] docs: sort classes alphabetically --- docs/api.md | 3954 +++++++++++++++++++++++++-------------------------- 1 file changed, 1965 insertions(+), 1989 deletions(-) diff --git a/docs/api.md b/docs/api.md index b4345de13e..7beac87720 100644 --- a/docs/api.md +++ b/docs/api.md @@ -2,24 +2,9 @@ # Playwright API Tip-Of-Tree -- API Translations: [中文|Chinese](https://zhaoqize.github.io/playwright-api-zh_CN/#/) -- Troubleshooting: [troubleshooting.md](https://github.com/Microsoft/playwright/blob/master/docs/troubleshooting.md) - - ##### Table of Contents -- [Overview](#overview) -- [class: ChromiumPlaywright](#class-chromiumplaywright) - * [chromiumPlaywright.connect(options)](#chromiumplaywrightconnectoptions) - * [chromiumPlaywright.createBrowserFetcher([options])](#chromiumplaywrightcreatebrowserfetcheroptions) - * [chromiumPlaywright.defaultArgs([options])](#chromiumplaywrightdefaultargsoptions) - * [chromiumPlaywright.devices](#chromiumplaywrightdevices) - * [chromiumPlaywright.downloadBrowser([options])](#chromiumplaywrightdownloadbrowseroptions) - * [chromiumPlaywright.errors](#chromiumplaywrighterrors) - * [chromiumPlaywright.executablePath()](#chromiumplaywrightexecutablepath) - * [chromiumPlaywright.launch([options])](#chromiumplaywrightlaunchoptions) - * [chromiumPlaywright.launchServer([options])](#chromiumplaywrightlaunchserveroptions) - [class: Browser](#class-browser) * [event: 'disconnected'](#event-disconnected) * [browser.browserContexts()](#browserbrowsercontexts) @@ -28,6 +13,15 @@ * [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()](#browsercontextnewpage) + * [browserContext.pages()](#browsercontextpages) + * [browserContext.setCookies(cookies)](#browsercontextsetcookiescookies) + * [browserContext.setPermissions(origin, permissions[])](#browsercontextsetpermissionsorigin-permissions) - [class: BrowserFetcher](#class-browserfetcher) * [browserFetcher.canDownload(revision)](#browserfetchercandownloadrevision) * [browserFetcher.download(revision[, progressCallback])](#browserfetcherdownloadrevision-progresscallback) @@ -39,28 +33,93 @@ * [browserServer.connect()](#browserserverconnect) * [browserServer.process()](#browserserverprocess) * [browserServer.wsEndpoint()](#browserserverwsendpoint) -- [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: BrowserContext](#class-browsercontext) - * [browserContext.clearCookies()](#browsercontextclearcookies) - * [browserContext.clearPermissions()](#browsercontextclearpermissions) - * [browserContext.close()](#browsercontextclose) - * [browserContext.cookies([...urls])](#browsercontextcookiesurls) - * [browserContext.newPage()](#browsercontextnewpage) - * [browserContext.pages()](#browsercontextpages) - * [browserContext.setCookies(cookies)](#browsercontextsetcookiescookies) - * [browserContext.setPermissions(origin, permissions[])](#browsercontextsetpermissionsorigin-permissions) -- [class: ChromiumOverrides](#class-chromiumoverrides) - * [chromiumOverrides.setGeolocation(options)](#chromiumoverridessetgeolocationoptions) +- [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.isIntersectingViewport()](#elementhandleisintersectingviewport) + * [elementHandle.ownerFrame()](#elementhandleownerframe) + * [elementHandle.press(key[, options])](#elementhandlepresskey-options) + * [elementHandle.screenshot([options])](#elementhandlescreenshotoptions) + * [elementHandle.select(...values)](#elementhandleselectvalues) + * [elementHandle.setInputFiles(...files)](#elementhandlesetinputfilesfiles) + * [elementHandle.toString()](#elementhandletostring) + * [elementHandle.tripleclick([options])](#elementhandletripleclickoptions) + * [elementHandle.type(text[, options])](#elementhandletypetext-options) +- [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) @@ -133,115 +192,6 @@ * [page.waitForResponse(urlOrPredicate[, options])](#pagewaitforresponseurlorpredicate-options) * [page.waitForSelector(selector[, options])](#pagewaitforselectorselector-options) * [page.workers](#pageworkers) -- [class: ChromiumWorker](#class-chromiumworker) - * [chromiumWorker.evaluate(pageFunction[, ...args])](#chromiumworkerevaluatepagefunction-args) - * [chromiumWorker.evaluateHandle(pageFunction[, ...args])](#chromiumworkerevaluatehandlepagefunction-args) - * [chromiumWorker.url()](#chromiumworkerurl) -- [class: ChromiumWorkers](#class-chromiumworkers) - * [event: 'workercreated'](#event-workercreated) - * [event: 'workerdestroyed'](#event-workerdestroyed) - * [chromiumWorkers.list()](#chromiumworkerslist) -- [class: ChromiumAccessibility](#class-chromiumaccessibility) - * [chromiumAccessibility.snapshot([options])](#chromiumaccessibilitysnapshotoptions) -- [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: ChromiumPDF](#class-chromiumpdf) - * [chromiumPDF.generate([options])](#chromiumpdfgenerateoptions) -- [class: FirefoxBrowser](#class-firefoxbrowser) -- [class: WebKitBrowser](#class-webkitbrowser) -- [class: Dialog](#class-dialog) - * [dialog.accept([promptText])](#dialogacceptprompttext) - * [dialog.defaultValue()](#dialogdefaultvalue) - * [dialog.dismiss()](#dialogdismiss) - * [dialog.message()](#dialogmessage) - * [dialog.type()](#dialogtype) -- [class: ConsoleMessage](#class-consolemessage) - * [consoleMessage.args()](#consolemessageargs) - * [consoleMessage.location()](#consolemessagelocation) - * [consoleMessage.text()](#consolemessagetext) - * [consoleMessage.type()](#consolemessagetype) -- [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: ChromiumInterception](#class-chromiuminterception) - * [chromiumInterception.abort(request, [errorCode])](#chromiuminterceptionabortrequest-errorcode) - * [chromiumInterception.authenticate(credentials)](#chromiuminterceptionauthenticatecredentials) - * [chromiumInterception.continue(request, [overrides])](#chromiuminterceptioncontinuerequest-overrides) - * [chromiumInterception.disable()](#chromiuminterceptiondisable) - * [chromiumInterception.enable()](#chromiuminterceptionenable) - * [chromiumInterception.fulfill(request, response)](#chromiuminterceptionfulfillrequest-response) - * [chromiumInterception.setOfflineMode(enabled)](#chromiuminterceptionsetofflinemodeenabled) -- [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: 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.isIntersectingViewport()](#elementhandleisintersectingviewport) - * [elementHandle.ownerFrame()](#elementhandleownerframe) - * [elementHandle.press(key[, options])](#elementhandlepresskey-options) - * [elementHandle.screenshot([options])](#elementhandlescreenshotoptions) - * [elementHandle.select(...values)](#elementhandleselectvalues) - * [elementHandle.setInputFiles(...files)](#elementhandlesetinputfilesfiles) - * [elementHandle.toString()](#elementhandletostring) - * [elementHandle.tripleclick([options])](#elementhandletripleclickoptions) - * [elementHandle.type(text[, options])](#elementhandletypetext-options) - [class: Request](#class-request) * [request.failure()](#requestfailure) * [request.frame()](#requestframe) @@ -265,6 +215,50 @@ * [response.statusText()](#responsestatustext) * [response.text()](#responsetext) * [response.url()](#responseurl) +- [class: TimeoutError](#class-timeouterror) +- [class: ChromiumAccessibility](#class-chromiumaccessibility) + * [chromiumAccessibility.snapshot([options])](#chromiumaccessibilitysnapshotoptions) +- [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: ChromiumCoverage](#class-chromiumcoverage) + * [chromiumCoverage.startCSSCoverage([options])](#chromiumcoveragestartcsscoverageoptions) + * [chromiumCoverage.startJSCoverage([options])](#chromiumcoveragestartjscoverageoptions) + * [chromiumCoverage.stopCSSCoverage()](#chromiumcoveragestopcsscoverage) + * [chromiumCoverage.stopJSCoverage()](#chromiumcoveragestopjscoverage) +- [class: ChromiumInterception](#class-chromiuminterception) + * [chromiumInterception.abort(request, [errorCode])](#chromiuminterceptionabortrequest-errorcode) + * [chromiumInterception.authenticate(credentials)](#chromiuminterceptionauthenticatecredentials) + * [chromiumInterception.continue(request, [overrides])](#chromiuminterceptioncontinuerequest-overrides) + * [chromiumInterception.disable()](#chromiuminterceptiondisable) + * [chromiumInterception.enable()](#chromiuminterceptionenable) + * [chromiumInterception.fulfill(request, response)](#chromiuminterceptionfulfillrequest-response) + * [chromiumInterception.setOfflineMode(enabled)](#chromiuminterceptionsetofflinemodeenabled) +- [class: ChromiumOverrides](#class-chromiumoverrides) + * [chromiumOverrides.setGeolocation(options)](#chromiumoverridessetgeolocationoptions) +- [class: ChromiumPDF](#class-chromiumpdf) + * [chromiumPDF.generate([options])](#chromiumpdfgenerateoptions) +- [class: ChromiumPlaywright](#class-chromiumplaywright) + * [chromiumPlaywright.connect(options)](#chromiumplaywrightconnectoptions) + * [chromiumPlaywright.createBrowserFetcher([options])](#chromiumplaywrightcreatebrowserfetcheroptions) + * [chromiumPlaywright.defaultArgs([options])](#chromiumplaywrightdefaultargsoptions) + * [chromiumPlaywright.devices](#chromiumplaywrightdevices) + * [chromiumPlaywright.downloadBrowser([options])](#chromiumplaywrightdownloadbrowseroptions) + * [chromiumPlaywright.errors](#chromiumplaywrighterrors) + * [chromiumPlaywright.executablePath()](#chromiumplaywrightexecutablepath) + * [chromiumPlaywright.launch([options])](#chromiumplaywrightlaunchoptions) + * [chromiumPlaywright.launchServer([options])](#chromiumplaywrightlaunchserveroptions) +- [class: ChromiumSession](#class-chromiumsession) + * [chromiumSession.detach()](#chromiumsessiondetach) + * [chromiumSession.send(method[, params])](#chromiumsessionsendmethod-params) - [class: ChromiumTarget](#class-chromiumtarget) * [chromiumTarget.browserContext()](#chromiumtargetbrowsercontext) * [chromiumTarget.createCDPSession()](#chromiumtargetcreatecdpsession) @@ -272,197 +266,20 @@ * [chromiumTarget.page()](#chromiumtargetpage) * [chromiumTarget.type()](#chromiumtargettype) * [chromiumTarget.url()](#chromiumtargeturl) -- [class: ChromiumSession](#class-chromiumsession) - * [chromiumSession.detach()](#chromiumsessiondetach) - * [chromiumSession.send(method[, params])](#chromiumsessionsendmethod-params) -- [class: ChromiumCoverage](#class-chromiumcoverage) - * [chromiumCoverage.startCSSCoverage([options])](#chromiumcoveragestartcsscoverageoptions) - * [chromiumCoverage.startJSCoverage([options])](#chromiumcoveragestartjscoverageoptions) - * [chromiumCoverage.stopCSSCoverage()](#chromiumcoveragestopcsscoverage) - * [chromiumCoverage.stopJSCoverage()](#chromiumcoveragestopjscoverage) -- [class: TimeoutError](#class-timeouterror) +- [class: ChromiumWorker](#class-chromiumworker) + * [chromiumWorker.evaluate(pageFunction[, ...args])](#chromiumworkerevaluatepagefunction-args) + * [chromiumWorker.evaluateHandle(pageFunction[, ...args])](#chromiumworkerevaluatehandlepagefunction-args) + * [chromiumWorker.url()](#chromiumworkerurl) +- [class: ChromiumWorkers](#class-chromiumworkers) + * [event: 'workercreated'](#event-workercreated) + * [event: 'workerdestroyed'](#event-workerdestroyed) + * [chromiumWorkers.list()](#chromiumworkerslist) +- [class: FirefoxBrowser](#class-firefoxbrowser) +- [class: WebKitBrowser](#class-webkitbrowser) - [Working with selectors](#working-with-selectors) - [Working with Chrome Extensions](#working-with-chrome-extensions) -### Overview - -Playwright is a Node library which provides a high-level API to control Chromium or Chrome over the DevTools Protocol. - -The Playwright API is hierarchical and mirrors the browser structure. - -> **NOTE** On the following diagram, faded entities are not currently represented in Playwright. - -![playwright overview](https://user-images.githubusercontent.com/746130/40333229-5df5480c-5d0c-11e8-83cb-c3e371de7374.png) - -- [`Playwright`](#class-playwright) communicates with the browser using [DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/). -- [`Browser`](#class-browser) instance can own multiple browser contexts. -- [`BrowserContext`](#class-browsercontext) instance defines a browsing session and can own multiple pages. -- [`Page`](#class-page) has at least one frame: main frame. There might be other frames created by [iframe](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) or [frame](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/frame) tags. -- [`Frame`](#class-frame) has at least one execution context - the default execution context - where the frame's JavaScript is executed. A Frame might have additional execution contexts that are associated with [extensions](https://developer.chrome.com/extensions). -- [`Worker`](#class-worker) has a single execution context and facilitates interacting with [WebWorkers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API). - -(Diagram source: [link](https://docs.google.com/drawings/d/1Q_AM6KYs9kbyLZF-Lpp5mtpAWth73Cq8IKCsWYgi8MM/edit?usp=sharing)) - -### class: ChromiumPlaywright - -Playwright module provides a method to launch a Chromium instance. -The following is a typical example of using Playwright to drive automation: -```js -const playwright = require('playwright'); - -(async () => { - const browser = await playwright.launch(); - const context = await browser.newContext(); - const page = await context.newPage(); - await page.goto('https://www.google.com'); - // other actions... - await browser.close(); -})(); -``` - -#### chromiumPlaywright.connect(options) -- `options` <[Object]> - - `browserWSEndpoint` a [browser websocket endpoint](#browserwsendpoint) to connect to. - - `browserURL` 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). - - `slowMo` <[number]> Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. - - `transport` <[ConnectionTransport]> **Experimental** Specify a custom transport object for Playwright to use. -- returns: <[Promise]<[Browser]>> - -This methods attaches Playwright to an existing Chromium instance. - -#### chromiumPlaywright.createBrowserFetcher([options]) -- `options` <[Object]> - - `host` <[string]> A download host to be used. Defaults to `https://storage.googleapis.com`. - - `path` <[string]> A path for the downloads folder. Defaults to `/.local-chromium`, where `` is playwright's package root. - - `platform` <[string]> Possible values are: `mac`, `win32`, `win64`, `linux`. Defaults to the current platform. -- returns: <[BrowserFetcher]> - -#### chromiumPlaywright.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](https://developers.google.com/web/updates/2017/04/headless-chrome). 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]> Whether to auto-open a DevTools panel for each tab. If this option is `true`, the `headless` option will be set `false`. -- returns: <[Array]<[string]>> - -The default flags that Chromium will be launched with. - -#### chromiumPlaywright.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/lib/DeviceDescriptors.js). - -```js -const playwright = require('playwright'); -const iPhone = playwright.devices['iPhone 6']; - -(async () => { - const browser = await playwright.launch(); - const context = await browser.newContext(); - const page = await context.newPage(); - await page.emulate(iPhone); - await page.goto('https://www.google.com'); - // other actions... - await browser.close(); -})(); -``` - -> **NOTE** The old way (Playwright versions <= v1.14.0) devices can be obtained with `require('playwright/DeviceDescriptors')`. - -#### chromiumPlaywright.downloadBrowser([options]) -- `options` <[Object]> - - `onProgress` <[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 - -Downloads the default browser that Playwright controls. The browser is usually around 100mb. - -#### chromiumPlaywright.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. - } -} -``` - -> **NOTE** The old way (Playwright versions <= v1.14.0) errors can be obtained with `require('playwright/Errors')`. - -#### chromiumPlaywright.executablePath() -- returns: <[string]> A path where Playwright expects to find bundled Chromium. - -#### chromiumPlaywright.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](https://developers.google.com/web/updates/2017/04/headless-chrome). Defaults to `true` unless the `devtools` option is `true`. - - `executablePath` <[string]> Path to a Chromium or Chrome executable to run instead of the bundled Chromium. 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, 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 [`playwright.defaultArgs()`](#playwrightdefaultargsoptions). 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](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md). - - `env` <[Object]> Specify environment variables that will be visible to the browser. Defaults to `process.env`. - - `devtools` <[boolean]> Whether to auto-open a DevTools panel for each tab. If this option is `true`, the `headless` option will be set `false`. - - `pipe` <[boolean]> Connects to the browser over a pipe instead of a WebSocket. Defaults to `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 playwright.launch({ - ignoreDefaultArgs: ['--mute-audio'] -}); -``` - -> **NOTE** 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 [playwright.launch([options])](#playwrightlaunchoptions) 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. - -#### chromiumPlaywright.launchServer([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](https://developers.google.com/web/updates/2017/04/headless-chrome). Defaults to `true` unless the `devtools` option is `true`. - - `executablePath` <[string]> Path to a Chromium or Chrome executable to run instead of the bundled Chromium. 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, 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 [`playwright.defaultArgs()`](#playwrightdefaultargsoptions). 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](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md). - - `env` <[Object]> Specify environment variables that will be visible to the browser. Defaults to `process.env`. - - `devtools` <[boolean]> Whether to auto-open a DevTools panel for each tab. If this option is `true`, the `headless` option will be set `false`. - - `pipe` <[boolean]> Connects to the browser over a pipe instead of a WebSocket. Defaults to `false`. -- returns: <[Promise]<[BrowserServer]>> Promise which resolves to browser server instance. - ### class: Browser * extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter) @@ -559,166 +376,6 @@ Creates a new browser context. It won't share cookies/cache with other browser c })(); ``` -### class: BrowserFetcher - -BrowserFetcher can download and manage different versions of Chromium. - -BrowserFetcher operates on revision strings that specify a precise version of Chromium, e.g. `"533271"`. 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. -- 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. -- `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. - -#### browserFetcher.localRevisions() -- returns: <[Promise]<[Array]<[string]>>> A list of all revisions available locally on disk. - -#### browserFetcher.remove(revision) -- `revision` <[string]> a revision to remove. 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. -- 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: BrowserServer - -#### browserServer.close() -- returns: <[Promise]> - -Closes the browser gracefully and makes sure the process is terminated. - -#### browserServer.connect() -- returns: <[Promise]<[Browser]>> - -Connects to the browser server and returns a <[Browser]> object. - -#### browserServer.process() -- returns: Spawned browser server process. - -#### browserServer.wsEndpoint() -- returns: <[string]> Browser websocket url. - -Browser websocket endpoint which can be used as an argument to `playwright.connect`. - -Learn more about the [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: ChromiumBrowser - -* extends: [Browser] - -Chromium-specific features including Tracing, service worker support, etc. -You can use [`chromiumBrowser.startTracing`](#chromiumbrowserstarttracingpage-options) and [`chromiumBrowser.stopTracing`](#chromiumbrowserstoptracing) to create a trace file which can be opened in Chrome DevTools or [timeline viewer](https://chromedevtools.github.io/timeline-viewer/). - -```js -await browser.startTracing(page, {path: 'trace.json'}); -await page.goto('https://www.google.com'); -await browser.stopTracing(); -``` - -#### event: 'targetchanged' -- <[Target]> - -Emitted when the url of a target changes. - -> **NOTE** This includes target changes in incognito browser contexts. - - -#### event: 'targetcreated' -- <[Target]> - -Emitted when a target is created, for example when a new page is opened by [`window.open`](https://developer.mozilla.org/en-US/docs/Web/API/Window/open) or [`browserContext.newPage`](#browsercontextnewpage). - -> **NOTE** This includes target creations in incognito browser contexts. - -#### event: 'targetdestroyed' -- <[Target]> - -Emitted when a target is destroyed, for example when a page is closed. - -> **NOTE** This includes target destructions in incognito browser contexts. - -#### chromiumBrowser.browserTarget() -- returns: <[Target]> - -Returns browser target. - -#### chromiumBrowser.pageTarget(page) -- `page` <[Page]> Page to return target for. -- returns: <[Target]> a target given page was created from. - -#### chromiumBrowser.serviceWorker(target) -- `target` <[ChromiumTarget]> Target to treat as a service worker -- returns: <[Promise]<[ChromiumWorker]>> - -Attaches to the service worker target. - -#### chromiumBrowser.startTracing(page, [options]) -- `page` <[Page]> Optional, if specified, tracing includes screenshots of the given page. -- `options` <[Object]> - - `path` <[string]> A path to write the trace file to. - - `screenshots` <[boolean]> captures screenshots in the trace. - - `categories` <[Array]<[string]>> specify custom categories to use instead of default. -- returns: <[Promise]> - -Only one trace can be active at a time per browser. - -#### chromiumBrowser.stopTracing() -- returns: <[Promise]<[Buffer]>> Promise which resolves to buffer with trace data. - -#### chromiumBrowser.targets(context) -- `context` <[BrowserContext]> Optional, if specified, only targets from this context are returned. -- returns: <[Array]<[Target]>> - -An array of all active targets inside the Browser. In case of multiple browser contexts, -the method will return an array with all the targets in all browser contexts. - -#### chromiumBrowser.waitForTarget(predicate[, options]) -- `predicate` <[function]\([Target]\):[boolean]> A function to be run for every target -- `options` <[Object]> - - `timeout` <[number]> Maximum wait time in milliseconds. Pass `0` to disable the timeout. Defaults to 30 seconds. -- returns: <[Promise]<[Target]>> Promise which resolves to the first target found that matches the `predicate` function. - -This searches for a target in all browser contexts. - -An example of finding a target for a page opened via `window.open`: -```js -await page.evaluate(() => window.open('https://www.example.com/')); -const newWindowTarget = await browser.chromium.waitForTarget(target => target.url() === 'https://www.example.com/'); -``` - ### class: BrowserContext * extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter) @@ -840,22 +497,1183 @@ const context = browser.defaultContext(); await context.setPermissions('https://html5demos.com', ['geolocation']); ``` -### class: ChromiumOverrides +### class: BrowserFetcher -#### chromiumOverrides.setGeolocation(options) -- `options` <[Object]> - - `latitude` <[number]> Latitude between -90 and 90. - - `longitude` <[number]> Longitude between -180 and 180. - - `accuracy` <[number]> Optional non-negative accuracy value. -- returns: <[Promise]> +BrowserFetcher can download and manage different versions of Chromium. -Sets the page's geolocation. +BrowserFetcher operates on revision strings that specify a precise version of Chromium, e.g. `"533271"`. 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 -await browserContext.overrides.setGeolocation({latitude: 59.95, longitude: 30.31667}); +const browserFetcher = playwright.createBrowserFetcher(); +const revisionInfo = await browserFetcher.download('533271'); +const browser = await playwright.launch({executablePath: revisionInfo.executablePath}) ``` -> **NOTE** Consider using [browserContext.setPermissions](#browsercontextsetpermissions-permissions) to grant permissions for the page to read its geolocation. +> **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. +- 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. +- `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. + +#### browserFetcher.localRevisions() +- returns: <[Promise]<[Array]<[string]>>> A list of all revisions available locally on disk. + +#### browserFetcher.remove(revision) +- `revision` <[string]> a revision to remove. 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. +- 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: BrowserServer + +#### browserServer.close() +- returns: <[Promise]> + +Closes the browser gracefully and makes sure the process is terminated. + +#### browserServer.connect() +- returns: <[Promise]<[Browser]>> + +Connects to the browser server and returns a <[Browser]> object. + +#### browserServer.process() +- returns: Spawned browser server process. + +#### browserServer.wsEndpoint() +- returns: <[string]> Browser websocket url. + +Browser websocket endpoint which can be used as an argument to `playwright.connect`. + +Learn more about the [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: 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(); + await page.goto('https://example.com'); + const hrefElement = await page.$('a'); + await hrefElement.click(); + // ... +})(); +``` + +ElementHandle prevents DOM element from garbage collection unless the handle is [disposed](#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 ``, `