puppeteer-core
Version:
A high-level API to control headless Chrome over the DevTools Protocol
1,293 lines (1,143 loc) • 159 kB
TypeScript
// This file is generated by /doclint/generate_types/index.js
import { ChildProcess } from 'child_process';
import { EventEmitter } from 'events';
/**
* Can be converted to JSON
*/
interface Serializable {}
interface ConnectionTransport {}
/**
* This methods attaches Puppeteer to an existing Chromium instance.
* @param options
*/
export function connect(options: ConnectOptions) : Promise<Browser>;
/**
* @param options
*/
export function createBrowserFetcher(options?: CreateBrowserFetcherOptions) : BrowserFetcher;
/**
* The default flags that Chromium will be launched with.
* @param options Set of configurable options to set on the browser. Can have the following fields:
*/
export function defaultArgs(options?: DefaultArgsOptions) : Array<string>;
/**
* @returns A path where Puppeteer expects to find bundled Chromium. Chromium might not exist there if the download was skipped with `PUPPETEER_SKIP_CHROMIUM_DOWNLOAD`.
*/
export function executablePath() : string;
/**
* You can use `ignoreDefaultArgs` to filter out `--mute-audio` from default arguments:
* ```js
* const browser = await puppeteer.launch({
* ignoreDefaultArgs: ['--mute-audio']
* });
* ```
*
* **NOTE** Puppeteer 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 or Dev Channel build is suggested.
* In puppeteer.launch([options]) above, any mention of Chromium also applies to Chrome.
* See `this article` for a description of the differences between Chromium and Chrome. `This article` describes some differences for Linux users.
* @param options Set of configurable options to set on the browser. Can have the following fields:
* @returns Promise which resolves to browser instance.
*/
export function launch(options?: LaunchOptions) : Promise<Browser>;
/**
* 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.
* An example of using BrowserFetcher to download a specific version of Chromium and running
* Puppeteer against it:
* ```js
* const browserFetcher = puppeteer.createBrowserFetcher();
* const revisionInfo = await browserFetcher.download('533271');
* 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.
*/
export interface BrowserFetcher {
/**
* The method initiates a HEAD request to check if the revision is available.
* @param revision a revision to check availability.
* @returns returns `true` if the revision could be downloaded from the host.
*/
canDownload(revision: string): Promise<boolean>;
/**
* The method initiates a GET request to download the revision from the host.
* @param revision a revision to download.
* @param progressCallback A function that will be called with two arguments:
* @returns Resolves with revision information when the revision is downloaded and extracted
*/
download(revision: string, progressCallback?: (downloadedBytes : number, totalBytes : number, ...args: any[]) => void): Promise<BrowserFetcherDownload>;
/**
* @returns A list of all revisions available locally on disk.
*/
localRevisions(): Promise<Array<string>>;
/**
* @returns One of `mac`, `linux`, `win32` or `win64`.
*/
platform(): string;
/**
* @param revision a revision to remove. The method will throw if the revision has not been downloaded.
* @returns Resolves when the revision has been removed.
*/
remove(revision: string): Promise<void>;
/**
* @param revision a revision to get info for.
*/
revisionInfo(revision: string): BrowserFetcherRevisionInfo;
}
/**
* A Browser is created when Puppeteer connects to a Chromium instance, either through `puppeteer.launch` or `puppeteer.connect`.
* 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();
* });
* ```
*/
export interface Browser extends EventEmitter {
on(event: 'disconnected', listener: (arg0 : void) => void): this;
/**
* Emitted when the url of a target changes.
*
* **NOTE** This includes target changes in incognito browser contexts.
*/
on(event: 'targetchanged', listener: (arg0 : Target) => void): this;
/**
* Emitted when a target is created, for example when a new page is opened by `window.open` or `browser.newPage`.
*
* **NOTE** This includes target creations in incognito browser contexts.
*/
on(event: 'targetcreated', listener: (arg0 : Target) => void): this;
/**
* Emitted when a target is destroyed, for example when a page is closed.
*
* **NOTE** This includes target destructions in incognito browser contexts.
*/
on(event: 'targetdestroyed', listener: (arg0 : Target) => void): this;
once(event: 'disconnected', listener: (arg0 : void) => void): this;
/**
* Emitted when the url of a target changes.
*
* **NOTE** This includes target changes in incognito browser contexts.
*/
once(event: 'targetchanged', listener: (arg0 : Target) => void): this;
/**
* Emitted when a target is created, for example when a new page is opened by `window.open` or `browser.newPage`.
*
* **NOTE** This includes target creations in incognito browser contexts.
*/
once(event: 'targetcreated', listener: (arg0 : Target) => void): this;
/**
* Emitted when a target is destroyed, for example when a page is closed.
*
* **NOTE** This includes target destructions in incognito browser contexts.
*/
once(event: 'targetdestroyed', listener: (arg0 : Target) => void): this;
addListener(event: 'disconnected', listener: (arg0 : void) => void): this;
/**
* Emitted when the url of a target changes.
*
* **NOTE** This includes target changes in incognito browser contexts.
*/
addListener(event: 'targetchanged', listener: (arg0 : Target) => void): this;
/**
* Emitted when a target is created, for example when a new page is opened by `window.open` or `browser.newPage`.
*
* **NOTE** This includes target creations in incognito browser contexts.
*/
addListener(event: 'targetcreated', listener: (arg0 : Target) => void): this;
/**
* Emitted when a target is destroyed, for example when a page is closed.
*
* **NOTE** This includes target destructions in incognito browser contexts.
*/
addListener(event: 'targetdestroyed', listener: (arg0 : Target) => void): this;
/**
* Returns an array of all open browser contexts. In a newly created browser, this will return
* a single instance of BrowserContext.
*/
browserContexts(): Array<BrowserContext>;
/**
* 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.
*/
close(): Promise<void>;
/**
* Creates a new incognito browser context. This won't share cookies/cache with other browser contexts.
* ```js
* const browser = await puppeteer.launch();
* // Create a new incognito browser context.
* const context = await browser.createIncognitoBrowserContext();
* // Create a new page in a pristine context.
* const page = await context.newPage();
* // Do stuff
* await page.goto('https://example.com');
* ```
*/
createIncognitoBrowserContext(): Promise<BrowserContext>;
/**
* Returns the default browser context. The default browser context can not be closed.
*/
defaultBrowserContext(): BrowserContext;
/**
* 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.
*/
disconnect(): void;
/**
* Promise which resolves to a new Page object. The Page is created in a default browser context.
*/
newPage(): Promise<Page>;
/**
* 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.
* @returns 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().
*/
pages(): Promise<Array<Page>>;
/**
* @returns Spawned browser process. Returns `null` if the browser instance was created with `puppeteer.connect` method.
*/
process(): null|ChildProcess;
/**
* A target associated with the browser.
*/
target(): 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.
*/
targets(): Array<Target>;
/**
* **NOTE** Pages can override browser user agent with page.setUserAgent
* @returns Promise which resolves to the browser's original user agent.
*/
userAgent(): Promise<string>;
/**
* **NOTE** the format of browser.version() might change with future releases of Chromium.
* @returns For headless Chromium, this is similar to `HeadlessChrome/61.0.3153.0`. For non-headless, this is similar to `Chrome/61.0.3153.0`.
*/
version(): Promise<string>;
/**
* 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/');
* ```
* @param predicate A function to be run for every target
* @param options
* @returns Promise which resolves to the first target found that matches the `predicate` function.
*/
waitForTarget(predicate: (arg0 : Target, ...args: any[]) => boolean, options?: BrowserWaitForTargetOptions): Promise<Target>;
/**
* Browser websocket endpoint which can be used as an argument to
* puppeteer.connect. The format is `ws://${host}:${port}/devtools/browser/<id>`
* You can find the `webSocketDebuggerUrl` from `http://${host}:${port}/json/version`. Learn more about the devtools protocol and the browser endpoint.
* @returns Browser websocket url.
*/
wsEndpoint(): string;
}
/**
* 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.
* If a page opens another page, e.g. with a `window.open` call, the popup will belong to the parent page's browser
* context.
* Puppeteer allows creation of "incognito" browser contexts with `browser.createIncognitoBrowserContext()` method.
* "Incognito" browser contexts don't write any browsing data to disk.
* ```js
* // Create a new incognito browser context
* const context = await browser.createIncognitoBrowserContext();
* // Create a new page inside context.
* const page = await context.newPage();
* // ... do stuff with page ...
* await page.goto('https://example.com');
* // Dispose context once it's no longer needed.
* await context.close();
* ```
*/
export interface BrowserContext extends EventEmitter {
/**
* Emitted when the url of a target inside the browser context changes.
*/
on(event: 'targetchanged', listener: (arg0 : Target) => void): this;
/**
* Emitted when a new target is created inside the browser context, for example when a new page is opened by `window.open` or `browserContext.newPage`.
*/
on(event: 'targetcreated', listener: (arg0 : Target) => void): this;
/**
* Emitted when a target inside the browser context is destroyed, for example when a page is closed.
*/
on(event: 'targetdestroyed', listener: (arg0 : Target) => void): this;
/**
* Emitted when the url of a target inside the browser context changes.
*/
once(event: 'targetchanged', listener: (arg0 : Target) => void): this;
/**
* Emitted when a new target is created inside the browser context, for example when a new page is opened by `window.open` or `browserContext.newPage`.
*/
once(event: 'targetcreated', listener: (arg0 : Target) => void): this;
/**
* Emitted when a target inside the browser context is destroyed, for example when a page is closed.
*/
once(event: 'targetdestroyed', listener: (arg0 : Target) => void): this;
/**
* Emitted when the url of a target inside the browser context changes.
*/
addListener(event: 'targetchanged', listener: (arg0 : Target) => void): this;
/**
* Emitted when a new target is created inside the browser context, for example when a new page is opened by `window.open` or `browserContext.newPage`.
*/
addListener(event: 'targetcreated', listener: (arg0 : Target) => void): this;
/**
* Emitted when a target inside the browser context is destroyed, for example when a page is closed.
*/
addListener(event: 'targetdestroyed', listener: (arg0 : Target) => void): this;
/**
* The browser this browser context belongs to.
*/
browser(): Browser;
/**
* Clears all permission overrides for the browser context.
* ```js
* const context = browser.defaultBrowserContext();
* context.overridePermissions('https://example.com', ['clipboard-read']);
* // do stuff ..
* context.clearPermissionOverrides();
* ```
*/
clearPermissionOverrides(): Promise<void>;
/**
* Closes the browser context. All the targets that belong to the browser context
* will be closed.
*
* **NOTE** only incognito browser contexts can be closed.
*/
close(): Promise<void>;
/**
* Returns whether BrowserContext is incognito.
* The default browser context is the only non-incognito browser context.
*
* **NOTE** the default browser context cannot be closed.
*/
isIncognito(): boolean;
/**
* Creates a new page in the browser context.
*/
newPage(): Promise<Page>;
/**
* ```js
* const context = browser.defaultBrowserContext();
* await context.overridePermissions('https://html5demos.com', ['geolocation']);
* ```
* @param origin The origin to grant permissions to, e.g. "https://example.com".
* @param permissions 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:
*/
overridePermissions(origin: string, permissions: Array<string>): Promise<void>;
/**
* An array of all pages inside the browser context.
* @returns 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().
*/
pages(): Promise<Array<Page>>;
/**
* An array of all active targets inside the browser context.
*/
targets(): Array<Target>;
/**
* 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/');
* ```
* @param predicate A function to be run for every target
* @param options
* @returns Promise which resolves to the first target found that matches the `predicate` function.
*/
waitForTarget(predicate: (arg0 : Target, ...args: any[]) => boolean, options?: BrowserContextWaitForTargetOptions): Promise<Target>;
}
/**
* Page provides methods to interact with a single tab or extension background page 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();
* });
* ```
* The Page class emits various events (described below) which can be handled using any of Node's native `EventEmitter` methods, such as `on`, `once` or `removeListener`.
* This example logs a message for a single page `load` event:
* ```js
* page.once('load', () => console.log('Page loaded!'));
* ```
* To unsubscribe from events use the `removeListener` method:
* ```js
* function logRequest(interceptedRequest) {
* console.log('A request was made:', interceptedRequest.url());
* }
* page.on('request', logRequest);
* // Sometime later...
* page.removeListener('request', logRequest);
* ```
*/
export interface Page extends EventEmitter {
/**
* event: 'close'
* Emitted when the page closes.
*/
on(event: 'close', listener: (arg0 : void) => void): this;
/**
* 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'}));
* ```
*/
on(event: 'console', listener: (arg0 : ConsoleMessage) => void): this;
/**
* Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Puppeteer can respond to the dialog via Dialog's accept or dismiss methods.
*/
on(event: 'dialog', listener: (arg0 : Dialog) => void): this;
/**
* event: 'domcontentloaded'
* Emitted when the JavaScript `DOMContentLoaded` event is dispatched.
*/
on(event: 'domcontentloaded', listener: (arg0 : void) => void): this;
/**
* Emitted when the page crashes.
*
* **NOTE** `error` event has a special meaning in Node, see error events for details.
*/
on(event: 'error', listener: (arg0 : Error) => void): this;
/**
* Emitted when a frame is attached.
*/
on(event: 'frameattached', listener: (arg0 : Frame) => void): this;
/**
* Emitted when a frame is detached.
*/
on(event: 'framedetached', listener: (arg0 : Frame) => void): this;
/**
* Emitted when a frame is navigated to a new url.
*/
on(event: 'framenavigated', listener: (arg0 : Frame) => void): this;
/**
* event: 'load'
* Emitted when the JavaScript `load` event is dispatched.
*/
on(event: 'load', listener: (arg0 : void) => void): this;
/**
* Emitted when the JavaScript code makes a call to `console.timeStamp`. For the list
* of metrics see `page.metrics`.
*/
on(event: 'metrics', listener: (arg0 : PageMetricsPayload) => void): this;
/**
* Emitted when an uncaught exception happens within the page.
*/
on(event: 'pageerror', listener: (arg0 : Error) => void): this;
/**
* Emitted when the page opens a new tab or window.
* ```js
* const [popup] = await Promise.all([
* 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)),
* page.evaluate(() => window.open('https://example.com')),
* ]);
* ```
*/
on(event: 'popup', listener: (arg0 : Page) => void): this;
/**
* Emitted when a page issues a request. The request object is read-only.
* In order to intercept and mutate requests, see `page.setRequestInterception`.
*/
on(event: 'request', listener: (arg0 : Request) => void): this;
/**
* Emitted when a request fails, for example by timing out.
*/
on(event: 'requestfailed', listener: (arg0 : Request) => void): this;
/**
* Emitted when a request finishes successfully.
*/
on(event: 'requestfinished', listener: (arg0 : Request) => void): this;
/**
* Emitted when a response is received.
*/
on(event: 'response', listener: (arg0 : Response) => void): this;
/**
* Emitted when a dedicated WebWorker is spawned by the page.
*/
on(event: 'workercreated', listener: (arg0 : Worker) => void): this;
/**
* Emitted when a dedicated WebWorker is terminated.
*/
on(event: 'workerdestroyed', listener: (arg0 : Worker) => void): this;
/**
* event: 'close'
* Emitted when the page closes.
*/
once(event: 'close', listener: (arg0 : void) => void): this;
/**
* 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'}));
* ```
*/
once(event: 'console', listener: (arg0 : ConsoleMessage) => void): this;
/**
* Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Puppeteer can respond to the dialog via Dialog's accept or dismiss methods.
*/
once(event: 'dialog', listener: (arg0 : Dialog) => void): this;
/**
* event: 'domcontentloaded'
* Emitted when the JavaScript `DOMContentLoaded` event is dispatched.
*/
once(event: 'domcontentloaded', listener: (arg0 : void) => void): this;
/**
* Emitted when the page crashes.
*
* **NOTE** `error` event has a special meaning in Node, see error events for details.
*/
once(event: 'error', listener: (arg0 : Error) => void): this;
/**
* Emitted when a frame is attached.
*/
once(event: 'frameattached', listener: (arg0 : Frame) => void): this;
/**
* Emitted when a frame is detached.
*/
once(event: 'framedetached', listener: (arg0 : Frame) => void): this;
/**
* Emitted when a frame is navigated to a new url.
*/
once(event: 'framenavigated', listener: (arg0 : Frame) => void): this;
/**
* event: 'load'
* Emitted when the JavaScript `load` event is dispatched.
*/
once(event: 'load', listener: (arg0 : void) => void): this;
/**
* Emitted when the JavaScript code makes a call to `console.timeStamp`. For the list
* of metrics see `page.metrics`.
*/
once(event: 'metrics', listener: (arg0 : PageMetricsPayload) => void): this;
/**
* Emitted when an uncaught exception happens within the page.
*/
once(event: 'pageerror', listener: (arg0 : Error) => void): this;
/**
* Emitted when the page opens a new tab or window.
* ```js
* const [popup] = await Promise.all([
* 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)),
* page.evaluate(() => window.open('https://example.com')),
* ]);
* ```
*/
once(event: 'popup', listener: (arg0 : Page) => void): this;
/**
* Emitted when a page issues a request. The request object is read-only.
* In order to intercept and mutate requests, see `page.setRequestInterception`.
*/
once(event: 'request', listener: (arg0 : Request) => void): this;
/**
* Emitted when a request fails, for example by timing out.
*/
once(event: 'requestfailed', listener: (arg0 : Request) => void): this;
/**
* Emitted when a request finishes successfully.
*/
once(event: 'requestfinished', listener: (arg0 : Request) => void): this;
/**
* Emitted when a response is received.
*/
once(event: 'response', listener: (arg0 : Response) => void): this;
/**
* Emitted when a dedicated WebWorker is spawned by the page.
*/
once(event: 'workercreated', listener: (arg0 : Worker) => void): this;
/**
* Emitted when a dedicated WebWorker is terminated.
*/
once(event: 'workerdestroyed', listener: (arg0 : Worker) => void): this;
/**
* event: 'close'
* Emitted when the page closes.
*/
addListener(event: 'close', listener: (arg0 : void) => void): this;
/**
* 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'}));
* ```
*/
addListener(event: 'console', listener: (arg0 : ConsoleMessage) => void): this;
/**
* Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Puppeteer can respond to the dialog via Dialog's accept or dismiss methods.
*/
addListener(event: 'dialog', listener: (arg0 : Dialog) => void): this;
/**
* event: 'domcontentloaded'
* Emitted when the JavaScript `DOMContentLoaded` event is dispatched.
*/
addListener(event: 'domcontentloaded', listener: (arg0 : void) => void): this;
/**
* Emitted when the page crashes.
*
* **NOTE** `error` event has a special meaning in Node, see error events for details.
*/
addListener(event: 'error', listener: (arg0 : Error) => void): this;
/**
* Emitted when a frame is attached.
*/
addListener(event: 'frameattached', listener: (arg0 : Frame) => void): this;
/**
* Emitted when a frame is detached.
*/
addListener(event: 'framedetached', listener: (arg0 : Frame) => void): this;
/**
* Emitted when a frame is navigated to a new url.
*/
addListener(event: 'framenavigated', listener: (arg0 : Frame) => void): this;
/**
* event: 'load'
* Emitted when the JavaScript `load` event is dispatched.
*/
addListener(event: 'load', listener: (arg0 : void) => void): this;
/**
* Emitted when the JavaScript code makes a call to `console.timeStamp`. For the list
* of metrics see `page.metrics`.
*/
addListener(event: 'metrics', listener: (arg0 : PageMetricsPayload) => void): this;
/**
* Emitted when an uncaught exception happens within the page.
*/
addListener(event: 'pageerror', listener: (arg0 : Error) => void): this;
/**
* Emitted when the page opens a new tab or window.
* ```js
* const [popup] = await Promise.all([
* 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)),
* page.evaluate(() => window.open('https://example.com')),
* ]);
* ```
*/
addListener(event: 'popup', listener: (arg0 : Page) => void): this;
/**
* Emitted when a page issues a request. The request object is read-only.
* In order to intercept and mutate requests, see `page.setRequestInterception`.
*/
addListener(event: 'request', listener: (arg0 : Request) => void): this;
/**
* Emitted when a request fails, for example by timing out.
*/
addListener(event: 'requestfailed', listener: (arg0 : Request) => void): this;
/**
* Emitted when a request finishes successfully.
*/
addListener(event: 'requestfinished', listener: (arg0 : Request) => void): this;
/**
* Emitted when a response is received.
*/
addListener(event: 'response', listener: (arg0 : Response) => void): this;
/**
* Emitted when a dedicated WebWorker is spawned by the page.
*/
addListener(event: 'workercreated', listener: (arg0 : Worker) => void): this;
/**
* Emitted when a dedicated WebWorker is terminated.
*/
addListener(event: 'workerdestroyed', listener: (arg0 : Worker) => void): this;
/**
* The method runs `document.querySelector` within the page. If no element matches the selector, the return value resolves to `null`.
* Shortcut for page.mainFrame().$(selector).
* @param selector A selector to query page for
*/
$(selector: string): Promise<null|ElementHandle>;
/**
* The method runs `document.querySelectorAll` within the page. If no elements match the selector, the return value resolves to `[]`.
* Shortcut for page.mainFrame().$$(selector).
* @param selector A selector to query page for
*/
$$(selector: string): Promise<Array<ElementHandle>>;
/**
* This method runs `Array.from(document.querySelectorAll(selector))` 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);
* ```
* @param selector A selector to query page for
* @param pageFunction Function to be evaluated in browser context
* @param args Arguments to pass to `pageFunction`
* @returns Promise which resolves to the return value of `pageFunction`
*/
$$eval(selector: string, pageFunction: (arg0 : Array<Element>, ...args: any[]) => void, ...args: Array<Serializable|JSHandle>): Promise<Serializable>;
/**
* 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).
* @param selector A selector to query page for
* @param pageFunction Function to be evaluated in browser context
* @param args Arguments to pass to `pageFunction`
* @returns Promise which resolves to the return value of `pageFunction`
*/
$eval(selector: string, pageFunction: (arg0 : Element, ...args: any[]) => void, ...args: Array<Serializable|JSHandle>): Promise<Serializable>;
/**
* The method evaluates the XPath expression.
* Shortcut for page.mainFrame().$x(expression)
* @param expression Expression to evaluate.
*/
$x(expression: string): Promise<Array<ElementHandle>>;
accessibility: Accessibility;
/**
* Adds a `<script>` tag into the page with the desired url or content.
* Shortcut for page.mainFrame().addScriptTag(options).
* @param options
* @returns which resolves to the added tag when the script's onload fires or when the script content was injected into frame.
*/
addScriptTag(options: PageAddScriptTagOptions): Promise<ElementHandle>;
/**
* Adds a `<link rel="stylesheet">` tag into the page with the desired url or a `<style type="text/css">` tag with the content.
* Shortcut for page.mainFrame().addStyleTag(options).
* @param options
* @returns which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
*/
addStyleTag(options: PageAddStyleTagOptions): Promise<ElementHandle>;
/**
* Provide credentials for HTTP authentication.
* To disable authentication, pass `null`.
* @param credentials
*/
authenticate(credentials: null|PageAuthenticateOptions): Promise<void>;
/**
* Brings page to front (activates tab).
*/
bringToFront(): Promise<void>;
/**
* Get the browser the page belongs to.
*/
browser(): Browser;
/**
* Get the browser context that the page belongs to.
*/
browserContext(): BrowserContext;
/**
* This method fetches an element with `selector`, scrolls it into view if needed, and then uses page.mouse to click in the center of the element.
* If there's no element matching `selector`, the method throws an error.
* Bear in mind that if `click()` triggers a navigation event and there's a separate `page.waitForNavigation()` promise to be resolved, you may end up with a race condition that yields unexpected results. The correct pattern for click and wait for navigation is the following:
* ```javascript
* const [response] = await Promise.all([
* page.waitForNavigation(waitOptions),
* page.click(selector, clickOptions),
* ]);
* ```
* Shortcut for page.mainFrame().click(selector[, options]).
* @param selector A selector to search for element to click. If there are multiple elements satisfying the selector, the first will be clicked.
* @param options
* @returns Promise which resolves when the element matching `selector` is successfully clicked. The Promise will be rejected if there is no element matching `selector`.
*/
click(selector: string, options?: PageClickOptions): Promise<void>;
/**
* By default, `page.close()` **does not** run beforeunload handlers.
*
* **NOTE** if `runBeforeUnload` is passed as true, a `beforeunload` dialog might be summoned
* and should be handled manually via page's 'dialog' event.
* @param options
*/
close(options?: PageCloseOptions): Promise<void>;
/**
* Gets the full HTML contents of the page, including the doctype.
*/
content(): Promise<string>;
/**
* If no URLs are specified, this method returns cookies for the current page URL.
* If URLs are specified, only cookies for those URLs are returned.
* @param urls
*/
cookies(...urls: Array<string>): Promise<Array<PageCookies>>;
coverage: Coverage;
/**
* @param cookies
*/
deleteCookie(...cookies: Array<PageDeleteCookieOptions>): Promise<void>;
/**
* Emulates given device metrics and user agent. This method is a shortcut for calling two methods:
*
* page.setUserAgent(userAgent)
* page.setViewport(viewport)
*
* To aid emulation, puppeteer provides a list of device descriptors which can be obtained via the `require('puppeteer/DeviceDescriptors')` command.
* Below is an example of emulating an iPhone 6 in puppeteer:
* ```js
* const puppeteer = require('puppeteer');
* const devices = require('puppeteer/DeviceDescriptors');
* const iPhone = devices['iPhone 6'];
*
* puppeteer.launch().then(async browser => {
* const page = await browser.newPage();
* await page.emulate(iPhone);
* await page.goto('https://www.google.com');
* // other actions...
* await browser.close();
* });
* ```
* List of all available devices is available in the source code: DeviceDescriptors.js.
* @param options
*/
emulate(options: PageEmulateOptions): Promise<void>;
/**
* @param mediaType Changes the CSS media type of the page. The only allowed values are `'screen'`, `'print'` and `null`. Passing `null` disables media emulation.
*/
emulateMedia(mediaType: null|string): Promise<void>;
/**
* If the function passed to the `page.evaluate` returns a Promise, then `page.evaluate` would wait for the promise to resolve and return its value.
* If the function passed to the `page.evaluate` returns a non-Serializable value, then `page.evaluate` resolves to `undefined`.
* Passing arguments to `pageFunction`:
* ```js
* const result = await page.evaluate(x => {
* return Promise.resolve(8 * x);
* }, 7);
* console.log(result); // prints "56"
* ```
* A string can also be passed in instead of a function:
* ```js
* console.log(await page.evaluate('1 + 2')); // prints "3"
* const x = 10;
* console.log(await page.evaluate(`1 + ${x}`)); // prints "11"
* ```
* ElementHandle instances can be passed as arguments to the `page.evaluate`:
* ```js
* const bodyHandle = await page.$('body');
* const html = await page.evaluate(body => body.innerHTML, bodyHandle);
* await bodyHandle.dispose();
* ```
* Shortcut for page.mainFrame().evaluate(pageFunction, ...args).
* @param pageFunction Function to be evaluated in the page context
* @param args Arguments to pass to `pageFunction`
* @returns Promise which resolves to the return value of `pageFunction`
*/
evaluate(pageFunction: Function|string, ...args: Array<Serializable|JSHandle>): Promise<Serializable>;
/**
* The only difference between `page.evaluate` and `page.evaluateHandle` is that `page.evaluateHandle` returns in-page object (JSHandle).
* If the function passed to the `page.evaluateHandle` returns a Promise, then `page.evaluateHandle` would wait for the promise to resolve and return its value.
* A string can also be passed in instead of a function:
* ```js
* const aHandle = await page.evaluateHandle('document'); // Handle for the 'document'
* ```
* JSHandle instances can be passed as arguments to the `page.evaluateHandle`:
* ```js
* const aHandle = await page.evaluateHandle(() => document.body);
* const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle);
* console.log(await resultHandle.jsonValue());
* await resultHandle.dispose();
* ```
* Shortcut for page.mainFrame().executionContext().evaluateHandle(pageFunction, ...args).
* @param pageFunction Function to be evaluated in the page context
* @param args Arguments to pass to `pageFunction`
* @returns Promise which resolves to the return value of `pageFunction` as in-page object (JSHandle)
*/
evaluateHandle(pageFunction: Function|string, ...args: Array<Serializable|JSHandle>): Promise<JSHandle>;
/**
* Adds a function which would be invoked in one of the following scenarios:
*
* whenever the page is navigated
* whenever the child frame is attached or navigated. In this case, the function is invoked in the context of the newly attached frame
*
* The function is invoked after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed `Math.random`.
* An example of overriding the navigator.languages property before the page loads:
* ```js
* // preload.js
*
* // overwrite the `languages` property to use a custom getter
* Object.defineProperty(navigator, "languages", {
* get: function() {
* return ["en-US", "en", "bn"];
* }
* });
*
* // In your puppeteer script, assuming the preload.js file is in same folder of our script
* const preloadFile = fs.readFileSync('./preload.js', 'utf8');
* await page.evaluateOnNewDocument(preloadFile);
* ```
* @param pageFunction Function to be evaluated in browser context
* @param args Arguments to pass to `pageFunction`
*/
evaluateOnNewDocument(pageFunction: Function|string, ...args: Array<Serializable>): Promise<void>;
/**
* The method adds a function called `name` on the page's `window` object.
* When called, the function executes `puppeteerFunction` in node.js and returns a Promise which resolves to the return value of `puppeteerFunction`.
* If the `puppeteerFunction` returns a Promise, it will be awaited.
*
* **NOTE** Functions installed via `page.exposeFunction` survive navigations.
*
* An example of adding an `md5` function into the page:
* ```js
* const puppeteer = require('puppeteer');
* const crypto = require('crypto');
*
* puppeteer.launch().then(async browser => {
* const page = await browser.newPage();
* page.on('console', msg => console.log(msg.text()));
* await page.exposeFunction('md5', text =>
* crypto.createHash('md5').update(text).digest('hex')
* );
* await page.evaluate(async () => {
* // use window.md5 to compute hashes
* const myString = 'PUPPETEER';
* const myHash = await window.md5(myString);
* console.log(`md5 of ${myString} is ${myHash}`);
* });
* await browser.close();
* });
* ```
* An example of adding a `window.readfile` function into the page:
* ```js
* const puppeteer = require('puppeteer');
* const fs = require('fs');
*
* puppeteer.launch().then(async browser => {
* const page = await browser.newPage();
* page.on('console', msg => console.log(msg.text()));
* await page.exposeFunction('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
* const content = await window.readfile('/etc/hosts');
* console.log(content);
* });
* await browser.close();
* });
*
* ```
* @param name Name of the function on the window object
* @param puppeteerFunction Callback function which will be called in Puppeteer's context.
*/
exposeFunction(name: string, puppeteerFunction: Function): Promise<void>;
/**
* This method fetches an element with `selector` and focuses it.
* If there's no element matching `selector`, the method throws an error.
* Shortcut for page.mainFrame().focus(selector).
* @param selector A selector of an element to focus. If there are multiple elements satisfying the selector, the first will be focused.
* @returns Promise which resolves when the element matching `selector` is successfully focused. The promise will be rejected if there is no element matching `selector`.
*/
focus(selector: string): Promise<void>;
/**
* @returns An array of all frames attached to the page.
*/
frames(): Array<Frame>;
/**
* Navigate to the previous page in history.
* @param options Navigation parameters which might have the following properties:
* @returns Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If
can not go back, resolves to `null`.
*/
goBack(options?: PageGoBackOptions): Promise<null|Response>;
/**
* Navigate to the next page in history.
* @param options Navigation parameters which might have the following properties:
* @returns Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If
can not go forward, resolves to `null`.
*/
goForward(options?: PageGoForwardOptions): Promise<null|Response>;
/**
* The `page.goto` will throw an error if:
*
* there's an SSL error (e.g. in case of self-signed certificates).
* target URL is invalid.
* the `timeout` is exceeded during navigation.
* the main resource failed to load.
*
*
* **NOTE** `page.goto` either throw or return a main resource response. The only exceptions are navigation to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.
*
*
* **NOTE** Headless mode doesn't support navigation to a PDF document. See the upstream issue.
*
* Shortcut for page.mainFrame().goto(url, options)
* @param url URL to navigate page to. The url should include scheme, e.g. `https://`.
* @param options Navigation parameters which might have the following properties:
* @returns Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
*/
goto(url: string, options?: PageGotoOptions): Promise<null|Response>;
/**
* This method fetches an element with `selector`, scrolls it into view if needed, and then uses page.mouse to hover over the center of the element.
* If there's no element matching `selector`, the method throws an error.
* Shortcut for page.mainFrame().hover(selector).
* @param selector A selector to search for element to hover. If there are multiple elements satisfying the selector, the first will be hovered.
* @returns Promise which resolves when the element matching `selector` is successfully hovered. Promise gets rejected if there's no element matching `selector`.
*/
hover(selector: string): Promise<void>;
/**
* Indicates that the page has been closed.
*/
isClosed(): boolean;
keyboard: Keyboard;
/**
* Page is guaranteed to have a main frame which persists during navigations.
* @returns The page's main frame.
*/
mainFrame(): Frame;
/**
* **NOTE** All timestamps are in monotonic time: monotonically increasing time in seconds since an arbitrary point in the past.
* @returns Object containing metrics as key/value pairs.
*/
metrics(): Promise<PageMetrics>;
mouse: Mouse;
/**
* **NOTE** Generating a pdf is currently only supported in Chrome headless.
*
* `page.pdf()` generates a pdf of the page with `print` css media. To generate a pdf with `screen` media, call page.emulateMedia('screen') before calling `page.pdf()`:
*
* **NOTE** By default, `page.pdf()` generates a pdf with modified colors for printing. Use the `-webkit-print-color-adjust` property to force rendering of exact colors.
*
* ```js
* // Generates a PDF with 'screen' media type.
* await page.emulateMedia('screen');
* await page.pdf({path: 'page.pdf'});
* ```
* The `width`, `height`, and `margin` options accept values labeled with units. Unlabeled values are treated as pixels.
* A few examples:
*
* `page.pdf({width: 100})` - prints with width set to 100 pixels
* `page.pdf({width: '100px'})` - prints with width set to 100 pixels
* `page.pdf({width: '10cm'})` - prints with width set to 10 centimeters.
*
* All possible units are:
*
* `px` - pixel
* `in` - inch
* `cm` - centimeter
* `mm` - millimeter
*
* The `format` options are:
*
* `Letter`: 8.5in x 11in
* `Legal`: 8.5in x 14in
* `Tabloid`: 11in x 17in
* `Ledger`: 17in x 11in
* `A0`: 33.1in x 46.8in
* `A1`: 23.4in x 33.1in
* `A2`: 16.5in x 23.4in
* `A3`: 11.7in x 16.5in
* `A4`: 8.27in x 11.7in
* `A5`: 5.83in x 8.27in
* `A6`: 4.13in x 5.83in
*
*
* **NOTE** `headerTemplate` and `footerTemplate` markup have the following limitations:
*
* Script tags inside templates are not evaluated.
* Page styles are not visible inside templates.
* @param options Options object which might have the following properties:
* @returns Promise which resolves with PDF buffer.
*/
pdf(options?: PagePdfOptions): Promise<Buffer>;
/**
* The method iterates the JavaScript heap and finds all the objects with the given prototype.
* ```js
* // Create a Map object
* await page.evaluate(() => window.map = new Map());
* // Get a handle to the Map object prototype
* const mapPrototype = await page.evaluateHandle(() => Map.prototype);
* // Query all map instances into an array
* const mapInstances = await page.queryObjects(mapPrototype);
* // Count amount of map objects in heap
* const count = await page.evaluate(maps => maps.length, mapInstances);
* await mapInstances.dispose();
* await mapPrototype.dispose();
* ```
* Shortcut for page.mainFrame().executionContext().queryObjects(prototypeHandle).
* @param prototypeHandle A handle to the object prototype.
* @returns Promise which resolves to a handle to an array of objects with this prototype.
*/
queryObjects(prototypeHandle: JSHandle): Promise<JSHandle>;
/**
* @param options Navigation parameters which might have the following properties:
* @returns Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
*/
reload(options?: PageReloadOptions): Promise<Response>;
/**
* **NOTE** Screenshots take at least 1/6 second on OS X. See https://crbug.com/741689 for discussion.
* @param options Options object which might have the following properties:
* @returns Promise which resolves to buffer or a base64 string (depending on the value of `encoding`) with captured screenshot.
*/
screenshot(options?: PageScreenshotOptions): Promise<string|Buffer>;
/**
* Triggers a `change` and `input` event once all the provided options have been selected.
* If there's no `<select>` element matching `selector`, the method throws an error.
* ```js
* page.select('select#colors', 'blue'); // single selection
* page.select('select#colors', 'red', 'green', 'blue'); // multiple selections
* ```
* Shortcut f