# Puppeteer API v0.1.0 ##### Table of Contents - [Puppeteer](#puppeteer) * [class: Puppeteer](#class-puppeteer) + [puppeteer.launch([options])](#puppeteerlaunchoptions) * [class: Browser](#class-browser) + [browser.close()](#browserclose) + [browser.newPage()](#browsernewpage) + [browser.version()](#browserversion) * [class: Page](#class-page) + [event: 'console'](#event-console) + [event: 'dialog'](#event-dialog) + [event: 'frameattached'](#event-frameattached) + [event: 'framedetached'](#event-framedetached) + [event: 'framenavigated'](#event-framenavigated) + [event: 'load'](#event-load) + [event: 'pageerror'](#event-pageerror) + [event: 'request'](#event-request) + [event: 'requestfailed'](#event-requestfailed) + [event: 'requestfinished'](#event-requestfinished) + [event: 'response'](#event-response) + [page.addBinding(name, puppeteerFunction)](#pageaddbindingname-puppeteerfunction) + [page.addScriptTag(url)](#pageaddscripttagurl) + [page.click(selector[, options])](#pageclickselector-options) + [page.close()](#pageclose) + [page.emulate(options)](#pageemulateoptions) + [page.evaluate(pageFunction, ...args)](#pageevaluatepagefunction-args) + [page.evaluateOnNewDocument(pageFunction, ...args)](#pageevaluateonnewdocumentpagefunction-args) + [page.focus(selector)](#pagefocusselector) + [page.frames()](#pageframes) + [page.goBack(options)](#pagegobackoptions) + [page.goForward(options)](#pagegoforwardoptions) + [page.goto(url, options)](#pagegotourl-options) + [page.hover(selector)](#pagehoverselector) + [page.injectFile(filePath)](#pageinjectfilefilepath) + [page.keyboard](#pagekeyboard) + [page.mainFrame()](#pagemainframe) + [page.mouse](#pagemouse) + [page.pdf(options)](#pagepdfoptions) + [page.plainText()](#pageplaintext) + [page.press(key[, options])](#pagepresskey-options) + [page.reload(options)](#pagereloadoptions) + [page.screenshot([options])](#pagescreenshotoptions) + [page.setContent(html)](#pagesetcontenthtml) + [page.setExtraHTTPHeaders(headers)](#pagesetextrahttpheadersheaders) + [page.setRequestInterceptionEnabled(value)](#pagesetrequestinterceptionenabledvalue) + [page.setUserAgent(userAgent)](#pagesetuseragentuseragent) + [page.setViewport(viewport)](#pagesetviewportviewport) + [page.title()](#pagetitle) + [page.tracing](#pagetracing) + [page.type(text, options)](#pagetypetext-options) + [page.uploadFile(selector, ...filePaths)](#pageuploadfileselector-filepaths) + [page.url()](#pageurl) + [page.viewport()](#pageviewport) + [page.waitFor(selectorOrFunctionOrTimeout[, options])](#pagewaitforselectororfunctionortimeout-options) + [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.sendCharacter(char)](#keyboardsendcharacterchar) + [keyboard.up(key)](#keyboardupkey) * [class: Mouse](#class-mouse) + [mouse.click(x, y, [options])](#mouseclickx-y-options) + [mouse.down([options])](#mousedownoptions) + [mouse.move(x, y)](#mousemovex-y) + [mouse.up([options])](#mouseupoptions) * [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: Frame](#class-frame) + [frame.addScriptTag(url)](#frameaddscripttagurl) + [frame.childFrames()](#framechildframes) + [frame.click(selector[, options])](#frameclickselector-options) + [frame.evaluate(pageFunction, ...args)](#frameevaluatepagefunction-args) + [frame.focus(selector)](#framefocusselector) + [frame.hover(selector)](#framehoverselector) + [frame.injectFile(filePath)](#frameinjectfilefilepath) + [frame.isDetached()](#frameisdetached) + [frame.name()](#framename) + [frame.parentFrame()](#frameparentframe) + [frame.title()](#frametitle) + [frame.uploadFile(selector, ...filePaths)](#frameuploadfileselector-filepaths) + [frame.url()](#frameurl) + [frame.waitFor(selectorOrFunctionOrTimeout[, options])](#framewaitforselectororfunctionortimeout-options) + [frame.waitForFunction(pageFunction[, options, ...args])](#framewaitforfunctionpagefunction-options-args) + [frame.waitForSelector(selector[, options])](#framewaitforselectorselector-options) * [class: Request](#class-request) + [request.abort()](#requestabort) + [request.continue([overrides])](#requestcontinueoverrides) + [request.headers](#requestheaders) + [request.method](#requestmethod) + [request.postData](#requestpostdata) + [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) ## Puppeteer Puppeteer is a Node library which provides a high-level API to control Chromium over the DevTools Protocol. ### 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 => { let page = await browser.newPage(); await page.goto('https://google.com'); // other actions... browser.close(); }); ``` #### 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`. - `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/). - `dumpio` <[boolean]> Whether to pipe browser process stdout and stderr into `process.stdout` and `process.stderr`. Defaults to `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 gets closed. > **Note** Puppeteer works best with bundled version of Chromium, and there's no guarantee it would work properly with any other version. Use `executablePath` option with extreme caution. ### class: Browser Browser manages a browser instance, creating it with a predefined settings, opening and closing pages. Instantiating Browser class does not necessarily result in launching browser; the instance will be launched when the need will arise. A typical scenario of using [Browser] is opening a new page and navigating it to a desired URL: ```js const puppeteer = require('puppeteer'); puppeteer.launch().then(async browser => { let page = await browser.newPage(); await page.goto('https://example.com'); browser.close(); }); ``` #### browser.close() Closes browser with all the pages (if any were opened). The browser object itself is considered to be disposed and could not be used anymore. #### browser.newPage() - returns: <[Promise]<[Page]>> Promise which resolves to a new [Page] object. #### browser.version() - returns: <[Promise]<[string]>> String describing browser version. For headless Chromium, this is similar to `HeadlessChrome/61.0.3153.0`. For non-headless, this is `Chrome/61.0.3153.0`. > **NOTE** the format of browser.version() is not fixed and might change with future releases of the library. ### class: Page Page provides methods to interact with browser page. Page could be thought about as a browser tab, so one [Browser] instance might have multiple [Page] instances. An example of creating a page, navigating it to a URL and saving screenshot as `screenshot.png`: ```js const puppeteer = require('puppeteer'); puppeteer.launch().then(async browser => { let page = await browser.newPage(); await page.goto('https://example.com'); await page.screenshot({path: 'screenshot.png'}); browser.close(); }); ``` #### event: 'console' - <[string]> Emitted when a page calls one of console API methods, e.g. `console.log` or `console.dir`. If multiple arguments are passed over to the console API call, these arguments are dispatched in an event. An example of handling `console` event: ```js page.on('console', (...args) => { for (let i =0; i < args.length; ++i) console.log(`${i}: ${args[i]}`); }); page.evaluate(() => console.log(5, 'hello', {foo: 'bar'})); ``` #### event: 'dialog' - <[Dialog]> Emitted when a JavaScript dialog, such as `alert`, `prompt`, `confirm` or `beforeunload`, gets opened on the page. Puppeteer can take action to the dialog via dialog's [accept](#dialogacceptprompttext) or [dismiss](#dialogdismiss) methods. #### event: 'frameattached' - <[Frame]> Emitted when a frame gets attached. #### event: 'framedetached' - <[Frame]> Emitted when a frame gets detached. #### event: 'framenavigated' - <[Frame]> Emitted when a frame committed navigation. #### event: 'load' Emitted when a page's `load` event was dispatched. #### event: 'pageerror' - <[string]> Emitted when an unhandled exception happens on the page. The only argument of the event holds the exception message. #### event: 'request' - <[Request]> Emitted when a page issues a request. The [request] object is a read-only object. In order to intercept and mutate requests, see `page.setRequestInterceptionEnabled`. #### event: 'requestfailed' - <[Request]> Emitted when a request is failed. #### event: 'requestfinished' - <[Request]> Emitted when a request is successfully finished. #### event: 'response' - <[Response]> Emitted when a [response] is received. #### page.addBinding(name, puppeteerFunction) - `name` <[string]> Name of the binding on window object - `puppeteerFunction` <[function]> Callback function which will be called in Puppeteer's context. - returns: <[Promise]> Promise which resolves with the result of `puppeteerFunction`. The method adds a function called `name` on `window` object. When called, the function executes `puppeteerFunction` function in puppeteer context and returns a promise that resolves with the puppeteer's result. If the `puppeteerFunction` returns a promise, it would be awaited. > **NOTE** All the bindings installed via the `page.addBinding` survive navigations. An example of adding `window.md5` binding to the page: ```js const puppeteer = require('puppeteer'); const crypto = require('crypto'); puppeteer.launch().then(async browser => { let page = await browser.newPage(); page.on('console', console.log); await page.setInPageCallback('md5', text => crypto.createHash('md5').update(text).digest('hex')); await page.evaluate(async () => { // use window.md5 to compute hashes let myString = 'PUPPETEER'; let myHash = await window.md5(myString); console.log(`md5 of ${myString} is ${myHash}`); }); browser.close(); }); ``` An example of adding `window.readfile` binding to the page: ```js const puppeteer = require('puppeteer'); const fs = require('fs'); puppeteer.launch().then(async browser => { let page = await browser.newPage(); page.on('console', console.log); await page.setInPageCallback('readfile', async filePath => { return new Promise((resolve, reject) => { fs.readFile(filePath, 'utf8', (err, text) => { if (err) reject(err); else resolve(text); }); }); }); await page.evaluate(async () => { // use window.readfile to read contents of a file let content = await window.readfile('/etc/hosts'); console.log(content); }); browser.close(); }); ``` #### page.addScriptTag(url) - `url` <[string]> Url of a script to be added - returns: <[Promise]> Promise which resolves as the script gets added and loads. Adds a `