///
import { ChildProcess } from 'child_process';
import { Protocol } from 'devtools-protocol';
import { ProtocolMapping } from 'devtools-protocol/types/protocol-mapping.js';
import type { Readable } from 'stream';
/**
* The Accessibility class provides methods for inspecting Chromium's
* accessibility tree. The accessibility tree is used by assistive technology
* such as {@link https://en.wikipedia.org/wiki/Screen_reader | screen readers} or
* {@link https://en.wikipedia.org/wiki/Switch_access | switches}.
*
* @remarks
*
* Accessibility is a very platform-specific thing. On different platforms,
* there are different screen readers that might have wildly different output.
*
* Blink - Chrome's rendering engine - has a concept of "accessibility tree",
* which is then translated into different platform-specific APIs. Accessibility
* namespace gives users access to the Blink Accessibility Tree.
*
* Most of the accessibility tree gets filtered out when converting from Blink
* AX Tree to Platform-specific AX-Tree or by assistive technologies themselves.
* By default, Puppeteer tries to approximate this filtering, exposing only
* the "interesting" nodes of the tree.
*
* @public
*/
export declare class Accessibility {
private _client;
/**
* @internal
*/
constructor(client: CDPSession);
/**
* Captures the current state of the accessibility tree.
* The returned object represents the root accessible node of the page.
*
* @remarks
*
* **NOTE** The Chromium accessibility tree contains nodes that go unused on
* most platforms and by most screen readers. Puppeteer will discard them as
* well for an easier to process tree, unless `interestingOnly` is set to
* `false`.
*
* @example
* An example of dumping the entire accessibility tree:
* ```js
* const snapshot = await page.accessibility.snapshot();
* console.log(snapshot);
* ```
*
* @example
* An example of logging the focused node's name:
* ```js
* const snapshot = await page.accessibility.snapshot();
* const node = findFocusedNode(snapshot);
* console.log(node && node.name);
*
* function findFocusedNode(node) {
* if (node.focused)
* return node;
* for (const child of node.children || []) {
* const foundNode = findFocusedNode(child);
* return foundNode;
* }
* return null;
* }
* ```
*
* @returns An AXNode object representing the snapshot.
*
*/
snapshot(options?: SnapshotOptions): Promise;
private serializeTree;
private collectInterestingNodes;
}
/**
* @public
*/
export declare type ActionResult = 'continue' | 'abort' | 'respond';
/**
* @public
*/
export declare interface BoundingBox extends Point {
/**
* the width of the element in pixels.
*/
width: number;
/**
* the height of the element in pixels.
*/
height: number;
}
/**
* @public
*/
export declare interface BoxModel {
content: Point[];
padding: Point[];
border: Point[];
margin: Point[];
width: number;
height: number;
}
/**
* A Browser is created when Puppeteer connects to a Chromium instance, either through
* {@link PuppeteerNode.launch} or {@link Puppeteer.connect}.
*
* @remarks
*
* The Browser class extends from Puppeteer's {@link EventEmitter} class and will
* emit various events which are documented in the {@link BrowserEmittedEvents} enum.
*
* @example
*
* An example of using a {@link Browser} to create a {@link Page}:
* ```js
* const puppeteer = require('puppeteer');
*
* (async () => {
* const browser = await puppeteer.launch();
* const page = await browser.newPage();
* await page.goto('https://example.com');
* await browser.close();
* })();
* ```
*
* @example
*
* An example of disconnecting from and reconnecting to a {@link Browser}:
* ```js
* const puppeteer = require('puppeteer');
*
* (async () => {
* const browser = await puppeteer.launch();
* // 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();
* })();
* ```
*
* @public
*/
export declare class Browser extends EventEmitter {
/**
* @internal
*/
static create(connection: Connection, contextIds: string[], ignoreHTTPSErrors: boolean, defaultViewport?: Viewport | null, process?: ChildProcess, closeCallback?: BrowserCloseCallback, targetFilterCallback?: TargetFilterCallback, isPageTargetCallback?: IsPageTargetCallback): Promise;
private _ignoreHTTPSErrors;
private _defaultViewport?;
private _process?;
private _connection;
private _closeCallback;
private _targetFilterCallback;
private _isPageTargetCallback;
private _defaultContext;
private _contexts;
private _screenshotTaskQueue;
private _ignoredTargets;
/**
* @internal
* Used in Target.ts directly so cannot be marked private.
*/
_targets: Map;
/**
* @internal
*/
constructor(connection: Connection, contextIds: string[], ignoreHTTPSErrors: boolean, defaultViewport?: Viewport | null, process?: ChildProcess, closeCallback?: BrowserCloseCallback, targetFilterCallback?: TargetFilterCallback, isPageTargetCallback?: IsPageTargetCallback);
/**
* The spawned browser process. Returns `null` if the browser instance was created with
* {@link Puppeteer.connect}.
*/
process(): ChildProcess | null;
/**
* @internal
*/
_setIsPageTargetCallback(isPageTargetCallback?: IsPageTargetCallback): void;
/**
* @internal
*/
_getIsPageTargetCallback(): IsPageTargetCallback | undefined;
/**
* Creates a new incognito browser context. This won't share cookies/cache with other
* browser contexts.
*
* @example
* ```js
* (async () => {
* 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(options?: BrowserContextOptions): Promise;
/**
* Returns an array of all open browser contexts. In a newly created browser, this will
* return a single instance of {@link BrowserContext}.
*/
browserContexts(): BrowserContext[];
/**
* Returns the default browser context. The default browser context cannot be closed.
*/
defaultBrowserContext(): BrowserContext;
/**
* @internal
* Used by BrowserContext directly so cannot be marked private.
*/
_disposeContext(contextId?: string): Promise;
private _targetCreated;
private _targetDestroyed;
private _targetInfoChanged;
/**
* The browser websocket endpoint which can be used as an argument to
* {@link Puppeteer.connect}.
*
* @returns The Browser websocket url.
*
* @remarks
*
* The format is `ws://${host}:${port}/devtools/browser/`.
*
* You can find the `webSocketDebuggerUrl` from `http://${host}:${port}/json/version`.
* Learn more about the
* {@link https://chromedevtools.github.io/devtools-protocol | devtools protocol} and
* the {@link
* https://chromedevtools.github.io/devtools-protocol/#how-do-i-access-the-browser-target
* | browser endpoint}.
*/
wsEndpoint(): string;
/**
* Promise which resolves to a new {@link Page} object. The Page is created in
* a default browser context.
*/
newPage(): Promise;
/**
* @internal
* Used by BrowserContext directly so cannot be marked private.
*/
_createPageInContext(contextId?: string): Promise;
/**
* All active targets inside the Browser. In case of multiple browser contexts, returns
* an array with all the targets in all browser contexts.
*/
targets(): Target[];
/**
* The target associated with the browser.
*/
target(): Target;
/**
* Searches for a target in all browser contexts.
*
* @param predicate - A function to be run for every target.
* @returns The first target found that matches the `predicate` function.
*
* @example
*
* 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/');
* ```
*/
waitForTarget(predicate: (x: Target) => boolean | Promise, options?: WaitForTargetOptions): Promise;
/**
* An array of all open pages inside the Browser.
*
* @remarks
*
* In case of multiple browser contexts, returns an array with all the pages in all
* browser contexts. Non-visible pages, such as `"background_page"`, will not be listed
* here. You can find them using {@link Target.page}.
*/
pages(): Promise;
/**
* A string representing the browser name and version.
*
* @remarks
*
* For headless Chromium, this is similar to `HeadlessChrome/61.0.3153.0`. For
* non-headless, this is similar to `Chrome/61.0.3153.0`.
*
* The format of browser.version() might change with future releases of Chromium.
*/
version(): Promise;
/**
* The browser's original user agent. Pages can override the browser user agent with
* {@link Page.setUserAgent}.
*/
userAgent(): Promise;
/**
* Closes Chromium and all of its pages (if any were opened). The {@link Browser} object
* itself is considered to be disposed and cannot be used anymore.
*/
close(): Promise;
/**
* Disconnects Puppeteer from the browser, but leaves the Chromium process running.
* After calling `disconnect`, the {@link Browser} object is considered disposed and
* cannot be used anymore.
*/
disconnect(): void;
/**
* Indicates that the browser is connected.
*/
isConnected(): boolean;
private _getVersion;
}
/**
* @internal
*/
export declare type BrowserCloseCallback = () => Promise | void;
/**
* Generic browser options that can be passed when launching any browser or when
* connecting to an existing browser instance.
* @public
*/
export declare interface BrowserConnectOptions {
/**
* Whether to ignore HTTPS errors during navigation.
* @defaultValue false
*/
ignoreHTTPSErrors?: boolean;
/**
* Sets the viewport for each page.
*/
defaultViewport?: Viewport | null;
/**
* Slows down Puppeteer operations by the specified amount of milliseconds to
* aid debugging.
*/
slowMo?: number;
/**
* Callback to decide if Puppeteer should connect to a given target or not.
*/
targetFilter?: TargetFilterCallback;
/**
* @internal
*/
isPageTarget?: IsPageTargetCallback;
}
/**
* 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 {@link Browser.newPage | Browser.newPage} creates a page
* in the default browser context.
*
* @remarks
*
* The Browser class extends from Puppeteer's {@link EventEmitter} class and
* will emit various events which are documented in the
* {@link BrowserContextEmittedEvents} enum.
*
* 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
* {@link Browser.createIncognitoBrowserContext | Browser.createIncognitoBrowserContext}
* method. "Incognito" browser contexts don't write any browsing data to disk.
*
* @example
* ```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();
* ```
* @public
*/
export declare class BrowserContext extends EventEmitter {
private _connection;
private _browser;
private _id?;
/**
* @internal
*/
constructor(connection: Connection, browser: Browser, contextId?: string);
/**
* An array of all active targets inside the browser context.
*/
targets(): Target[];
/**
* This searches for a target in this specific browser context.
*
* @example
* 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 - An object of options. Accepts a timout,
* which is the maximum wait time in milliseconds.
* Pass `0` to disable the timeout. Defaults to 30 seconds.
* @returns Promise which resolves to the first target found
* that matches the `predicate` function.
*/
waitForTarget(predicate: (x: Target) => boolean | Promise, options?: {
timeout?: number;
}): Promise;
/**
* 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 {@link Target.page | the target page}.
*/
pages(): Promise;
/**
* Returns whether BrowserContext is incognito.
* The default browser context is the only non-incognito browser context.
*
* @remarks
* The default browser context cannot be closed.
*/
isIncognito(): boolean;
/**
* @example
* ```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.
*/
overridePermissions(origin: string, permissions: Permission[]): Promise;
/**
* Clears all permission overrides for the browser context.
*
* @example
* ```js
* const context = browser.defaultBrowserContext();
* context.overridePermissions('https://example.com', ['clipboard-read']);
* // do stuff ..
* context.clearPermissionOverrides();
* ```
*/
clearPermissionOverrides(): Promise;
/**
* Creates a new page in the browser context.
*/
newPage(): Promise;
/**
* The browser this browser context belongs to.
*/
browser(): Browser;
/**
* Closes the browser context. All the targets that belong to the browser context
* will be closed.
*
* @remarks
* Only incognito browser contexts can be closed.
*/
close(): Promise;
}
/**
* @public
*/
export declare const enum BrowserContextEmittedEvents {
/**
* Emitted when the url of a target inside the browser context changes.
* Contains a {@link Target} instance.
*/
TargetChanged = "targetchanged",
/**
* Emitted when a target is created within the browser context, for example
* when a new page is opened by
* {@link https://developer.mozilla.org/en-US/docs/Web/API/Window/open | window.open}
* or by {@link BrowserContext.newPage | browserContext.newPage}
*
* Contains a {@link Target} instance.
*/
TargetCreated = "targetcreated",
/**
* Emitted when a target is destroyed within the browser context, for example
* when a page is closed. Contains a {@link Target} instance.
*/
TargetDestroyed = "targetdestroyed"
}
/**
* BrowserContext options.
*
* @public
*/
export declare interface BrowserContextOptions {
/**
* Proxy server with optional port to use for all requests.
* Username and password can be set in `Page.authenticate`.
*/
proxyServer?: string;
/**
* Bypass the proxy for the given semi-colon-separated list of hosts.
*/
proxyBypassList?: string[];
}
/**
* All the events a {@link Browser | browser instance} may emit.
*
* @public
*/
export declare const enum BrowserEmittedEvents {
/**
* Emitted when Puppeteer gets disconnected from the Chromium instance. This
* might happen because of one of the following:
*
* - Chromium is closed or crashed
*
* - The {@link Browser.disconnect | browser.disconnect } method was called.
*/
Disconnected = "disconnected",
/**
* Emitted when the url of a target changes. Contains a {@link Target} instance.
*
* @remarks
*
* Note that this includes target changes in incognito browser contexts.
*/
TargetChanged = "targetchanged",
/**
* Emitted when a target is created, for example when a new page is opened by
* {@link https://developer.mozilla.org/en-US/docs/Web/API/Window/open | window.open}
* or by {@link Browser.newPage | browser.newPage}
*
* Contains a {@link Target} instance.
*
* @remarks
*
* Note that this includes target creations in incognito browser contexts.
*/
TargetCreated = "targetcreated",
/**
* Emitted when a target is destroyed, for example when a page is closed.
* Contains a {@link Target} instance.
*
* @remarks
*
* Note that this includes target destructions in incognito browser contexts.
*/
TargetDestroyed = "targetdestroyed"
}
/**
* BrowserFetcher can download and manage different versions of Chromium and Firefox.
*
* @remarks
* BrowserFetcher operates on revision strings that specify a precise version of Chromium, e.g. `"533271"`. Revision strings can be obtained from {@link http://omahaproxy.appspot.com/ | omahaproxy.appspot.com}.
* In the Firefox case, BrowserFetcher downloads Firefox Nightly and
* operates on version numbers such as `"75"`.
*
* @example
* 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.
*
* @public
*/
export declare class BrowserFetcher {
private _product;
private _downloadsFolder;
private _downloadHost;
private _platform;
/**
* @internal
*/
constructor(projectRoot: string, options?: BrowserFetcherOptions);
/**
* @returns Returns the current `Platform`, which is one of `mac`, `linux`,
* `win32` or `win64`.
*/
platform(): Platform;
/**
* @returns Returns the current `Product`, which is one of `chrome` or
* `firefox`.
*/
product(): Product;
/**
* @returns The download host being used.
*/
host(): string;
/**
* Initiates a HEAD request to check if the revision is available.
* @remarks
* This method is affected by the current `product`.
* @param revision - The revision to check availability for.
* @returns A promise that resolves to `true` if the revision could be downloaded
* from the host.
*/
canDownload(revision: string): Promise;
/**
* Initiates a GET request to download the revision from the host.
* @remarks
* This method is affected by the current `product`.
* @param revision - The revision to download.
* @param progressCallback - A function that will be called with two arguments:
* How many bytes have been downloaded and the total number of bytes of the download.
* @returns A promise with revision information when the revision is downloaded
* and extracted.
*/
download(revision: string, progressCallback?: (x: number, y: number) => void): Promise;
/**
* @remarks
* This method is affected by the current `product`.
* @returns A promise with a list of all revision strings (for the current `product`)
* available locally on disk.
*/
localRevisions(): Promise;
/**
* @remarks
* This method is affected by the current `product`.
* @param revision - A revision to remove for the current `product`.
* @returns A promise that resolves when the revision has been removes or
* throws if the revision has not been downloaded.
*/
remove(revision: string): Promise;
/**
* @param revision - The revision to get info for.
* @returns The revision info for the given revision.
*/
revisionInfo(revision: string): BrowserFetcherRevisionInfo;
/**
* @internal
*/
_getFolderPath(revision: string): string;
}
/**
* @public
*/
export declare interface BrowserFetcherOptions {
platform?: Platform;
product?: string;
path?: string;
host?: string;
}
/**
* @public
*/
export declare interface BrowserFetcherRevisionInfo {
folderPath: string;
executablePath: string;
url: string;
local: boolean;
revision: string;
product: string;
}
/**
* Launcher options that only apply to Chrome.
*
* @public
*/
export declare interface BrowserLaunchArgumentOptions {
/**
* Whether to run the browser in headless mode.
* @defaultValue true
*/
headless?: boolean | 'chrome';
/**
* Path to a user data directory.
* {@link https://chromium.googlesource.com/chromium/src/+/refs/heads/main/docs/user_data_dir.md | see the Chromium docs}
* for more info.
*/
userDataDir?: string;
/**
* Whether to auto-open a DevTools panel for each tab. If this is set to
* `true`, then `headless` will be forced to `false`.
* @defaultValue `false`
*/
devtools?: boolean;
/**
*
*/
debuggingPort?: number;
/**
* Additional command line arguments to pass to the browser instance.
*/
args?: string[];
}
/**
* The `CDPSession` instances are used to talk raw Chrome Devtools Protocol.
*
* @remarks
*
* Protocol methods can be called with {@link CDPSession.send} method and protocol
* events can be subscribed to with `CDPSession.on` method.
*
* Useful links: {@link https://chromedevtools.github.io/devtools-protocol/ | DevTools Protocol Viewer}
* and {@link https://github.com/aslushnikov/getting-started-with-cdp/blob/HEAD/README.md | Getting Started with DevTools Protocol}.
*
* @example
* ```js
* const client = await page.target().createCDPSession();
* await client.send('Animation.enable');
* client.on('Animation.animationCreated', () => console.log('Animation created!'));
* const response = await client.send('Animation.getPlaybackRate');
* console.log('playback rate is ' + response.playbackRate);
* await client.send('Animation.setPlaybackRate', {
* playbackRate: response.playbackRate / 2
* });
* ```
*
* @public
*/
export declare class CDPSession extends EventEmitter {
/**
* @internal
*/
_connection?: Connection;
private _sessionId;
private _targetType;
private _callbacks;
/**
* @internal
*/
constructor(connection: Connection, targetType: string, sessionId: string);
connection(): Connection | undefined;
send(method: T, ...paramArgs: ProtocolMapping.Commands[T]['paramsType']): Promise;
/**
* @internal
*/
_onMessage(object: CDPSessionOnMessageObject): void;
/**
* Detaches the cdpSession from the target. Once detached, the cdpSession object
* won't emit any events and can't be used to send messages.
*/
detach(): Promise;
/**
* @internal
*/
_onClosed(): void;
/**
* @internal
*/
id(): string;
}
declare interface CDPSession_2 extends EventEmitter {
send(method: T, ...paramArgs: ProtocolMapping.Commands[T]['paramsType']): Promise;
}
declare interface CDPSession_3 extends EventEmitter {
send(method: T, ...paramArgs: ProtocolMapping.Commands[T]['paramsType']): Promise;
}
declare interface CDPSession_4 extends EventEmitter {
send(method: T, ...paramArgs: ProtocolMapping.Commands[T]['paramsType']): Promise;
}
/**
* Internal events that the CDPSession class emits.
*
* @internal
*/
export declare const CDPSessionEmittedEvents: {
readonly Disconnected: symbol;
};
/**
* @public
*/
export declare interface CDPSessionOnMessageObject {
id?: number;
method: string;
params: Record;
error: {
message: string;
data: any;
code: number;
};
result?: any;
}
/**
* @public
*/
export declare type ChromeReleaseChannel = 'chrome' | 'chrome-beta' | 'chrome-canary' | 'chrome-dev';
/**
* @public
* {@inheritDoc Puppeteer.clearCustomQueryHandlers}
*/
export declare function clearCustomQueryHandlers(): void;
/**
* @public
*/
export declare interface ClickOptions {
/**
* Time to wait between `mousedown` and `mouseup` in milliseconds.
*
* @defaultValue 0
*/
delay?: number;
/**
* @defaultValue 'left'
*/
button?: MouseButton;
/**
* @defaultValue 1
*/
clickCount?: number;
/**
* Offset for the clickable point relative to the top-left corder of the border box.
*/
offset?: Offset;
}
/**
* @public
*/
export declare interface CommonEventEmitter {
on(event: EventType, handler: Handler): CommonEventEmitter;
off(event: EventType, handler: Handler): CommonEventEmitter;
addListener(event: EventType, handler: Handler): CommonEventEmitter;
removeListener(event: EventType, handler: Handler): CommonEventEmitter;
emit(event: EventType, eventData?: unknown): boolean;
once(event: EventType, handler: Handler): CommonEventEmitter;
listenerCount(event: string): number;
removeAllListeners(event?: EventType): CommonEventEmitter;
}
/**
* Settings that are common to the Puppeteer class, regardless of environment.
* @internal
*/
export declare interface CommonPuppeteerSettings {
isPuppeteerCore: boolean;
}
/**
* @public
* {@inheritDoc PuppeteerNode.connect}
*/
export declare function connect(options: ConnectOptions): Promise;
/**
* @public
*/
export declare class Connection extends EventEmitter {
_url: string;
_transport: ConnectionTransport;
_delay: number;
_lastId: number;
_sessions: Map;
_closed: boolean;
_callbacks: Map;
constructor(url: string, transport: ConnectionTransport, delay?: number);
static fromSession(session: CDPSession): Connection | undefined;
/**
* @param sessionId - The session id
* @returns The current CDP session if it exists
*/
session(sessionId: string): CDPSession | null;
url(): string;
send(method: T, ...paramArgs: ProtocolMapping.Commands[T]['paramsType']): Promise;
_rawSend(message: Record): number;
_onMessage(message: string): Promise;
_onClose(): void;
dispose(): void;
/**
* @param targetInfo - The target info
* @returns The CDP session that is created
*/
createSession(targetInfo: Protocol.Target.TargetInfo): Promise;
}
/**
* @public
*/
export declare interface ConnectionCallback {
resolve: Function;
reject: Function;
error: ProtocolError;
method: string;
}
/**
* Internal events that the Connection class emits.
*
* @internal
*/
export declare const ConnectionEmittedEvents: {
readonly Disconnected: symbol;
};
/**
* Copyright 2020 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @public
*/
export declare interface ConnectionTransport {
send(message: string): void;
close(): void;
onmessage?: (message: string) => void;
onclose?: () => void;
}
/**
* @public
*/
export declare interface ConnectOptions extends BrowserConnectOptions {
browserWSEndpoint?: string;
browserURL?: string;
transport?: ConnectionTransport;
product?: Product;
}
/**
* Users should never call this directly; it's called when calling
* `puppeteer.connect`.
* @internal
*/
export declare const connectToBrowser: (options: BrowserConnectOptions & {
browserWSEndpoint?: string;
browserURL?: string;
transport?: ConnectionTransport;
}) => Promise;
/**
* @internal
*/
export declare type ConsoleAPICalledCallback = (eventType: ConsoleMessageType, handles: JSHandle[], trace: Protocol.Runtime.StackTrace) => void;
/**
* ConsoleMessage objects are dispatched by page via the 'console' event.
* @public
*/
export declare class ConsoleMessage {
private _type;
private _text;
private _args;
private _stackTraceLocations;
/**
* @public
*/
constructor(type: ConsoleMessageType, text: string, args: JSHandle[], stackTraceLocations: ConsoleMessageLocation[]);
/**
* @returns The type of the console message.
*/
type(): ConsoleMessageType;
/**
* @returns The text of the console message.
*/
text(): string;
/**
* @returns An array of arguments passed to the console.
*/
args(): JSHandle[];
/**
* @returns The location of the console message.
*/
location(): ConsoleMessageLocation;
/**
* @returns The array of locations on the stack of the console message.
*/
stackTrace(): ConsoleMessageLocation[];
}
/**
* @public
*/
export declare interface ConsoleMessageLocation {
/**
* URL of the resource if known or `undefined` otherwise.
*/
url?: string;
/**
* 0-based line number in the resource if known or `undefined` otherwise.
*/
lineNumber?: number;
/**
* 0-based column number in the resource if known or `undefined` otherwise.
*/
columnNumber?: number;
}
/**
* The supported types for console messages.
* @public
*/
export declare type ConsoleMessageType = 'log' | 'debug' | 'info' | 'error' | 'warning' | 'dir' | 'dirxml' | 'table' | 'trace' | 'clear' | 'startGroup' | 'startGroupCollapsed' | 'endGroup' | 'assert' | 'profile' | 'profileEnd' | 'count' | 'timeEnd' | 'verbose';
/**
* @public
*/
export declare interface ContinueRequestOverrides {
/**
* If set, the request URL will change. This is not a redirect.
*/
url?: string;
method?: string;
postData?: string;
headers?: Record;
}
/**
* The Coverage class provides methods to gathers information about parts of
* JavaScript and CSS that were used by the page.
*
* @remarks
* To output coverage in a form consumable by {@link https://github.com/istanbuljs | Istanbul},
* see {@link https://github.com/istanbuljs/puppeteer-to-istanbul | puppeteer-to-istanbul}.
*
* @example
* An example of using JavaScript and CSS coverage to get percentage of initially
* executed code:
* ```js
* // Enable both JavaScript and CSS coverage
* await Promise.all([
* page.coverage.startJSCoverage(),
* page.coverage.startCSSCoverage()
* ]);
* // Navigate to page
* await page.goto('https://example.com');
* // Disable both JavaScript and CSS coverage
* const [jsCoverage, cssCoverage] = await Promise.all([
* page.coverage.stopJSCoverage(),
* page.coverage.stopCSSCoverage(),
* ]);
* let totalBytes = 0;
* let usedBytes = 0;
* const coverage = [...jsCoverage, ...cssCoverage];
* for (const entry of coverage) {
* totalBytes += entry.text.length;
* for (const range of entry.ranges)
* usedBytes += range.end - range.start - 1;
* }
* console.log(`Bytes used: ${usedBytes / totalBytes * 100}%`);
* ```
* @public
*/
export declare class Coverage {
/**
* @internal
*/
_jsCoverage: JSCoverage;
/**
* @internal
*/
_cssCoverage: CSSCoverage;
constructor(client: CDPSession);
/**
* @param options - Set of configurable options for coverage defaults to
* `resetOnNavigation : true, reportAnonymousScripts : false`
* @returns Promise that resolves when coverage is started.
*
* @remarks
* Anonymous scripts are ones that don't have an associated url. These are
* scripts that are dynamically created on the page using `eval` or
* `new Function`. If `reportAnonymousScripts` is set to `true`, anonymous
* scripts will have `pptr://__puppeteer_evaluation_script__` as their URL.
*/
startJSCoverage(options?: JSCoverageOptions): Promise;
/**
* @returns Promise that resolves to the array of coverage reports for
* all scripts.
*
* @remarks
* JavaScript Coverage doesn't include anonymous scripts by default.
* However, scripts with sourceURLs are reported.
*/
stopJSCoverage(): Promise;
/**
* @param options - Set of configurable options for coverage, defaults to
* `resetOnNavigation : true`
* @returns Promise that resolves when coverage is started.
*/
startCSSCoverage(options?: CSSCoverageOptions): Promise;
/**
* @returns Promise that resolves to the array of coverage reports
* for all stylesheets.
* @remarks
* CSS Coverage doesn't include dynamically injected style tags
* without sourceURLs.
*/
stopCSSCoverage(): Promise;
}
/**
* The CoverageEntry class represents one entry of the coverage report.
* @public
*/
export declare interface CoverageEntry {
/**
* The URL of the style sheet or script.
*/
url: string;
/**
* The content of the style sheet or script.
*/
text: string;
/**
* The covered range as start and end positions.
*/
ranges: Array<{
start: number;
end: number;
}>;
}
/**
* @internal
*/
export declare function createJSHandle(context: ExecutionContext, remoteObject: Protocol.Runtime.RemoteObject): JSHandle;
/**
* @public
*/
export declare interface Credentials {
username: string;
password: string;
}
/**
* @public
*/
export declare class CSSCoverage {
_client: CDPSession;
_enabled: boolean;
_stylesheetURLs: Map;
_stylesheetSources: Map;
_eventListeners: PuppeteerEventListener[];
_resetOnNavigation: boolean;
_reportAnonymousScripts: boolean;
constructor(client: CDPSession);
start(options?: {
resetOnNavigation?: boolean;
}): Promise;
_onExecutionContextsCleared(): void;
_onStyleSheet(event: Protocol.CSS.StyleSheetAddedEvent): Promise;
stop(): Promise;
}
/**
* Set of configurable options for CSS coverage.
* @public
*/
export declare interface CSSCoverageOptions {
/**
* Whether to reset coverage on every navigation.
*/
resetOnNavigation?: boolean;
}
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @public
*/
export declare class CustomError extends Error {
constructor(message?: string);
}
/**
* Contains two functions `queryOne` and `queryAll` that can
* be {@link Puppeteer.registerCustomQueryHandler | registered}
* as alternative querying strategies. The functions `queryOne` and `queryAll`
* are executed in the page context. `queryOne` should take an `Element` and a
* selector string as argument and return a single `Element` or `null` if no
* element is found. `queryAll` takes the same arguments but should instead
* return a `NodeListOf` or `Array` with all the elements
* that match the given query selector.
* @public
*/
export declare interface CustomQueryHandler {
queryOne?: (element: Element | Document, selector: string) => Element | null;
queryAll?: (element: Element | Document, selector: string) => Element[] | NodeListOf;
}
/**
* @public
* {@inheritDoc Puppeteer.customQueryHandlerNames}
*/
export declare function customQueryHandlerNames(): string[];
/**
* The default cooperative request interception resolution priority
*
* @public
*/
export declare const DEFAULT_INTERCEPT_RESOLUTION_PRIORITY = 0;
/**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @public
*/
export declare interface Device {
name: string;
userAgent: string;
viewport: {
width: number;
height: number;
deviceScaleFactor: number;
isMobile: boolean;
hasTouch: boolean;
isLandscape: boolean;
};
}
/**
* @public
* {@inheritDoc Puppeteer.devices}
*/
export declare let devices: DevicesMap;
/**
* @public
*/
export declare type DevicesMap = {
[name: string]: Device;
};
/**
* @internal
*/
export declare const devicesMap: DevicesMap;
/**
* Dialog instances are dispatched by the {@link Page} via the `dialog` event.
*
* @remarks
*
* @example
* ```js
* const puppeteer = require('puppeteer');
*
* (async () => {
* const browser = await puppeteer.launch();
* const page = await browser.newPage();
* page.on('dialog', async dialog => {
* console.log(dialog.message());
* await dialog.dismiss();
* await browser.close();
* });
* page.evaluate(() => alert('1'));
* })();
* ```
* @public
*/
export declare class Dialog {
private _client;
private _type;
private _message;
private _defaultValue;
private _handled;
/**
* @internal
*/
constructor(client: CDPSession, type: Protocol.Page.DialogType, message: string, defaultValue?: string);
/**
* @returns The type of the dialog.
*/
type(): Protocol.Page.DialogType;
/**
* @returns The message displayed in the dialog.
*/
message(): string;
/**
* @returns The default value of the prompt, or an empty string if the dialog
* is not a `prompt`.
*/
defaultValue(): string;
/**
* @param promptText - optional text that will be entered in the dialog
* prompt. Has no effect if the dialog's type is not `prompt`.
*
* @returns A promise that resolves when the dialog has been accepted.
*/
accept(promptText?: string): Promise;
/**
* @returns A promise which will resolve once the dialog has been dismissed
*/
dismiss(): Promise;
}
/**
* @internal
*/
export declare class DOMWorld {
private _frameManager;
private _client;
private _frame;
private _timeoutSettings;
private _documentPromise;
private _contextPromise;
private _contextResolveCallback;
private _detached;
/**
* @internal
*/
_waitTasks: Set;
/**
* @internal
* Contains mapping from functions that should be bound to Puppeteer functions.
*/
_boundFunctions: Map;
private _ctxBindings;
private static bindingIdentifier;
constructor(client: CDPSession, frameManager: FrameManager, frame: Frame, timeoutSettings: TimeoutSettings);
frame(): Frame;
_setContext(context: ExecutionContext | null): Promise;
_hasContext(): boolean;
_detach(): void;
executionContext(): Promise;
evaluateHandle(pageFunction: EvaluateHandleFn, ...args: SerializableOrJSHandle[]): Promise;
evaluate(pageFunction: T, ...args: SerializableOrJSHandle[]): Promise>>;
$(selector: string): Promise | null>;
_document(): Promise;
$x(expression: string): Promise;
$eval(selector: string, pageFunction: (element: Element, ...args: unknown[]) => ReturnType | Promise, ...args: SerializableOrJSHandle[]): Promise>;
$$eval(selector: string, pageFunction: (elements: Element[], ...args: unknown[]) => ReturnType | Promise, ...args: SerializableOrJSHandle[]): Promise>;
$$(selector: string): Promise>>;
content(): Promise;
setContent(html: string, options?: {
timeout?: number;
waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[];
}): Promise;
/**
* Adds a script tag into the current context.
*
* @remarks
*
* You can pass a URL, filepath or string of contents. Note that when running Puppeteer
* in a browser environment you cannot pass a filepath and should use either
* `url` or `content`.
*/
addScriptTag(options: {
url?: string;
path?: string;
content?: string;
id?: string;
type?: string;
}): Promise;
/**
* Adds a style tag into the current context.
*
* @remarks
*
* You can pass a URL, filepath or string of contents. Note that when running Puppeteer
* in a browser environment you cannot pass a filepath and should use either
* `url` or `content`.
*
*/
addStyleTag(options: {
url?: string;
path?: string;
content?: string;
}): Promise;
click(selector: string, options: {
delay?: number;
button?: MouseButton;
clickCount?: number;
}): Promise;
focus(selector: string): Promise;
hover(selector: string): Promise;
select(selector: string, ...values: string[]): Promise;
tap(selector: string): Promise;
type(selector: string, text: string, options?: {
delay: number;
}): Promise;
waitForSelector(selector: string, options: WaitForSelectorOptions): Promise;
private _settingUpBinding;
/**
* @internal
*/
addBindingToContext(context: ExecutionContext, name: string): Promise;
private _onBindingCalled;
/**
* @internal
*/
waitForSelectorInPage(queryOne: Function, selector: string, options: WaitForSelectorOptions, binding?: PageBinding): Promise;
waitForXPath(xpath: string, options: WaitForSelectorOptions): Promise;
waitForFunction(pageFunction: Function | string, options?: {
polling?: string | number;
timeout?: number;
}, ...args: SerializableOrJSHandle[]): Promise;
title(): Promise;
}
/**
* ElementHandle represents an in-page DOM element.
*
* @remarks
*
* ElementHandles can be created with the {@link Page.$} method.
*
* ```js
* const puppeteer = require('puppeteer');
*
* (async () => {
* const browser = await puppeteer.launch();
* const page = await browser.newPage();
* await page.goto('https://example.com');
* const hrefElement = await page.$('a');
* await hrefElement.click();
* // ...
* })();
* ```
*
* ElementHandle prevents the DOM element from being garbage-collected unless the
* handle is {@link JSHandle.dispose | disposed}. ElementHandles are auto-disposed
* when their origin frame gets navigated.
*
* ElementHandle instances can be used as arguments in {@link Page.$eval} and
* {@link Page.evaluate} methods.
*
* If you're using TypeScript, ElementHandle takes a generic argument that
* denotes the type of element the handle is holding within. For example, if you
* have a handle to a `