##### Released API: [v0.12.0](https://github.com/GoogleChrome/puppeteer/blob/v0.12.0/docs/api.md) | [v0.11.0](https://github.com/GoogleChrome/puppeteer/blob/v0.11.0/docs/api.md) | [v0.10.2](https://github.com/GoogleChrome/puppeteer/blob/v0.10.2/docs/api.md) | [v0.10.1](https://github.com/GoogleChrome/puppeteer/blob/v0.10.1/docs/api.md) | [v0.10.0](https://github.com/GoogleChrome/puppeteer/blob/v0.10.0/docs/api.md) | [v0.9.0](https://github.com/GoogleChrome/puppeteer/blob/v0.9.0/docs/api.md) # Puppeteer API v0.13.0-alpha ##### Table of Contents - [Overview](#overview) - [Environment Variables](#environment-variables) - [class: Puppeteer](#class-puppeteer) * [puppeteer.connect(options)](#puppeteerconnectoptions) * [puppeteer.executablePath()](#puppeteerexecutablepath) * [puppeteer.launch([options])](#puppeteerlaunchoptions) - [class: Browser](#class-browser) * [event: 'targetchanged'](#event-targetchanged) * [event: 'targetcreated'](#event-targetcreated) * [event: 'targetdestroyed'](#event-targetdestroyed) * [browser.close()](#browserclose) * [browser.disconnect()](#browserdisconnect) * [browser.newPage()](#browsernewpage) * [browser.pages()](#browserpages) * [browser.targets()](#browsertargets) * [browser.version()](#browserversion) * [browser.wsEndpoint()](#browserwsendpoint) - [class: Page](#class-page) * [event: 'console'](#event-console) * [event: 'dialog'](#event-dialog) * [event: 'error'](#event-error) * [event: 'frameattached'](#event-frameattached) * [event: 'framedetached'](#event-framedetached) * [event: 'framenavigated'](#event-framenavigated) * [event: 'load'](#event-load) * [event: 'metrics'](#event-metrics) * [event: 'pageerror'](#event-pageerror) * [event: 'request'](#event-request) * [event: 'requestfailed'](#event-requestfailed) * [event: 'requestfinished'](#event-requestfinished) * [event: 'response'](#event-response) * [page.$(selector)](#pageselector) * [page.$$(selector)](#pageselector) * [page.$$eval(selector, pageFunction[, ...args])](#pageevalselector-pagefunction-args) * [page.$eval(selector, pageFunction[, ...args])](#pageevalselector-pagefunction-args) * [page.addScriptTag(options)](#pageaddscripttagoptions) * [page.addStyleTag(options)](#pageaddstyletagoptions) * [page.authenticate(credentials)](#pageauthenticatecredentials) * [page.click(selector[, options])](#pageclickselector-options) * [page.close()](#pageclose) * [page.content()](#pagecontent) * [page.cookies(...urls)](#pagecookiesurls) * [page.deleteCookie(...cookies)](#pagedeletecookiecookies) * [page.emulate(options)](#pageemulateoptions) * [page.emulateMedia(mediaType)](#pageemulatemediamediatype) * [page.evaluate(pageFunction, ...args)](#pageevaluatepagefunction-args) * [page.evaluateHandle(pageFunction, ...args)](#pageevaluatehandlepagefunction-args) * [page.evaluateOnNewDocument(pageFunction, ...args)](#pageevaluateonnewdocumentpagefunction-args) * [page.exposeFunction(name, puppeteerFunction)](#pageexposefunctionname-puppeteerfunction) * [page.focus(selector)](#pagefocusselector) * [page.frames()](#pageframes) * [page.getMetrics()](#pagegetmetrics) * [page.goBack(options)](#pagegobackoptions) * [page.goForward(options)](#pagegoforwardoptions) * [page.goto(url, options)](#pagegotourl-options) * [page.hover(selector)](#pagehoverselector) * [page.keyboard](#pagekeyboard) * [page.mainFrame()](#pagemainframe) * [page.mouse](#pagemouse) * [page.pdf(options)](#pagepdfoptions) * [page.queryObjects(prototypeHandle)](#pagequeryobjectsprototypehandle) * [page.reload(options)](#pagereloadoptions) * [page.screenshot([options])](#pagescreenshotoptions) * [page.select(selector, ...values)](#pageselectselector-values) * [page.setContent(html, options)](#pagesetcontenthtml-options) * [page.setCookie(...cookies)](#pagesetcookiecookies) * [page.setExtraHTTPHeaders(headers)](#pagesetextrahttpheadersheaders) * [page.setJavaScriptEnabled(enabled)](#pagesetjavascriptenabledenabled) * [page.setOfflineMode(enabled)](#pagesetofflinemodeenabled) * [page.setRequestInterception(value)](#pagesetrequestinterceptionvalue) * [page.setUserAgent(userAgent)](#pagesetuseragentuseragent) * [page.setViewport(viewport)](#pagesetviewportviewport) * [page.tap(selector)](#pagetapselector) * [page.title()](#pagetitle) * [page.touchscreen](#pagetouchscreen) * [page.tracing](#pagetracing) * [page.type(selector, text[, options])](#pagetypeselector-text-options) * [page.url()](#pageurl) * [page.viewport()](#pageviewport) * [page.waitFor(selectorOrFunctionOrTimeout[, options[, ...args]])](#pagewaitforselectororfunctionortimeout-options-args) * [page.waitForFunction(pageFunction[, options[, ...args]])](#pagewaitforfunctionpagefunction-options-args) * [page.waitForNavigation(options)](#pagewaitfornavigationoptions) * [page.waitForSelector(selector[, options])](#pagewaitforselectorselector-options) - [class: Keyboard](#class-keyboard) * [keyboard.down(key[, options])](#keyboarddownkey-options) * [keyboard.press(key[, options])](#keyboardpresskey-options) * [keyboard.sendCharacter(char)](#keyboardsendcharacterchar) * [keyboard.type(text, options)](#keyboardtypetext-options) * [keyboard.up(key)](#keyboardupkey) - [class: Mouse](#class-mouse) * [mouse.click(x, y, [options])](#mouseclickx-y-options) * [mouse.down([options])](#mousedownoptions) * [mouse.move(x, y, [options])](#mousemovex-y-options) * [mouse.up([options])](#mouseupoptions) - [class: Touchscreen](#class-touchscreen) * [touchscreen.tap(x, y)](#touchscreentapx-y) - [class: Tracing](#class-tracing) * [tracing.start(options)](#tracingstartoptions) * [tracing.stop()](#tracingstop) - [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.text](#consolemessagetext) * [consoleMessage.type](#consolemessagetype) - [class: Frame](#class-frame) * [frame.$(selector)](#frameselector) * [frame.$$(selector)](#frameselector) * [frame.$$eval(selector, pageFunction[, ...args])](#frameevalselector-pagefunction-args) * [frame.$eval(selector, pageFunction[, ...args])](#frameevalselector-pagefunction-args) * [frame.addScriptTag(options)](#frameaddscripttagoptions) * [frame.addStyleTag(options)](#frameaddstyletagoptions) * [frame.childFrames()](#framechildframes) * [frame.evaluate(pageFunction, ...args)](#frameevaluatepagefunction-args) * [frame.executionContext()](#frameexecutioncontext) * [frame.isDetached()](#frameisdetached) * [frame.name()](#framename) * [frame.parentFrame()](#frameparentframe) * [frame.title()](#frametitle) * [frame.url()](#frameurl) * [frame.waitFor(selectorOrFunctionOrTimeout[, options[, ...args]])](#framewaitforselectororfunctionortimeout-options-args) * [frame.waitForFunction(pageFunction[, options[, ...args]])](#framewaitforfunctionpagefunction-options-args) * [frame.waitForSelector(selector[, options])](#framewaitforselectorselector-options) - [class: ExecutionContext](#class-executioncontext) * [executionContext.evaluate(pageFunction, ...args)](#executioncontextevaluatepagefunction-args) * [executionContext.evaluateHandle(pageFunction, ...args)](#executioncontextevaluatehandlepagefunction-args) * [executionContext.queryObjects(prototypeHandle)](#executioncontextqueryobjectsprototypehandle) - [class: JSHandle](#class-jshandle) * [jsHandle.asElement()](#jshandleaselement) * [jsHandle.dispose()](#jshandledispose) * [jsHandle.executionContext()](#jshandleexecutioncontext) * [jsHandle.getProperties()](#jshandlegetproperties) * [jsHandle.getProperty(propertyName)](#jshandlegetpropertypropertyname) * [jsHandle.jsonValue()](#jshandlejsonvalue) - [class: ElementHandle](#class-elementhandle) * [elementHandle.$(selector)](#elementhandleselector) * [elementHandle.$$(selector)](#elementhandleselector) * [elementHandle.asElement()](#elementhandleaselement) * [elementHandle.boundingBox()](#elementhandleboundingbox) * [elementHandle.click([options])](#elementhandleclickoptions) * [elementHandle.dispose()](#elementhandledispose) * [elementHandle.executionContext()](#elementhandleexecutioncontext) * [elementHandle.focus()](#elementhandlefocus) * [elementHandle.getProperties()](#elementhandlegetproperties) * [elementHandle.getProperty(propertyName)](#elementhandlegetpropertypropertyname) * [elementHandle.hover()](#elementhandlehover) * [elementHandle.jsonValue()](#elementhandlejsonvalue) * [elementHandle.press(key[, options])](#elementhandlepresskey-options) * [elementHandle.screenshot([options])](#elementhandlescreenshotoptions) * [elementHandle.tap()](#elementhandletap) * [elementHandle.toString()](#elementhandletostring) * [elementHandle.type(text[, options])](#elementhandletypetext-options) * [elementHandle.uploadFile(...filePaths)](#elementhandleuploadfilefilepaths) - [class: Request](#class-request) * [request.abort([errorCode])](#requestaborterrorcode) * [request.continue([overrides])](#requestcontinueoverrides) * [request.failure()](#requestfailure) * [request.headers](#requestheaders) * [request.method](#requestmethod) * [request.postData](#requestpostdata) * [request.resourceType](#requestresourcetype) * [request.respond(response)](#requestrespondresponse) * [request.response()](#requestresponse) * [request.url](#requesturl) - [class: Response](#class-response) * [response.buffer()](#responsebuffer) * [response.headers](#responseheaders) * [response.json()](#responsejson) * [response.ok](#responseok) * [response.request()](#responserequest) * [response.status](#responsestatus) * [response.text()](#responsetext) * [response.url](#responseurl) - [class: Target](#class-target) * [target.page()](#targetpage) * [target.type()](#targettype) * [target.url()](#targeturl) ### Overview Puppeteer is a Node library which provides a high-level API to control Chromium over the DevTools Protocol. Puppeteer API is hierarchical and mirrors browser structure. On the following diagram, faded entities are not currently represented in Puppeteer. ![puppeteer overview](https://user-images.githubusercontent.com/746130/31592143-089f6f9a-b1db-11e7-9a20-16b7fc754fa1.png) - [`Puppeteer`](#class-puppeteer) communicates with browser using [devtools protocol](https://chromedevtools.github.io/devtools-protocol/). - [`Browser`](#class-browser) instance owns 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 - default execution context - where frame's JavaScript is executed. Frame might have additional execution contexts associated with [extensions](https://developer.chrome.com/extensions). (Diagram source: [link](https://docs.google.com/drawings/d/1Q_AM6KYs9kbyLZF-Lpp5mtpAWth73Cq8IKCsWYgi8MM/edit?usp=sharing)) ### Environment Variables Puppeteer looks for certain [environment variables](https://en.wikipedia.org/wiki/Environment_variable) to aid its operations. These variables can either be set in the environment or in the [npm config](https://docs.npmjs.com/cli/config). - `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` - defines HTTP proxy settings that are used to download and run Chromium. - `PUPPETEER_SKIP_CHROMIUM_DOWNLOAD` - do not download bundled Chromium during installation step. - `PUPPETEER_DOWNLOAD_HOST` - overwrite host part of URL that is used to download Chromium ### class: Puppeteer Puppeteer module provides a method to launch a Chromium instance. The following is a typical example of using a Puppeteer to drive automation: ```js const puppeteer = require('puppeteer'); puppeteer.launch().then(async browser => { const page = await browser.newPage(); await page.goto('https://www.google.com'); // other actions... await browser.close(); }); ``` #### puppeteer.connect(options) - `options` <[Object]> - `browserWSEndpoint` <[string]> a [browser websocket endpoint](#browserwsendpoint) to connect to. - `ignoreHTTPSErrors` <[boolean]> Whether to ignore HTTPS errors during navigation. Defaults to `false`. - returns: <[Promise]<[Browser]>> This methods attaches Puppeteer to an existing Chromium instance. #### puppeteer.executablePath() - returns: <[string]> A path where Puppeteer expects to find bundled Chromium. Chromium might not exist there if the download was skipped with [`PUPPETEER_SKIP_CHROMIUM_DOWNLOAD`](#environment-variables). #### puppeteer.launch([options]) - `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields: - `ignoreHTTPSErrors` <[boolean]> Whether to ignore HTTPS errors during navigation. Defaults to `false`. - `headless` <[boolean]> Whether to run Chromium 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 executable to run instead of 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). - `slowMo` <[number]> Slows down Puppeteer 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 Chromium instance. List of Chromium flags can be found [here](http://peter.sh/experiments/chromium-command-line-switches/). - `handleSIGINT` <[boolean]> Close chrome process on Ctrl-C. Defaults to `true`. - `timeout` <[number]> Maximum time in milliseconds to wait for the Chrome instance to start. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. - `dumpio` <[boolean]> Whether to pipe 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 Chromium. Defaults to `process.env`. - `devtools` <[boolean]> Whether to auto-open DevTools panel for each tab. If this option is `true`, the `headless` option will be set `false`. - returns: <[Promise]<[Browser]>> Promise which resolves to browser instance. The method launches a browser instance with given arguments. The browser will be closed when the parent node.js process is closed. > **NOTE** Puppeteer 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. ### class: Browser A Browser is created when Puppeteer connects to a Chromium instance, either through [`puppeteer.launch`](#puppeteerlaunchoptions) or [`puppeteer.connect`](#puppeteerconnectoptions). An example of using a [Browser] to create a [Page]: ```js const puppeteer = require('puppeteer'); puppeteer.launch().then(async browser => { const page = await browser.newPage(); await page.goto('https://example.com'); await browser.close(); }); ``` An example of disconnecting from and reconnecting to a [Browser]: ```js const puppeteer = require('puppeteer'); puppeteer.launch().then(async browser => { // Store the endpoint to be able to reconnect to Chromium const browserWSEndpoint = browser.wsEndpoint(); // Disconnect puppeteer from Chromium browser.disconnect(); // Use the endpoint to reestablish a connection const browser2 = await puppeteer.connect({browserWSEndpoint}); // Close Chromium await browser2.close(); }); ``` #### event: 'targetchanged' - <[Target]> Emitted when the url of a target changes. #### 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 [`browser.newPage`](#browsernewpage). #### event: 'targetdestroyed' - <[Target]> Emitted when a target is destroyed, for example when a page is closed. #### browser.close() - returns: <[Promise]> Closes Chromium and all of its pages (if any were opened). The browser object itself is considered disposed and cannot be used anymore. #### browser.disconnect() Disconnects Puppeteer from the browser, but leaves the Chromium process running. After calling `disconnect`, the browser object is considered disposed and cannot be used anymore. #### browser.newPage() - returns: <[Promise]<[Page]>> Promise which resolves to a new [Page] object. #### browser.pages() - returns: <[Promise]<[Array]<[Page]>>> Promise which resolves to an array of all open pages. #### browser.targets() - returns: <[Array]<[Target]>> An array of all active targets. #### browser.version() - returns: <[Promise]<[string]>> For headless Chromium, this is similar to `HeadlessChrome/61.0.3153.0`. For non-headless, this is similar to `Chrome/61.0.3153.0`. > **NOTE** the format of browser.version() might change with future releases of Chromium. #### browser.wsEndpoint() - returns: <[string]> Browser websocket url. Browser websocket endpoint which can be used as an argument to [puppeteer.connect](#puppeteerconnectoptions). The format is `ws://${host}:${port}/devtools/browser/` You can find the `webSocketDebuggerUrl` from `http://${host}:${port}/json/version`. 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: Page Page provides methods to interact with a single tab in Chromium. One [Browser] instance might have multiple [Page] instances. This example creates a page, navigates it to a URL, and then saves a screenshot: ```js const puppeteer = require('puppeteer'); puppeteer.launch().then(async browser => { const page = await browser.newPage(); await page.goto('https://example.com'); await page.screenshot({path: 'screenshot.png'}); await browser.close(); }); ``` #### event: 'console' - <[ConsoleMessage]> Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`. Also emitted if the page throws an error or a warning. The arguments passed into `console.log` appear as arguments on the event handler. An example of handling `console` event: ```js page.on('console', msg => { for (let i = 0; i < msg.args.length; ++i) console.log(`${i}: ${msg.args[i]}`); }); page.evaluate(() => console.log('hello', 5, {foo: 'bar'})); ``` #### event: 'dialog' - <[Dialog]> Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Puppeteer can respond to the dialog via [Dialog]'s [accept](#dialogacceptprompttext) or [dismiss](#dialogdismiss) methods. #### event: 'error' - <[Error]> Emitted when the page crashes. > **NOTE** `error` event has a special meaning in Node, see [error events](https://nodejs.org/api/events.html#events_error_events) for details. #### event: 'frameattached' - <[Frame]> Emitted when a frame is attached. #### event: 'framedetached' - <[Frame]> Emitted when a frame is detached. #### event: 'framenavigated' - <[Frame]> Emitted when a frame is navigated to a new url. #### event: 'load' Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched. #### event: 'metrics' - <[Object]> - `title` <[string]> The title passed to `console.timeStamp`. - `metrics` <[Object]> Object containing metrics as key/value pairs. The values of metrics are of <[number]> type. Emitted when the JavaScript code makes a call to `console.timeStamp`. For the list of metrics see `page.getMetrics`. #### event: 'pageerror' - <[string]> The exception message Emitted when an uncaught exception happens within the page. #### event: 'request' - <[Request]> Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests, see `page.setRequestInterception`. #### event: 'requestfailed' - <[Request]> Emitted when a request fails, for example by timing out. #### event: 'requestfinished' - <[Request]> Emitted when a request finishes successfully. #### event: 'response' - <[Response]> Emitted when a [response] is received. #### page.$(selector) - `selector` <[string]> A [selector] to query page for - returns: <[Promise]<[ElementHandle]>> The method runs `document.querySelector` within the page. If no element matches the selector, the return value resolve to `null`. Shortcut for [page.mainFrame().$(selector)](#frameselector). #### page.$$(selector) - `selector` <[string]> A [selector] to query page for - returns: <[Promise]<[Array]<[ElementHandle]>>> The method runs `document.querySelectorAll` within the page. If no elements match the selector, the return value resolve to `[]`. Shortcut for [page.mainFrame().$$(selector)](#frameselector-1). #### page.$$eval(selector, pageFunction[, ...args]) - `selector` <[string]> A [selector] to query frame for - `pageFunction` <[function]> Function to be evaluated in browser context - `...args` <...[Serializable]|[ElementHandle]> Arguments to pass to `pageFunction` - returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction` This method runs `document.querySelectorAll` within the page and passes it as the first argument to `pageFunction`. If `pageFunction` returns a [Promise], then `page.$$eval` would wait for the promise to resolve and return its value. Examples: ```js const divsCounts = await page.$$eval('div', divs => divs.length); ``` #### page.$eval(selector, pageFunction[, ...args]) - `selector` <[string]> A [selector] to query page for - `pageFunction` <[function]> Function to be evaluated in browser context - `...args` <...[Serializable]|[ElementHandle]> Arguments to pass to `pageFunction` - returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction` This method runs `document.querySelector` within the page 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 `page.$eval` would wait for the promise to resolve and return its value. Examples: ```js const searchValue = await page.$eval('#search', el => el.value); const preloadHref = await page.$eval('link[rel=preload]', el => el.href); const html = await page.$eval('.main-container', e => e.outerHTML); ``` Shortcut for [page.mainFrame().$eval(selector, pageFunction)](#frameevalselector-pagefunction-args). #### page.addScriptTag(options) - `options` <[Object]> - `url` <[string]> Url of a script to be added. - `path` <[string]> Path to the JavaScript file to be injected into frame. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). - `content` <[string]> Raw JavaScript content to be injected into frame. - returns: <[Promise]> which resolves when the script's onload fires or when the script content was injected into frame. Adds a `