From c62b02f177db0460069101ebad999a0e0e0e606d Mon Sep 17 00:00:00 2001 From: David Barton <43063460+theDavidBarton@users.noreply.github.com> Date: Tue, 23 Mar 2021 10:02:34 +0100 Subject: [PATCH] chore: automate prettier in docs (#7014) Issue: #7012 Co-authored-by: Mathias Bynens --- .prettierignore | 8 + CONTRIBUTING.md | 9 +- docs/api.md | 951 +++++++++++++++++------ docs/troubleshooting.md | 29 +- examples/README.md | 3 +- experimental/puppeteer-firefox/README.md | 4 +- package.json | 4 +- test/README.md | 25 +- utils/doclint/README.md | 14 +- 9 files changed, 760 insertions(+), 287 deletions(-) create mode 100644 .prettierignore diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000..dacae78b --- /dev/null +++ b/.prettierignore @@ -0,0 +1,8 @@ +node_modules/ +lib/ +third_party/ +vendor/ + +package-lock.json +yarn.lock +package.json diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 992efb45..2ac41ffb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,3 +1,4 @@ + - [How to Contribute](#how-to-contribute) * [Contributor License Agreement](#contributor-license-agreement) @@ -21,7 +22,7 @@ - [Bisecting upstream changes](#bisecting-upstream-changes) * [Releasing to npm](#releasing-to-npm) - + # How to Contribute First of all, thank you for your interest in Puppeteer! @@ -164,6 +165,12 @@ To run the documentation linter, use: npm run doc ``` +To format the documentation markdown and its code snippets, use: + +```bash +npm run markdownlint-fix +``` + ## Adding New Dependencies For all dependencies (both installation and development): diff --git a/docs/api.md b/docs/api.md index f09d69c3..9a37dc7f 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1,10 +1,13 @@ - # Puppeteer API Tip-Of-Tree + - Interactive Documentation: https://pptr.dev - API Translations: [中文|Chinese](https://zhaoqize.github.io/puppeteer-api-zh_CN/#/) - Troubleshooting: [troubleshooting.md](https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md) + + + - Releases per Chromium version: * Chromium 90.0.4427.0 - [Puppeteer v8.0.0](https://github.com/puppeteer/puppeteer/blob/v8.0.0/docs/api.md) @@ -28,8 +31,12 @@ * [All releases](https://github.com/puppeteer/puppeteer/releases) + + ##### Table of Contents + + - [Overview](#overview) - [puppeteer vs puppeteer-core](#puppeteer-vs-puppeteer-core) @@ -369,6 +376,8 @@ - [interface: CustomQueryHandler](#interface-customqueryhandler) + + ### Overview Puppeteer is a Node library which provides a high-level API to control Chromium or Chrome over the DevTools Protocol. @@ -391,27 +400,30 @@ The Puppeteer API is hierarchical and mirrors the browser structure. ### puppeteer vs puppeteer-core Every release since v1.7.0 we publish two packages: + - [puppeteer](https://www.npmjs.com/package/puppeteer) - [puppeteer-core](https://www.npmjs.com/package/puppeteer-core) -`puppeteer` is a *product* for browser automation. When installed, it downloads a version of +`puppeteer` is a _product_ for browser automation. When installed, it downloads a version of Chromium, which it then drives using `puppeteer-core`. Being an end-user product, `puppeteer` supports a bunch of convenient `PUPPETEER_*` env variables to tweak its behavior. -`puppeteer-core` is a *library* to help drive anything that supports DevTools protocol. `puppeteer-core` doesn't download Chromium when installed. Being a library, `puppeteer-core` is fully driven +`puppeteer-core` is a _library_ to help drive anything that supports DevTools protocol. `puppeteer-core` doesn't download Chromium when installed. Being a library, `puppeteer-core` is fully driven through its programmatic interface and disregards all the `PUPPETEER_*` env variables. To sum up, the only differences between `puppeteer-core` and `puppeteer` are: + - `puppeteer-core` doesn't automatically download Chromium when installed. - `puppeteer-core` ignores all `PUPPETEER_*` env variables. In most cases, you'll be fine using the `puppeteer` package. However, you should use `puppeteer-core` if: + - you're building another end-user product or library atop of DevTools protocol. For example, one might build a PDF generator using `puppeteer-core` and write a custom `install.js` script that downloads [`headless_shell`](https://chromium.googlesource.com/chromium/src/+/lkgr/headless/README.md) instead of Chromium to save disk space. - you're bundling Puppeteer to use in Chrome Extension / browser with the DevTools protocol where downloading an additional Chromium binary is unnecessary. - you're building a set of tools where `puppeteer-core` is one of the ingredients and you want to postpone `install.js` script execution until Chromium is about to be used. -When using `puppeteer-core`, remember to change the *include* line: +When using `puppeteer-core`, remember to change the _include_ line: ```js const puppeteer = require('puppeteer-core'); @@ -432,8 +444,7 @@ If Puppeteer doesn't find them in the environment during the installation step, - `PUPPETEER_EXECUTABLE_PATH` - specify an executable path to be used in `puppeteer.launch`. See [puppeteer.launch([options])](#puppeteerlaunchoptions) on how the executable path is inferred. **BEWARE**: Puppeteer is only [guaranteed to work](https://github.com/puppeteer/puppeteer/#q-why-doesnt-puppeteer-vxxx-work-with-chromium-vyyy) with the bundled Chromium, use at your own risk. - `PUPPETEER_PRODUCT` - specify which browser you'd like Puppeteer to use. Must be one of `chrome` or `firefox`. This can also be used during installation to fetch the recommended browser binary. Setting `product` programmatically in [puppeteer.launch([options])](#puppeteerlaunchoptions) supersedes this environment variable. The product is exposed in [`puppeteer.product`](#puppeteerproduct) -> **NOTE** PUPPETEER_* env variables are not accounted for in the [`puppeteer-core`](https://www.npmjs.com/package/puppeteer-core) package. - +> **NOTE** `PUPPETEER_*` env variables are not accounted for in the [`puppeteer-core`](https://www.npmjs.com/package/puppeteer-core) package. ### Working with Chrome Extensions @@ -442,6 +453,7 @@ Puppeteer can be used for testing Chrome Extensions. > **NOTE** Extensions in Chrome / Chromium currently only work in non-headless mode. The following is code for getting a handle to the [background page](https://developer.chrome.com/extensions/background_pages) of an extension whose source is located in `./my-extension`: + ```js const puppeteer = require('puppeteer'); @@ -451,11 +463,13 @@ const puppeteer = require('puppeteer'); headless: false, args: [ `--disable-extensions-except=${pathToExtension}`, - `--load-extension=${pathToExtension}` - ] + `--load-extension=${pathToExtension}`, + ], }); const targets = await browser.targets(); - const backgroundPageTarget = targets.find(target => target.type() === 'background_page'); + const backgroundPageTarget = targets.find( + (target) => target.type() === 'background_page' + ); const backgroundPage = await backgroundPageTarget.page(); // Test the background page as you would any other page. await browser.close(); @@ -468,6 +482,7 @@ const puppeteer = require('puppeteer'); Puppeteer module provides a method to launch a Chromium instance. The following is a typical example of using Puppeteer to drive automation: + ```js const puppeteer = require('puppeteer'); @@ -479,10 +494,13 @@ const puppeteer = require('puppeteer'); await browser.close(); })(); ``` + #### puppeteer.clearCustomQueryHandlers() + Clears all registered handlers. #### puppeteer.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 Puppeteer fetch it from [metadata endpoint](https://chromedevtools.github.io/devtools-protocol/#how-do-i-access-the-browser-target). @@ -502,6 +520,7 @@ Clears all registered handlers. This methods attaches Puppeteer to an existing browser instance. #### puppeteer.createBrowserFetcher([options]) + - `options` <[Object]> - `host` <[string]> A download host to be used. Defaults to `https://storage.googleapis.com`. If the `product` is `firefox`, this defaults to `https://archive.mozilla.org/pub/firefox/nightly/latest-mozilla-central`. - `path` <[string]> A path for the downloads folder. Defaults to `/.local-chromium`, where `` is puppeteer's package root. If the `product` is `firefox`, this defaults to `/.local-firefox`. @@ -510,10 +529,12 @@ This methods attaches Puppeteer to an existing browser instance. - returns: <[BrowserFetcher]> #### puppeteer.customQueryHandlerNames() + - returns: <[Array]> A list with the names of all registered custom query handlers. #### puppeteer.defaultArgs([options]) -- `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields: + +- `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). @@ -523,6 +544,7 @@ This methods attaches Puppeteer to an existing browser instance. The default flags that Chromium will be launched with. #### puppeteer.devices + - returns: <[Object]> Returns a list of devices to be used with [`page.emulate(options)`](#pageemulateoptions). Actual list of @@ -543,6 +565,7 @@ const iPhone = puppeteer.devices['iPhone 6']; ``` #### puppeteer.errors + - returns: <[Object]> - `TimeoutError` <[function]> A class of [TimeoutError]. @@ -553,6 +576,7 @@ For certain types of errors Puppeteer uses specific error classes. These classes are available via [`puppeteer.errors`](#puppeteererrors) An example of handling a timeout error: + ```js try { await page.waitForSelector('.foo'); @@ -566,13 +590,14 @@ try { > **NOTE** The old way (Puppeteer versions <= v1.14.0) errors can be obtained with `require('puppeteer/Errors')`. #### puppeteer.executablePath() + - returns: <[string]> A path where Puppeteer expects to find the bundled browser. The browser binary might not be there if the download was skipped with [`PUPPETEER_SKIP_CHROMIUM_DOWNLOAD`](#environment-variables). > **NOTE** `puppeteer.executablePath()` is affected by the `PUPPETEER_EXECUTABLE_PATH` and `PUPPETEER_CHROMIUM_REVISION` env variables. See [Environment Variables](#environment-variables) for details. - #### puppeteer.launch([options]) -- `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields: + +- `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields: - `product` <[string]> Which browser to launch. At this time, this is either `chrome` or `firefox`. See also `PUPPETEER_PRODUCT`. - `ignoreHTTPSErrors` <[boolean]> Whether to ignore HTTPS errors during navigation. Defaults to `false`. - `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`. @@ -599,11 +624,11 @@ try { - `extraPrefsFirefox` <[Object]> Additional [preferences](https://developer.mozilla.org/en-US/docs/Mozilla/Preferences/Preference_reference) that can be passed to Firefox (see `PUPPETEER_PRODUCT`) - 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 puppeteer.launch({ - ignoreDefaultArgs: ['--mute-audio'] + ignoreDefaultArgs: ['--mute-audio'], }); ``` @@ -616,6 +641,7 @@ const browser = await puppeteer.launch({ > 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. #### puppeteer.networkConditions + - returns: <[Object]> Returns a list of network conditions to be used with [`page.emulateNetworkConditions(networkConditions)`](#pageemulatenetworkconditionsnetworkconditions). Actual list of @@ -636,11 +662,13 @@ const slow3G = puppeteer.networkConditions['Slow 3G']; ``` #### puppeteer.product + - returns: <[string]> returns the name of the browser that is under automation (`"chrome"` or `"firefox"`) The product is set by the `PUPPETEER_PRODUCT` environment variable or the `product` option in [puppeteer.launch([options])](#puppeteerlaunchoptions) and defaults to `chrome`. Firefox support is experimental and requires to install Puppeteer via `PUPPETEER_PRODUCT=firefox npm i puppeteer`. #### puppeteer.registerCustomQueryHandler(name, queryHandler) + - `name` <[string]> The name that the custom query handler will be registered under. - `queryHandler` <[CustomQueryHandler]> The [custom query handler](#interface-customqueryhandler) to register. @@ -661,6 +689,7 @@ const aHandle = await page.$('getByClass/…'); ``` #### puppeteer.unregisterCustomQueryHandler(name) + - `name` <[string]> The name of the query handler to unregister. ### class: BrowserFetcher @@ -677,19 +706,23 @@ Puppeteer against it: ```js const browserFetcher = puppeteer.createBrowserFetcher(); const revisionInfo = await browserFetcher.download('533271'); -const browser = await puppeteer.launch({ executablePath: revisionInfo.executablePath }); +const browser = await puppeteer.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. +- 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 @@ -704,22 +737,28 @@ The method initiates a HEAD request to check if the revision is available. The method initiates a GET request to download the revision from the host. #### browserFetcher.host() + - returns: <[string]> The download host being used. #### browserFetcher.localRevisions() + - returns: <[Promise]<[Array]<[string]>>> A list of all revisions (for the current `product`) available locally on disk. #### browserFetcher.platform() + - returns: <[string]> One of `mac`, `linux`, `win32` or `win64`. #### browserFetcher.product() + - returns: <[string]> One of `chrome` or `firefox`. #### browserFetcher.remove(revision) + - `revision` <[string]> a revision to remove for the current `product`. 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 @@ -734,11 +773,12 @@ The method initiates a GET request to download the revision from the host. ### class: Browser -* extends: [EventEmitter](#class-eventemitter) +- extends: [EventEmitter](#class-eventemitter) 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'); @@ -751,6 +791,7 @@ const puppeteer = require('puppeteer'); ``` An example of disconnecting from and reconnecting to a [Browser]: + ```js const puppeteer = require('puppeteer'); @@ -767,20 +808,24 @@ const puppeteer = require('puppeteer'); await browser2.close(); })(); ``` + #### event: 'disconnected' + Emitted when Puppeteer gets disconnected from the Chromium instance. This might happen because of one of the following: + - Chromium is closed or crashed - The [`browser.disconnect`](#browserdisconnect) method was called #### 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 [`browser.newPage`](#browsernewpage). @@ -788,6 +833,7 @@ Emitted when a target is created, for example when a new page is opened by [`win > **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. @@ -795,17 +841,20 @@ Emitted when a target is destroyed, for example when a page is closed. > **NOTE** This includes target destructions in incognito browser contexts. #### 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 Chromium and all of its pages (if any were opened). The [Browser] object itself is considered to be disposed and cannot be used anymore. #### browser.createIncognitoBrowserContext() + - returns: <[Promise]<[BrowserContext]>> Creates a new incognito browser context. This won't share cookies/cache with other browser contexts. @@ -823,6 +872,7 @@ Creates a new incognito browser context. This won't share cookies/cache with oth ``` #### browser.defaultBrowserContext() + - returns: <[BrowserContext]> Returns the default browser context. The default browser context can not be closed. @@ -838,41 +888,49 @@ Disconnects Puppeteer from the browser, but leaves the Chromium process running. Indicates that the browser is connected. #### browser.newPage() + - returns: <[Promise]<[Page]>> Promise which resolves to a new [Page] object. The [Page] is created in a default browser context. #### browser.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. In case of multiple browser contexts, the method will return an array with all the pages in all browser contexts. #### browser.process() + - returns: Spawned browser process. Returns `null` if the browser instance was created with [`puppeteer.connect`](#puppeteerconnectoptions) method. #### browser.target() + - returns: <[Target]> A target associated with the browser. #### browser.targets() + - 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. #### browser.userAgent() + - returns: <[Promise]<[string]>> Promise which resolves to the browser's original user agent. > **NOTE** Pages can override browser user agent with [page.setUserAgent](#pagesetuseragentuseragent) #### 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.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. @@ -881,12 +939,16 @@ the method will return an array with all the targets in all browser contexts. 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.waitForTarget(target => target.url() === 'https://www.example.com/'); +const newWindowTarget = await browser.waitForTarget( + (target) => target.url() === 'https://www.example.com/' +); ``` #### browser.wsEndpoint() + - returns: <[string]> Browser websocket url. Browser websocket endpoint which can be used as an argument to @@ -896,7 +958,7 @@ You can find the `webSocketDebuggerUrl` from `http://${host}:${port}/json/versio ### class: BrowserContext -* extends: [EventEmitter](#class-eventemitter) +- extends: [EventEmitter](#class-eventemitter) BrowserContexts provide a way to operate multiple independent browser sessions. When a browser is launched, it has a single BrowserContext used by default. The method `browser.newPage()` creates a page in the default browser context. @@ -919,26 +981,31 @@ await context.close(); ``` #### event: 'targetchanged' + - <[Target]> Emitted when the url of a target inside the browser context changes. #### event: 'targetcreated' + - <[Target]> Emitted when a new target is created inside the browser context, 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). #### event: 'targetdestroyed' + - <[Target]> Emitted when a target inside the browser context is destroyed, for example when a page is closed. #### browserContext.browser() + - returns: <[Browser]> The browser this browser context belongs to. #### browserContext.clearPermissionOverrides() + - returns: <[Promise]> Clears all permission overrides for the browser context. @@ -951,6 +1018,7 @@ context.clearPermissionOverrides(); ``` #### browserContext.close() + - returns: <[Promise]> Closes the browser context. All the targets that belong to the browser context @@ -959,6 +1027,7 @@ will be closed. > **NOTE** only incognito browser contexts can be closed. #### browserContext.isIncognito() + - returns: <[boolean]> Returns whether BrowserContext is incognito. @@ -967,50 +1036,52 @@ The default browser context is the only non-incognito browser context. > **NOTE** the default browser context cannot be closed. #### browserContext.newPage() + - returns: <[Promise]<[Page]>> Creates a new page in the browser context. - #### browserContext.overridePermissions(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'` + - `'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.defaultBrowserContext(); await context.overridePermissions('https://html5demos.com', ['geolocation']); ``` - #### 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.targets() + - returns: <[Array]<[Target]>> An array of all active targets inside the browser context. #### browserContext.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. @@ -1019,18 +1090,22 @@ An array of all active targets inside the browser context. This searches for a target in this specific browser context. 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 browserContext.waitForTarget(target => target.url() === 'https://www.example.com/'); +const newWindowTarget = await browserContext.waitForTarget( + (target) => target.url() === 'https://www.example.com/' +); ``` ### class: Page -* extends: [EventEmitter](#class-eventemitter) +- extends: [EventEmitter](#class-eventemitter) Page provides methods to interact with a single tab or [extension background page](https://developer.chrome.com/extensions/background_pages) 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'); @@ -1048,6 +1123,7 @@ any of the [`EventEmitter`](#class-eventemitter) methods, such as `on`, `once` or `off`. This example logs a message for a single page `load` event: + ```js page.once('load', () => console.log('Page loaded!')); ``` @@ -1068,6 +1144,7 @@ page.off('request', logRequest); Emitted when the page closes. #### 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. @@ -1075,8 +1152,9 @@ Emitted when JavaScript within the page calls one of console API methods, e.g. ` The arguments passed into `console.log` appear as arguments on the event handler. An example of handling `console` event: + ```js -page.on('console', msg => { +page.on('console', (msg) => { for (let i = 0; i < msg.args().length; ++i) console.log(`${i}: ${msg.args()[i]}`); }); @@ -1084,6 +1162,7 @@ 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. @@ -1093,6 +1172,7 @@ Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` o Emitted when the JavaScript [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) event is dispatched. #### event: 'error' + - <[Error]> Emitted when the page crashes. @@ -1100,16 +1180,19 @@ 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. @@ -1119,6 +1202,7 @@ Emitted when a frame is navigated to a new url. 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 @@ -1128,36 +1212,40 @@ Emitted when the JavaScript code makes a call to `console.timeStamp`. For the li of metrics see `page.metrics`. #### event: 'pageerror' + - <[Error]> The exception message Emitted when an uncaught exception happens within the page. #### event: 'popup' + - <[Page]> Page corresponding to "popup" window Emitted when the page opens a new tab or window. ```js const [popup] = await Promise.all([ - new Promise(resolve => page.once('popup', resolve)), + new Promise((resolve) => page.once('popup', resolve)), page.click('a[target=_blank]'), ]); ``` ```js const [popup] = await Promise.all([ - new Promise(resolve => page.once('popup', resolve)), + new Promise((resolve) => page.once('popup', resolve)), page.evaluate(() => window.open('https://example.com')), ]); ``` #### event: 'request' + - <[HTTPRequest]> Emitted when a page issues a request. The [HTTPRequest] object is read-only. In order to intercept and mutate requests, see `page.setRequestInterception`. #### event: 'requestfailed' + - <[HTTPRequest]> Emitted when a request fails, for example by timing out. @@ -1165,26 +1253,31 @@ Emitted when a request fails, for example by timing out. > **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with [`'requestfinished'`](#event-requestfinished) event and not with [`'requestfailed'`](#event-requestfailed). #### event: 'requestfinished' + - <[HTTPRequest]> Emitted when a request finishes successfully. #### event: 'response' + - <[HTTPResponse]> Emitted when a [HTTPResponse] is received. #### event: 'workercreated' + - <[WebWorker]> Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned by the page. #### event: 'workerdestroyed' + - <[WebWorker]> Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is terminated. #### page.$(selector) + - `selector` <[string]> A [selector] to query page for - returns: <[Promise]> @@ -1193,6 +1286,7 @@ The method runs `document.querySelector` within the page. If no element matches Shortcut for [page.mainFrame().$(selector)](#frameselector). #### page.$$(selector) + - `selector` <[string]> A [selector] to query page for - returns: <[Promise]<[Array]<[ElementHandle]>>> @@ -1201,6 +1295,7 @@ The method runs `document.querySelectorAll` within the page. If no elements matc Shortcut for [page.mainFrame().$$(selector)](#frameselector-1). #### page.$$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` @@ -1211,15 +1306,19 @@ This method runs `Array.from(document.querySelectorAll(selector))` within the pa If `pageFunction` returns a [Promise], then `page.$$eval` would wait for the promise to resolve and return its value. Examples: + ```js -const divCount = await page.$$eval('div', divs => divs.length); +const divCount = await page.$$eval('div', (divs) => divs.length); ``` ```js -const options = await page.$$eval('div > span.options', options => options.map(option => option.textContent)); +const options = await page.$$eval('div > span.options', (options) => + options.map((option) => option.textContent) +); ``` #### page.$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` @@ -1230,15 +1329,17 @@ This method runs `document.querySelector` within the page and passes it as the f 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); +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.$x(expression) + - `expression` <[string]> Expression to [evaluate](https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate). - returns: <[Promise]<[Array]<[ElementHandle]>>> @@ -1247,9 +1348,11 @@ The method evaluates the XPath expression relative to the page document as its c Shortcut for [page.mainFrame().$x(expression)](#framexexpression) #### page.accessibility + - returns: <[Accessibility]> #### 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). @@ -1262,6 +1365,7 @@ Adds a `