puppeteer/docs/api/index.md
2024-04-29 14:50:39 +02:00

39 KiB

sidebar_label
API

API Reference

Classes

Class

Description

Accessibility

The Accessibility class provides methods for inspecting the browser's accessibility tree. The accessibility tree is used by assistive technology such as screen readers or 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.

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the Accessibility class.

Browser

Browser represents a browser instance that is either:

Browser emits various events which are documented in the BrowserEvent enum.

Remarks:

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the Browser class.

BrowserContext

BrowserContext represents individual user contexts within a browser.

When a browser is launched, it has a single browser context by default. Others can be created using Browser.createBrowserContext(). Each context has isolated storage (cookies/localStorage/etc.)

BrowserContext emits various events which are documented in the BrowserContextEvent enum.

If a page opens another page, e.g. using window.open, the popup will belong to the parent page's browser context.

Remarks:

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the BrowserContext class.

CDPSession

The CDPSession instances are used to talk raw Chrome Devtools Protocol.

Remarks:

Protocol methods can be called with CDPSession.send() method and protocol events can be subscribed to with CDPSession.on method.

Useful links: DevTools Protocol Viewer and Getting Started with DevTools Protocol.

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the CDPSession class.

Connection

ConsoleMessage

ConsoleMessage objects are dispatched by page via the 'console' event.

Coverage

The Coverage class provides methods to gather information about parts of JavaScript and CSS that were used by the page.

Remarks:

To output coverage in a form consumable by Istanbul, see puppeteer-to-istanbul.

CSSCoverage

DeviceRequestPrompt

Device request prompts let you respond to the page requesting for a device through an API like WebBluetooth.

Remarks:

DeviceRequestPrompt instances are returned via the Page.waitForDevicePrompt() method.

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the DeviceRequestPrompt class.

DeviceRequestPromptDevice

Device in a request prompt.

Remarks:

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the DeviceRequestPromptDevice class.

Dialog

Dialog instances are dispatched by the Page via the dialog event.

Remarks:

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the Dialog class.

ElementHandle

ElementHandle represents an in-page DOM element.

Remarks:

ElementHandles can be created with the Page.$() method.

import puppeteer from '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 disposed. ElementHandles are auto-disposed when their origin frame gets navigated.

ElementHandle instances can be used as arguments in Page.$eval() and 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 <select> element, you can type it as ElementHandle<HTMLSelectElement> and you get some nicer type checks.

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the ElementHandle class.

EventEmitter

The EventEmitter class that many Puppeteer classes extend.

Remarks:

This allows you to listen to events that Puppeteer classes fire and act accordingly. Therefore you'll mostly use on and off to bind and unbind to event listeners.

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the EventEmitter class.

FileChooser

File choosers let you react to the page requesting for a file.

Remarks:

FileChooser instances are returned via the Page.waitForFileChooser() method.

In browsers, only one file chooser can be opened at a time. All file choosers must be accepted or canceled. Not doing so will prevent subsequent file choosers from appearing.

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the FileChooser class.

Frame

Represents a DOM frame.

To understand frames, you can think of frames as <iframe> elements. Just like iframes, frames can be nested, and when JavaScript is executed in a frame, the JavaScript does not effect frames inside the ambient frame the JavaScript executes in.

Remarks:

Frame lifecycles are controlled by three events that are all dispatched on the parent page:

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the Frame class.

HTTPRequest

Represents an HTTP request sent by a page.

Remarks:

Whenever the page sends a request, such as for a network resource, the following events are emitted by Puppeteer's page:

  • request: emitted when the request is issued by the page. - requestfinished - emitted when the response body is downloaded and the request is complete.

If request fails at some point, then instead of requestfinished event the requestfailed event is emitted.

All of these events provide an instance of HTTPRequest representing the request that occurred:

page.on('request', request => ...)

NOTE: HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with requestfinished event.

If request gets a 'redirect' response, the request is successfully finished with the requestfinished event, and a new request is issued to a redirected url.

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the HTTPRequest class.

HTTPResponse

The HTTPResponse class represents responses which are received by the Page class.

Remarks:

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the HTTPResponse class.

JSCoverage

JSHandle

Represents a reference to a JavaScript object. Instances can be created using Page.evaluateHandle().

Handles prevent the referenced JavaScript object from being garbage-collected unless the handle is purposely disposed. JSHandles are auto-disposed when their associated frame is navigated away or the parent context gets destroyed.

Handles can be used as arguments for any evaluation function such as Page.$eval(), Page.evaluate(), and Page.evaluateHandle(). They are resolved to their referenced object.

Remarks:

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the JSHandle class.

Keyboard

Keyboard provides an api for managing a virtual keyboard. The high level api is Keyboard.type(), which takes raw characters and generates proper keydown, keypress/input, and keyup events on your page.

Remarks:

For finer control, you can use Keyboard.down(), Keyboard.up(), and Keyboard.sendCharacter() to manually fire events as if they were generated from a real keyboard.

On macOS, keyboard shortcuts like ⌘ A -> Select All do not work. See #1313.

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the Keyboard class.

Locator

Locators describe a strategy of locating objects and performing an action on them. If the action fails because the object is not ready for the action, the whole operation is retried. Various preconditions for a successful action are checked automatically.

Mouse

The Mouse class operates in main-frame CSS pixels relative to the top-left corner of the viewport.

Remarks:

Every page object has its own Mouse, accessible with [page.mouse](#pagemouse).

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the Mouse class.

Page

Page provides methods to interact with a single tab or extension background page in the browser.

:::note

One Browser instance might have multiple Page instances.

:::

Remarks:

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the Page class.

ProductLauncher

Describes a launcher - a class that is able to create and launch a browser instance.

Remarks:

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the ProductLauncher class.

ProtocolError

ProtocolError is emitted whenever there is an error from the protocol.

Puppeteer

The main Puppeteer class.

IMPORTANT: if you are using Puppeteer in a Node environment, you will get an instance of PuppeteerNode when you import or require puppeteer. That class extends Puppeteer, so has all the methods documented below as well as all that are defined on PuppeteerNode.

Remarks:

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the Puppeteer class.

PuppeteerError

The base class for all Puppeteer-specific errors

Remarks:

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the PuppeteerError class.

PuppeteerNode

Extends the main Puppeteer class with Node specific behaviour for fetching and downloading browsers.

If you're using Puppeteer in a Node environment, this is the class you'll get when you run require('puppeteer') (or the equivalent ES import).

Remarks:

The most common method to use is launch, which is used to launch and connect to a new browser instance.

See the main Puppeteer class for methods common to all environments, such as Puppeteer.connect().

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the PuppeteerNode class.

ScreenRecorder

Remarks:

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the ScreenRecorder class.

SecurityDetails

The SecurityDetails class represents the security details of a response that was received over a secure connection.

Remarks:

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the SecurityDetails class.

Target

Target represents a CDP target. In CDP a target is something that can be debugged such a frame, a page or a worker.

Remarks:

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the Target class.

TimeoutError

TimeoutError is emitted whenever certain operations are terminated due to timeout.

Remarks:

Example operations are page.waitForSelector or puppeteer.launch.

Touchscreen

The Touchscreen class exposes touchscreen events.

Remarks:

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the Touchscreen class.

Tracing

The Tracing class exposes the tracing audit interface.

Remarks:

You can use tracing.start and tracing.stop to create a trace file which can be opened in Chrome DevTools or timeline viewer.

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the Tracing class.

UnsupportedOperation

Puppeteer will throw this error if a method is not supported by the currently used protocol

WebWorker

This class represents a WebWorker.

Remarks:

The events workercreated and workerdestroyed are emitted on the page object to signal the worker lifecycle.

The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the WebWorker class.

Enumerations

Enumeration

Description

BrowserContextEvent

BrowserEvent

All the events a browser instance may emit.

InterceptResolutionAction

LocatorEvent

All the events that a locator instance may emit.

PageEvent

All the events that a page instance may emit.

TargetType

Functions

Function

Description

clearCustomQueryHandlers()

Deprecated:

Import Puppeteer and use the static method Puppeteer.clearCustomQueryHandlers()

connect(options)

customQueryHandlerNames()

Deprecated:

Import Puppeteer and use the static method Puppeteer.customQueryHandlerNames()

defaultArgs(options)

executablePath(channel)

launch(options)

registerCustomQueryHandler(name, handler)

Deprecated:

Import Puppeteer and use the static method Puppeteer.registerCustomQueryHandler()

trimCache()

unregisterCustomQueryHandler(name)

Deprecated:

Import Puppeteer and use the static method Puppeteer.unregisterCustomQueryHandler()

Interfaces

Interface

Description

ActionOptions

AutofillData

BoundingBox

BoxModel

BrowserConnectOptions

Generic browser options that can be passed when launching any browser or when connecting to an existing browser instance.

BrowserContextEvents

BrowserContextOptions

BrowserEvents

BrowserLaunchArgumentOptions

Launcher options that only apply to Chrome.

CDPSessionEvents

ClickOptions

CommandOptions

CommonEventEmitter

Configuration

Defines options to configure Puppeteer's behavior during installation and runtime.

See individual properties for more information.

ConnectionTransport

ConnectOptions

ConsoleMessageLocation

ContinueRequestOverrides

Cookie

Represents a cookie object.

CookieParam

Cookie parameter object

CoverageEntry

The CoverageEntry class represents one entry of the coverage report.

Credentials

CSSCoverageOptions

Set of configurable options for CSS coverage.

CustomQueryHandler

DebugInfo

(Experimental)

DeleteCookiesRequest

Device

ElementScreenshotOptions

FrameAddScriptTagOptions

FrameAddStyleTagOptions

FrameEvents

FrameWaitForFunctionOptions

GeolocationOptions

GoToOptions

InterceptResolutionState

InternalNetworkConditions

JSCoverageEntry

The CoverageEntry class for JavaScript

JSCoverageOptions

Set of configurable options for JS coverage.

KeyboardTypeOptions

KeyDownOptions

LaunchOptions

Generic launch options that can be passed when launching any browser.

LocatorEvents

LocatorOptions

LocatorScrollOptions

MediaFeature

Metrics

MouseClickOptions

MouseMoveOptions

MouseOptions

MouseWheelOptions

Moveable

NetworkConditions

NewDocumentScriptEvaluation

Offset

PageEvents

Denotes the objects received by callback functions for page events.

See PageEvent for more detail on the events and when they are emitted.

PDFMargin

PDFOptions

Valid options to configure PDF generation via Page.pdf().

Point

PuppeteerLaunchOptions

RemoteAddress

ResponseForRequest

Required response data to fulfill a request with.

ScreencastOptions

(Experimental)

ScreenshotClip

ScreenshotOptions

SerializedAXNode

Represents a Node and the properties of it that are relevant to Accessibility.

SnapshotOptions

TracingOptions

Viewport

WaitForNetworkIdleOptions

WaitForOptions

WaitForSelectorOptions

WaitForTargetOptions

WaitTimeoutOptions

Namespaces

Namespace

Description

CDPSessionEvent

Events that the CDPSession class emits.

Variables

Variable

Description

DEFAULT_INTERCEPT_RESOLUTION_PRIORITY

The default cooperative request interception resolution priority

KnownDevices

A list of devices to be used with Page.emulate().

MouseButton

Enum of valid mouse buttons.

PredefinedNetworkConditions

A list of network conditions to be used with Page.emulateNetworkConditions().

puppeteer

Type Aliases

Type Alias

Description

ActionResult

Awaitable

AwaitableIterable

AwaitablePredicate

AwaitedLocator

CDPEvents

ChromeReleaseChannel

ConsoleMessageType

The supported types for console messages.

CookiePriority

Represents the cookie's 'Priority' status: https://tools.ietf.org/html/draft-west-cookie-priority-00

CookieSameSite

Represents the cookie's 'SameSite' status: https://tools.ietf.org/html/draft-west-first-party-cookies

CookieSourceScheme

Represents the source scheme of the origin that originally set the cookie. A value of "Unset" allows protocol clients to emulate legacy cookie scope for the scheme. This is a temporary ability and it will be removed in the future.

ElementFor

ErrorCode

EvaluateFunc

EvaluateFuncWith

EventsWithWildcard

EventType

ExperimentsConfiguration

Defines experiment options for Puppeteer.

See individual properties for more information.

FlattenHandle

HandleFor

HandleOr

Handler

InnerParams

KeyInput

All the valid keys that can be passed to functions that take user input, such as keyboard.press

KeyPressOptions

LocatorClickOptions

LowerCasePaperFormat

Mapper

MouseButton

NodeFor

PaperFormat

All the valid paper format types when printing a PDF.

Remarks:

The sizes of each format are as follows:

  • 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.54in x 23.4in

  • A3: 11.7in x 16.54in

  • A4: 8.27in x 11.7in

  • A5: 5.83in x 8.27in

  • A6: 4.13in x 5.83in

Permission

Predicate

Product

Supported products.

ProtocolLifeCycleEvent

ProtocolType

PuppeteerLifeCycleEvent

PuppeteerNodeLaunchOptions

Utility type exposed to enable users to define options that can be passed to puppeteer.launch without having to list the set of all types.

Quad

ResourceType

Resource types for HTTPRequests as perceived by the rendering engine.

TargetFilterCallback

VisibilityOption