puppeteer-core
- Version 23.7.1
- Published
- 8.02 MB
- 6 dependencies
- Apache-2.0 license
Install
npm i puppeteer-core
yarn add puppeteer-core
pnpm add puppeteer-core
Overview
A high-level API to control headless Chrome over the DevTools Protocol
Index
Variables
Functions
Classes
ElementHandle
- $()
- $$()
- $$eval()
- $eval()
- autofill()
- boundingBox()
- boxModel()
- click()
- clickablePoint()
- contentFrame()
- drag()
- dragAndDrop()
- dragEnter()
- dragOver()
- drop()
- focus()
- frame
- hover()
- isHidden()
- isIntersectingViewport()
- isVisible()
- press()
- screenshot()
- scrollIntoView()
- select()
- tap()
- toElement()
- touchEnd()
- touchMove()
- touchStart()
- type()
- uploadFile()
- waitForSelector()
HTTPRequest
- abort()
- abortErrorReason()
- client
- continue()
- continueRequestOverrides()
- enqueueInterceptAction()
- failure()
- fetchPostData()
- finalizeInterceptions()
- frame()
- hasPostData()
- headers()
- initiator()
- interceptResolutionState()
- isInterceptResolutionHandled()
- isNavigationRequest()
- method()
- postData()
- redirectChain()
- resourceType()
- respond()
- response()
- responseForRequest()
- url()
Page
- $()
- $$()
- $$eval()
- $eval()
- accessibility
- addScriptTag()
- addStyleTag()
- authenticate()
- bringToFront()
- browser()
- browserContext()
- click()
- close()
- content()
- cookies()
- coverage
- createCDPSession()
- createPDFStream()
- deleteCookie()
- emulate()
- emulateCPUThrottling()
- emulateIdleState()
- emulateMediaFeatures()
- emulateMediaType()
- emulateNetworkConditions()
- emulateTimezone()
- emulateVisionDeficiency()
- evaluate()
- evaluateHandle()
- evaluateOnNewDocument()
- exposeFunction()
- focus()
- frames()
- getDefaultTimeout()
- goBack()
- goForward()
- goto()
- hover()
- isClosed()
- isDragInterceptionEnabled()
- isJavaScriptEnabled()
- isServiceWorkerBypassed()
- keyboard
- locator()
- mainFrame()
- metrics()
- mouse
- pdf()
- queryObjects()
- reload()
- removeExposedFunction()
- removeScriptToEvaluateOnNewDocument()
- screencast()
- screenshot()
- select()
- setBypassCSP()
- setBypassServiceWorker()
- setCacheEnabled()
- setContent()
- setCookie()
- setDefaultNavigationTimeout()
- setDefaultTimeout()
- setDragInterception()
- setExtraHTTPHeaders()
- setGeolocation()
- setJavaScriptEnabled()
- setOfflineMode()
- setRequestInterception()
- setUserAgent()
- setViewport()
- tap()
- target()
- title()
- touchscreen
- tracing
- type()
- url()
- viewport()
- waitForDevicePrompt()
- waitForFileChooser()
- waitForFrame()
- waitForFunction()
- waitForNavigation()
- waitForNetworkIdle()
- waitForRequest()
- waitForResponse()
- waitForSelector()
- workers()
Interfaces
PageEvents
- [PageEvent.Close]
- [PageEvent.Console]
- [PageEvent.Dialog]
- [PageEvent.DOMContentLoaded]
- [PageEvent.Error]
- [PageEvent.FrameAttached]
- [PageEvent.FrameDetached]
- [PageEvent.FrameNavigated]
- [PageEvent.Load]
- [PageEvent.Metrics]
- [PageEvent.PageError]
- [PageEvent.Popup]
- [PageEvent.Request]
- [PageEvent.RequestFailed]
- [PageEvent.RequestFinished]
- [PageEvent.RequestServedFromCache]
- [PageEvent.Response]
- [PageEvent.WorkerCreated]
- [PageEvent.WorkerDestroyed]
Enums
Type Aliases
- ActionResult
- Awaitable
- AwaitableIterable
- AwaitablePredicate
- AwaitedLocator
- CDPEvents
- ChromeReleaseChannel
- ConsoleMessageType
- CookiePriority
- CookieSameSite
- CookieSourceScheme
- ElementFor
- ErrorCode
- EvaluateFunc
- EvaluateFuncWith
- EventsWithWildcard
- EventType
- ExperimentsConfiguration
- FlattenHandle
- HandleFor
- HandleOr
- Handler
- InnerParams
- KeyInput
- KeyPressOptions
- LocatorClickOptions
- LowerCasePaperFormat
- Mapper
- MouseButton
- NodeFor
- PaperFormat
- Permission
- Predicate
- ProtocolLifeCycleEvent
- ProtocolType
- PuppeteerLifeCycleEvent
- PuppeteerNodeLaunchOptions
- Quad
- ResourceType
- SupportedBrowser
- SupportedWebDriverCapability
- TargetFilterCallback
- VisibilityOption
Namespaces
Puppeteer_2
- Accessibility
- ActionOptions
- ActionResult
- AutofillData
- Awaitable
- AwaitableIterable
- AwaitablePredicate
- AwaitedLocator
- BoundingBox
- BoxModel
- Browser
- BrowserConnectOptions
- BrowserContext
- BrowserContextEvent
- BrowserContextEvents
- BrowserContextOptions
- BrowserEvent
- BrowserEvents
- BrowserLaunchArgumentOptions
- BrowserLauncher
- CDPEvents
- CDPSession
- CDPSessionEvents
- ChromeHeadlessShellSettings
- ChromeReleaseChannel
- ChromeSettings
- ClickOptions
- CommandOptions
- CommonEventEmitter
- Configuration
- Connection
- ConnectionTransport
- ConnectOptions
- ConsoleMessage
- ConsoleMessageLocation
- ConsoleMessageType
- ContinueRequestOverrides
- Cookie
- CookieParam
- CookiePriority
- CookieSameSite
- CookieSourceScheme
- Coverage
- CoverageEntry
- Credentials
- CSSCoverage
- CSSCoverageOptions
- CustomQueryHandler
- DebugInfo
- DEFAULT_INTERCEPT_RESOLUTION_PRIORITY
- DeleteCookiesRequest
- Device
- DeviceRequestPrompt
- DeviceRequestPromptDevice
- Dialog
- ElementFor
- ElementHandle
- ElementScreenshotOptions
- ErrorCode
- EvaluateFunc
- EvaluateFuncWith
- EventEmitter
- EventsWithWildcard
- EventType
- ExperimentsConfiguration
- ExtensionTransport
- FileChooser
- FirefoxSettings
- FlattenHandle
- Frame
- FrameAddScriptTagOptions
- FrameAddStyleTagOptions
- FrameEvents
- FrameWaitForFunctionOptions
- GeolocationOptions
- GoToOptions
- HandleFor
- HandleOr
- Handler
- HTTPRequest
- HTTPResponse
- InnerParams
- InterceptResolutionAction
- InterceptResolutionState
- InternalNetworkConditions
- JSCoverage
- JSCoverageEntry
- JSCoverageOptions
- JSHandle
- Keyboard
- KeyboardTypeOptions
- KeyDownOptions
- KeyInput
- KeyPressOptions
- KnownDevices
- LaunchOptions
- Locator
- LocatorClickOptions
- LocatorEvent
- LocatorEvents
- LocatorScrollOptions
- LowerCasePaperFormat
- Mapper
- MediaFeature
- Metrics
- Mouse
- MouseButton
- MouseButton
- MouseClickOptions
- MouseMoveOptions
- MouseOptions
- MouseWheelOptions
- Moveable
- NetworkConditions
- NewDocumentScriptEvaluation
- NodeFor
- Offset
- Page
- PageEvent
- PageEvents
- PaperFormat
- PDFMargin
- PDFOptions
- Permission
- Point
- PredefinedNetworkConditions
- Predicate
- ProtocolError
- ProtocolLifeCycleEvent
- ProtocolType
- Puppeteer
- PuppeteerError
- PuppeteerLaunchOptions
- PuppeteerLifeCycleEvent
- PuppeteerNode
- PuppeteerNodeLaunchOptions
- Quad
- QueryOptions
- RemoteAddress
- ResourceType
- ResponseForRequest
- ScreencastOptions
- ScreenRecorder
- ScreenshotClip
- ScreenshotOptions
- SecurityDetails
- SerializedAXNode
- SnapshotOptions
- SupportedBrowser
- SupportedWebDriverCapabilities
- SupportedWebDriverCapability
- Target
- TargetFilterCallback
- TargetType
- TimeoutError
- TouchError
- TouchHandle
- Touchscreen
- Tracing
- TracingOptions
- UnsupportedOperation
- Viewport
- VisibilityOption
- WaitForNetworkIdleOptions
- WaitForOptions
- WaitForSelectorOptions
- WaitForTargetOptions
- WaitTimeoutOptions
- WebWorker
Variables
variable customQuerySelectors
const customQuerySelectors: CustomQuerySelectorRegistry;
variable DEFAULT_INTERCEPT_RESOLUTION_PRIORITY
const DEFAULT_INTERCEPT_RESOLUTION_PRIORITY: number;
The default cooperative request interception resolution priority
Modifiers
@public
variable KnownDevices
const KnownDevices: Readonly< Record< | 'Blackberry PlayBook' | 'Blackberry PlayBook landscape' | 'BlackBerry Z30' | 'BlackBerry Z30 landscape' | 'Galaxy Note 3' | 'Galaxy Note 3 landscape' | 'Galaxy Note II' | 'Galaxy Note II landscape' | 'Galaxy S III' | 'Galaxy S III landscape' | 'Galaxy S5' | 'Galaxy S5 landscape' | 'Galaxy S8' | 'Galaxy S8 landscape' | 'Galaxy S9+' | 'Galaxy S9+ landscape' | 'Galaxy Tab S4' | 'Galaxy Tab S4 landscape' | 'iPad' | 'iPad landscape' | 'iPad (gen 6)' | 'iPad (gen 6) landscape' | 'iPad (gen 7)' | 'iPad (gen 7) landscape' | 'iPad Mini' | 'iPad Mini landscape' | 'iPad Pro' | 'iPad Pro landscape' | 'iPad Pro 11' | 'iPad Pro 11 landscape' | 'iPhone 4' | 'iPhone 4 landscape' | 'iPhone 5' | 'iPhone 5 landscape' | 'iPhone 6' | 'iPhone 6 landscape' | 'iPhone 6 Plus' | 'iPhone 6 Plus landscape' | 'iPhone 7' | 'iPhone 7 landscape' | 'iPhone 7 Plus' | 'iPhone 7 Plus landscape' | 'iPhone 8' | 'iPhone 8 landscape' | 'iPhone 8 Plus' | 'iPhone 8 Plus landscape' | 'iPhone SE' | 'iPhone SE landscape' | 'iPhone X' | 'iPhone X landscape' | 'iPhone XR' | 'iPhone XR landscape' | 'iPhone 11' | 'iPhone 11 landscape' | 'iPhone 11 Pro' | 'iPhone 11 Pro landscape' | 'iPhone 11 Pro Max' | 'iPhone 11 Pro Max landscape' | 'iPhone 12' | 'iPhone 12 landscape' | 'iPhone 12 Pro' | 'iPhone 12 Pro landscape' | 'iPhone 12 Pro Max' | 'iPhone 12 Pro Max landscape' | 'iPhone 12 Mini' | 'iPhone 12 Mini landscape' | 'iPhone 13' | 'iPhone 13 landscape' | 'iPhone 13 Pro' | 'iPhone 13 Pro landscape' | 'iPhone 13 Pro Max' | 'iPhone 13 Pro Max landscape' | 'iPhone 13 Mini' | 'iPhone 13 Mini landscape' | 'iPhone 14' | 'iPhone 14 landscape' | 'iPhone 14 Plus' | 'iPhone 14 Plus landscape' | 'iPhone 14 Pro' | 'iPhone 14 Pro landscape' | 'iPhone 14 Pro Max' | 'iPhone 14 Pro Max landscape' | 'iPhone 15' | 'iPhone 15 landscape' | 'iPhone 15 Plus' | 'iPhone 15 Plus landscape' | 'iPhone 15 Pro' | 'iPhone 15 Pro landscape' | 'iPhone 15 Pro Max' | 'iPhone 15 Pro Max landscape' | 'JioPhone 2' | 'JioPhone 2 landscape' | 'Kindle Fire HDX' | 'Kindle Fire HDX landscape' | 'LG Optimus L70' | 'LG Optimus L70 landscape' | 'Microsoft Lumia 550' | 'Microsoft Lumia 950' | 'Microsoft Lumia 950 landscape' | 'Nexus 10' | 'Nexus 10 landscape' | 'Nexus 4' | 'Nexus 4 landscape' | 'Nexus 5' | 'Nexus 5 landscape' | 'Nexus 5X' | 'Nexus 5X landscape' | 'Nexus 6' | 'Nexus 6 landscape' | 'Nexus 6P' | 'Nexus 6P landscape' | 'Nexus 7' | 'Nexus 7 landscape' | 'Nokia Lumia 520' | 'Nokia Lumia 520 landscape' | 'Nokia N9' | 'Nokia N9 landscape' | 'Pixel 2' | 'Pixel 2 landscape' | 'Pixel 2 XL' | 'Pixel 2 XL landscape' | 'Pixel 3' | 'Pixel 3 landscape' | 'Pixel 4' | 'Pixel 4 landscape' | 'Pixel 4a (5G)' | 'Pixel 4a (5G) landscape' | 'Pixel 5' | 'Pixel 5 landscape' | 'Moto G4' | 'Moto G4 landscape', Device >>;
A list of devices to be used with Page.emulate.
Example 1
import {KnownDevices} from 'puppeteer';const iPhone = KnownDevices['iPhone 15 Pro'];(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();await page.emulate(iPhone);await page.goto('https://www.google.com');// other actions...await browser.close();})();Modifiers
@public
variable MouseButton
const MouseButton: Readonly<{ Left: 'left'; Right: 'right'; Middle: 'middle'; Back: 'back'; Forward: 'forward';}>;
Enum of valid mouse buttons.
Modifiers
@public
variable PredefinedNetworkConditions
const PredefinedNetworkConditions: Readonly<{ 'Slow 3G': NetworkConditions; 'Fast 3G': NetworkConditions; 'Slow 4G': NetworkConditions; 'Fast 4G': NetworkConditions;}>;
A list of pre-defined network conditions to be used with Page.emulateNetworkConditions.
Example 1
import {PredefinedNetworkConditions} from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();await page.emulateNetworkConditions(PredefinedNetworkConditions['Slow 3G'],);await page.goto('https://www.google.com');await page.emulateNetworkConditions(PredefinedNetworkConditions['Fast 3G'],);await page.goto('https://www.google.com');await page.emulateNetworkConditions(PredefinedNetworkConditions['Slow 4G'],); // alias to Fast 3G.await page.goto('https://www.google.com');await page.emulateNetworkConditions(PredefinedNetworkConditions['Fast 4G'],);await page.goto('https://www.google.com');// other actions...await browser.close();})();Modifiers
@public
variable puppeteer
const puppeteer: PuppeteerNode;
Modifiers
@public
Functions
function connect
connect: (options: Puppeteer_2.ConnectOptions) => Promise<Puppeteer_2.Browser>;
Modifiers
@public
function defaultArgs
defaultArgs: (options?: Puppeteer_2.BrowserLaunchArgumentOptions) => string[];
Modifiers
@public
function executablePath
executablePath: (channel?: Puppeteer_2.ChromeReleaseChannel) => string;
Modifiers
@public
function launch
launch: ( options?: Puppeteer_2.PuppeteerLaunchOptions) => Promise<Puppeteer_2.Browser>;
Modifiers
@public
Classes
class Accessibility
class 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.
Modifiers
@public
method snapshot
snapshot: (options?: SnapshotOptions) => Promise<SerializedAXNode | null>;
Captures the current state of the accessibility tree. The returned object represents the root accessible node of the page.
Returns
An AXNode object representing the snapshot.
Remarks
**NOTE** The Chrome 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 tofalse
.Example 1
An example of dumping the entire accessibility tree:
const snapshot = await page.accessibility.snapshot();console.log(snapshot);Example 2
An example of logging the focused node's name:
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;}
class Browser
abstract class Browser extends EventEmitter<BrowserEvents> {}
Browser represents a browser instance that is either:
- connected to via Puppeteer.connect or - launched by PuppeteerNode.launch.
Browser emits various events which are documented in the BrowserEvent enum.
Example 1
Using a Browser to create a Page:
import puppeteer from 'puppeteer';const browser = await puppeteer.launch();const page = await browser.newPage();await page.goto('https://example.com');await browser.close();Example 2
Disconnecting from and reconnecting to a Browser:
import puppeteer from 'puppeteer';const browser = await puppeteer.launch();// Store the endpoint to be able to reconnect to the browser.const browserWSEndpoint = browser.wsEndpoint();// Disconnect puppeteer from the browser.await browser.disconnect();// Use the endpoint to reestablish a connectionconst browser2 = await puppeteer.connect({browserWSEndpoint});// Close the browser.await browser2.close();Modifiers
@public
property connected
readonly connected: boolean;
Whether Puppeteer is connected to this browser.
property debugInfo
readonly debugInfo: DebugInfo;
Get debug information from Puppeteer.
Remarks
Currently, includes pending protocol calls. In the future, we might add more info.
Modifiers
@public
@experimental
method browserContexts
abstract browserContexts: () => BrowserContext[];
Gets a list of open browser contexts.
In a newly-created browser, this will return a single instance of BrowserContext.
method close
abstract close: () => Promise<void>;
method createBrowserContext
abstract createBrowserContext: ( options?: BrowserContextOptions) => Promise<BrowserContext>;
Creates a new browser context.
This won't share cookies/cache with other browser contexts.
Example 1
import puppeteer from 'puppeteer';const browser = await puppeteer.launch();// Create a new browser context.const context = await browser.createBrowserContext();// Create a new page in a pristine context.const page = await context.newPage();// Do stuffawait page.goto('https://example.com');
method defaultBrowserContext
abstract defaultBrowserContext: () => BrowserContext;
Gets the default browser context.
Remarks
The default browser context cannot be closed.
method disconnect
abstract disconnect: () => Promise<void>;
Disconnects Puppeteer from this browser, but leaves the process running.
method isConnected
isConnected: () => boolean;
Whether Puppeteer is connected to this browser.
Deprecated
Use Browser.connected.
method newPage
abstract newPage: () => Promise<Page>;
Creates a new page in the default browser context.
method pages
pages: () => Promise<Page[]>;
Gets a list of all open pages inside this Browser.
If there are multiple browser contexts, this returns all pages in all browser contexts.
Remarks
Non-visible pages, such as
"background_page"
, will not be listed here. You can find them using Target.page.
method process
abstract process: () => ChildProcess | null;
Gets the associated ChildProcess.
Returns
null
if this instance was connected to via Puppeteer.connect.
method target
abstract target: () => Target;
Gets the target associated with the default browser context).
method targets
abstract targets: () => Target[];
Gets all active targets.
In case of multiple browser contexts, this returns all targets in all browser contexts.
method userAgent
abstract userAgent: () => Promise<string>;
Gets this browser's original user agent.
Pages can override the user agent with Page.setUserAgent.
method version
abstract version: () => Promise<string>;
Gets a string representing this browser's name and version.
For headless browser, this is similar to
"HeadlessChrome/61.0.3153.0"
. For non-headless or new-headless, this is similar to"Chrome/61.0.3153.0"
. For Firefox, it is similar to"Firefox/116.0a1"
.The format of Browser.version might change with future releases of browsers.
method waitForTarget
waitForTarget: ( predicate: (x: Target) => boolean | Promise<boolean>, options?: WaitForTargetOptions) => Promise<Target>;
Waits until a target matching the given
predicate
appears and returns it.This will look all open browser contexts.
Example 1
Finding a target for a page opened via
window.open
:await page.evaluate(() => window.open('https://www.example.com/'));const newWindowTarget = await browser.waitForTarget(target => target.url() === 'https://www.example.com/',);
method wsEndpoint
abstract wsEndpoint: () => string;
Gets the WebSocket URL to connect to this browser.
This is usually used with Puppeteer.connect.
You can find the debugger URL (
webSocketDebuggerUrl
) fromhttp://HOST:PORT/json/version
.See browser endpoint for more information.
Remarks
The format is always
ws://HOST:PORT/devtools/browser/<id>
.
class BrowserContext
abstract class BrowserContext extends EventEmitter<BrowserContextEvents> {}
BrowserContext represents individual user contexts within a browser.
When a browser is launched, it has at least one default browser context. 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
In Chrome all non-default contexts are incognito, and default browser context might be incognito if you provide the
--incognito
argument when launching the browser.Example 1
Creating a new browser context:
// Create a new browser contextconst context = await browser.createBrowserContext();// 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();Modifiers
@public
property closed
readonly closed: boolean;
Whether this browser context is closed.
property id
readonly id: string;
Identifier for this browser context.
method browser
abstract browser: () => Browser;
Gets the browser associated with this browser context.
method clearPermissionOverrides
abstract clearPermissionOverrides: () => Promise<void>;
Clears all permission overrides for this browser context.
Example 1
Clearing overridden permissions in the default browser context:
const context = browser.defaultBrowserContext();context.overridePermissions('https://example.com', ['clipboard-read']);// do stuff ..context.clearPermissionOverrides();
method close
abstract close: () => Promise<void>;
Closes this browser context and all associated pages.
Remarks
The default browser context cannot be closed.
method newPage
abstract newPage: () => Promise<Page>;
Creates a new page in this browser context.
method overridePermissions
abstract overridePermissions: ( origin: string, permissions: Permission[]) => Promise<void>;
Grants this browser context the given
permissions
within the givenorigin
.Parameter origin
The origin to grant permissions to, e.g. "https://example.com".
Parameter permissions
An array of permissions to grant. All permissions that are not listed here will be automatically denied.
Example 1
Overriding permissions in the default browser context:
const context = browser.defaultBrowserContext();await context.overridePermissions('https://html5demos.com', ['geolocation',]);
method pages
abstract pages: () => Promise<Page[]>;
Gets a list of all open pages inside this browser context.
Remarks
Non-visible pages, such as
"background_page"
, will not be listed here. You can find them using Target.page.
method targets
abstract targets: () => Target[];
Gets all active targets inside this browser context.
method waitForTarget
waitForTarget: ( predicate: (x: Target) => boolean | Promise<boolean>, options?: WaitForTargetOptions) => Promise<Target>;
Waits until a target matching the given
predicate
appears and returns it.This will look all open browser contexts.
Example 1
Finding a target for a page opened via
window.open
:await page.evaluate(() => window.open('https://www.example.com/'));const newWindowTarget = await browserContext.waitForTarget(target => target.url() === 'https://www.example.com/',);
class BrowserLauncher
abstract class BrowserLauncher {}
Describes a launcher - a class that is able to create and launch a browser instance.
Modifiers
@public
property browser
readonly browser: SupportedBrowser;
method defaultArgs
abstract defaultArgs: (object: BrowserLaunchArgumentOptions) => string[];
method executablePath
abstract executablePath: (channel?: ChromeReleaseChannel) => string;
method launch
launch: (options?: PuppeteerNodeLaunchOptions) => Promise<Browser>;
class CDPSession
abstract class CDPSession extends EventEmitter<CDPSessionEvents> {}
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.
Example 1
const client = await page.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,});Modifiers
@public
method connection
abstract connection: () => Connection | undefined;
method detach
abstract detach: () => Promise<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.
method id
abstract id: () => string;
Returns the session's id.
method send
abstract send: <T extends string | number | symbol>( method: T, params?: ProtocolMapping.Commands, options?: CommandOptions) => Promise<ProtocolMapping.Commands[T]['returnType']>;
class Connection
class Connection extends EventEmitter<CDPSessionEvents> {}
Modifiers
@public
constructor
constructor( url: string, transport: ConnectionTransport, delay?: number, timeout?: number);
property timeout
readonly timeout: number;
method createSession
createSession: (targetInfo: Protocol.Target.TargetInfo) => Promise<CDPSession>;
Parameter targetInfo
The target info
Returns
The CDP session that is created
method dispose
dispose: () => void;
method fromSession
static fromSession: (session: CDPSession) => Connection | undefined;
method send
send: <T extends string | number | symbol>( method: T, params?: ProtocolMapping.Commands, options?: CommandOptions) => Promise<ProtocolMapping.Commands[T]['returnType']>;
method session
session: (sessionId: string) => CDPSession | null;
Parameter sessionId
The session id
Returns
The current CDP session if it exists
method url
url: () => string;
class ConsoleMessage
class ConsoleMessage {}
ConsoleMessage objects are dispatched by page via the 'console' event.
Modifiers
@public
method args
args: () => JSHandle[];
An array of arguments passed to the console.
method location
location: () => ConsoleMessageLocation;
The location of the console message.
method stackTrace
stackTrace: () => ConsoleMessageLocation[];
The array of locations on the stack of the console message.
method text
text: () => string;
The text of the console message.
method type
type: () => ConsoleMessageType;
The type of the console message.
class Coverage
class 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.
Example 1
An example of using JavaScript and CSS coverage to get percentage of initially executed code:
// Enable both JavaScript and CSS coverageawait Promise.all([page.coverage.startJSCoverage(),page.coverage.startCSSCoverage(),]);// Navigate to pageawait page.goto('https://example.com');// Disable both JavaScript and CSS coverageconst [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}%`);Modifiers
@public
method startCSSCoverage
startCSSCoverage: (options?: CSSCoverageOptions) => Promise<void>;
Parameter options
Set of configurable options for coverage, defaults to
resetOnNavigation : true
Returns
Promise that resolves when coverage is started.
method startJSCoverage
startJSCoverage: (options?: JSCoverageOptions) => Promise<void>;
Parameter options
Set of configurable options for coverage defaults to
resetOnNavigation : true, reportAnonymousScripts : false,
includeRawScriptCoverage : false, useBlockCoverage : true
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
ornew Function
. IfreportAnonymousScripts
is set totrue
, anonymous scripts URL will start withdebugger://VM
(unless a magic //# sourceURL comment is present, in which case that will the be URL).
method stopCSSCoverage
stopCSSCoverage: () => Promise<CoverageEntry[]>;
Promise that resolves to the array of coverage reports for all stylesheets.
Remarks
CSS Coverage doesn't include dynamically injected style tags without sourceURLs.
method stopJSCoverage
stopJSCoverage: () => Promise<JSCoverageEntry[]>;
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.
class CSSCoverage
class CSSCoverage {}
Modifiers
@public
constructor
constructor(client: CDPSession);
method start
start: (options?: { resetOnNavigation?: boolean }) => Promise<void>;
method stop
stop: () => Promise<CoverageEntry[]>;
class DeviceRequestPrompt
class 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.Example 1
const [devicePrompt] = Promise.all([page.waitForDevicePrompt(),page.click('#connect-bluetooth'),]);await devicePrompt.select(await devicePrompt.waitForDevice(({name}) => name.includes('My Device')),);Modifiers
@public
property devices
devices: DeviceRequestPromptDevice[];
Current list of selectable devices.
method cancel
cancel: () => Promise<void>;
Cancel the prompt.
method select
select: (device: DeviceRequestPromptDevice) => Promise<void>;
Select a device in the prompt's list.
method waitForDevice
waitForDevice: ( filter: (device: DeviceRequestPromptDevice) => boolean, options?: WaitTimeoutOptions) => Promise<DeviceRequestPromptDevice>;
Resolve to the first device in the prompt matching a filter.
class DeviceRequestPromptDevice
class DeviceRequestPromptDevice {}
Device in a request prompt.
Modifiers
@public
class Dialog
abstract class Dialog {}
Dialog instances are dispatched by the Page via the
dialog
event.Remarks
Example 1
import puppeteer from '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'));})();Modifiers
@public
method accept
accept: (promptText?: string) => Promise<void>;
A promise that resolves when the dialog has been accepted.
Parameter promptText
optional text that will be entered in the dialog prompt. Has no effect if the dialog's type is not
prompt
.
method defaultValue
defaultValue: () => string;
The default value of the prompt, or an empty string if the dialog is not a
prompt
.
method dismiss
dismiss: () => Promise<void>;
A promise which will resolve once the dialog has been dismissed
method message
message: () => string;
The message displayed in the dialog.
method type
type: () => Protocol.Page.DialogType;
The type of the dialog.
class ElementHandle
abstract class ElementHandle< ElementType extends Node = Element> extends JSHandle<ElementType> {}
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 asElementHandle<HTMLSelectElement>
and you get some nicer type checks.Modifiers
@public
property frame
readonly frame: Frame;
Frame corresponding to the current handle.
method $
$: <Selector extends string>( selector: Selector) => Promise<ElementHandle<NodeFor<Selector>> | null>;
Queries the current element for an element matching the given selector.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Returns
A element handle to the first element matching the given selector. Otherwise,
null
.
method $$
$$: <Selector extends string>( selector: Selector, options?: QueryOptions) => Promise<Array<ElementHandle<NodeFor<Selector>>>>;
Queries the current element for all elements matching the given selector.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Returns
An array of element handles that point to elements matching the given selector.
method $$eval
$$eval: < Selector extends string, Params extends unknown[], Func extends EvaluateFuncWith< ParseSelector<ComplexSelector>[], Params > = EvaluateFuncWith<ParseSelector<ComplexSelector>[], Params>>( selector: Selector, pageFunction: Func | string, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
Runs the given function on an array of elements matching the given selector in the current element.
If the given function returns a promise, then this method will wait till the promise resolves.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Parameter pageFunction
The function to be evaluated in the element's page's context. An array of elements matching the given selector will be passed to the function as its first argument.
Parameter args
Additional arguments to pass to
pageFunction
.Returns
A promise to the result of the function.
Example 1
HTML:
<div class="feed"><div class="tweet">Hello!</div><div class="tweet">Hi!</div></div>JavaScript:
const feedHandle = await page.$('.feed');expect(await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText)),).toEqual(['Hello!', 'Hi!']);
method $eval
$eval: < Selector extends string, Params extends unknown[], Func extends EvaluateFuncWith< ParseSelector<ComplexSelector>, Params > = EvaluateFuncWith<ParseSelector<ComplexSelector>, Params>>( selector: Selector, pageFunction: Func | string, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
Runs the given function on the first element matching the given selector in the current element.
If the given function returns a promise, then this method will wait till the promise resolves.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Parameter pageFunction
The function to be evaluated in this element's page's context. The first element matching the selector will be passed in as the first argument.
Parameter args
Additional arguments to pass to
pageFunction
.Returns
A promise to the result of the function.
Example 1
const tweetHandle = await page.$('.tweet');expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100',);expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10',);
method autofill
abstract autofill: (data: AutofillData) => Promise<void>;
If the element is a form input, you can use ElementHandle.autofill to test if the form is compatible with the browser's autofill implementation. Throws an error if the form cannot be autofilled.
Remarks
Currently, Puppeteer supports auto-filling credit card information only and in Chrome in the new headless and headful modes only.
// Select an input on the credit card form.const name = await page.waitForSelector('form #name');// Trigger autofill with the desired data.await name.autofill({creditCard: {number: '4444444444444444',name: 'John Smith',expiryMonth: '01',expiryYear: '2030',cvc: '123',},});
method boundingBox
boundingBox: () => Promise<BoundingBox | null>;
This method returns the bounding box of the element (relative to the main frame), or
null
if the element is not part of the layout (example:display: none
).
method boxModel
boxModel: () => Promise<BoxModel | null>;
This method returns boxes of the element, or
null
if the element is not part of the layout (example:display: none
).Remarks
Boxes are represented as an array of points; Each Point is an object
{x, y}
. Box points are sorted clock-wise.
method click
click: ( this: ElementHandle<Element>, options?: Readonly<ClickOptions>) => Promise<void>;
This method scrolls element into view if needed, and then uses Page.mouse to click in the center of the element. If the element is detached from DOM, the method throws an error.
method clickablePoint
clickablePoint: (offset?: Offset) => Promise<Point>;
Returns the middle point within an element unless a specific offset is provided.
method contentFrame
abstract contentFrame: { (this: ElementHandle<HTMLIFrameElement>): Promise<Frame>; (): Promise<Frame>;};
Resolves the frame associated with the element, if any. Always exists for HTMLIFrameElements.
method drag
drag: ( this: ElementHandle<Element>, target: Point | ElementHandle<Element>) => Promise<Protocol.Input.DragData | void>;
Drags an element over the given element or point.
Returns
DEPRECATED. When drag interception is enabled, the drag payload is returned.
method dragAndDrop
dragAndDrop: ( this: ElementHandle<Element>, target: ElementHandle<Node>, options?: { delay: number }) => Promise<void>;
Deprecated
Use
ElementHandle.drop
instead.
method dragEnter
dragEnter: ( this: ElementHandle<Element>, data?: Protocol.Input.DragData) => Promise<void>;
Deprecated
Do not use.
dragenter
will automatically be performed during dragging.
method dragOver
dragOver: ( this: ElementHandle<Element>, data?: Protocol.Input.DragData) => Promise<void>;
Deprecated
Do not use.
dragover
will automatically be performed during dragging.
method drop
drop: { ( this: ElementHandle<Element>, element: ElementHandle<Element> ): Promise<void>; ( this: ElementHandle<Element>, data?: Protocol.Input.DragData ): Promise<void>;};
Drops the given element onto the current one.
Deprecated
No longer supported.
method focus
focus: () => Promise<void>;
Calls focus on the element.
method hover
hover: (this: ElementHandle<Element>) => Promise<void>;
This method scrolls element into view if needed, and then uses Page.mouse to hover over the center of the element. If the element is detached from DOM, the method throws an error.
method isHidden
isHidden: () => Promise<boolean>;
An element is considered to be hidden if at least one of the following is true:
- the element has no computed styles.
- the element has an empty bounding client rect.
- the element's visibility is
hidden
orcollapse
.
method isIntersectingViewport
isIntersectingViewport: ( this: ElementHandle<Element>, options?: { threshold?: number }) => Promise<boolean>;
Resolves to true if the element is visible in the current viewport. If an element is an SVG, we check if the svg owner element is in the viewport instead. See https://crbug.com/963246.
Parameter options
Threshold for the intersection between 0 (no intersection) and 1 (full intersection). Defaults to 1.
method isVisible
isVisible: () => Promise<boolean>;
An element is considered to be visible if all of the following is true:
- the element has computed styles.
- the element has a non-empty bounding client rect.
- the element's visibility is not
hidden
orcollapse
.
method press
press: (key: KeyInput, options?: Readonly<KeyPressOptions>) => Promise<void>;
Focuses the element, and then uses Keyboard.down and Keyboard.up.
Parameter key
Name of key to press, such as
ArrowLeft
. See KeyInput for a list of all key names.Remarks
If
key
is a single character and no modifier keys besidesShift
are being held down, akeypress
/input
event will also be generated. Thetext
option can be specified to force an input event to be generated.**NOTE** Modifier keys DO affect
elementHandle.press
. Holding downShift
will type the text in upper case.
method screenshot
screenshot: { ( options: Readonly<ScreenshotOptions> & { encoding: 'base64' } ): Promise<string>; (options?: Readonly<ScreenshotOptions>): Promise<Uint8Array>;};
This method scrolls element into view if needed, and then uses Page.screenshot to take a screenshot of the element. If the element is detached from DOM, the method throws an error.
method scrollIntoView
scrollIntoView: (this: ElementHandle<Element>) => Promise<void>;
Scrolls the element into view using either the automation protocol client or by calling element.scrollIntoView.
method select
select: (...values: string[]) => Promise<string[]>;
Triggers a
change
andinput
event once all the provided options have been selected. If there's no<select>
element matchingselector
, the method throws an error.Parameter values
Values of options to select. If the
<select>
has themultiple
attribute, all values are considered, otherwise only the first one is taken into account.Example 1
handle.select('blue'); // single selectionhandle.select('red', 'green', 'blue'); // multiple selections
method tap
tap: (this: ElementHandle<Element>) => Promise<void>;
This method scrolls element into view if needed, and then uses Touchscreen.tap to tap in the center of the element. If the element is detached from DOM, the method throws an error.
method toElement
toElement: < K extends | 'symbol' | 'object' | 'dir' | 'table' | 'a' | 'abbr' | 'address' | 'area' | 'article' | 'aside' | 'audio' | 'b' | 'base' | 'bdi' | 'bdo' | 'blockquote' | 'body' | 'br' | 'button' | 'canvas' | 'caption' | 'cite' | 'code' | 'col' | 'colgroup' | 'data' | 'datalist' | 'dd' | 'del' | 'details' | 'dfn' | 'dialog' | 'div' | 'dl' | 'dt' | 'em' | 'embed' | 'fieldset' | 'figcaption' | 'figure' | 'font' | 'footer' | 'form' | 'frame' | 'frameset' | 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'head' | 'header' | 'hgroup' | 'hr' | 'html' | 'i' | 'iframe' | 'img' | 'input' | 'ins' | 'kbd' | 'label' | 'legend' | 'li' | 'link' | 'main' | 'map' | 'mark' | 'marquee' | 'menu' | 'meta' | 'meter' | 'nav' | 'noscript' | 'ol' | 'optgroup' | 'option' | 'output' | 'p' | 'param' | 'picture' | 'pre' | 'progress' | 'q' | 'rp' | 'rt' | 'ruby' | 's' | 'samp' | 'script' | 'section' | 'select' | 'slot' | 'small' | 'source' | 'span' | 'strong' | 'style' | 'sub' | 'summary' | 'sup' | 'tbody' | 'td' | 'template' | 'textarea' | 'tfoot' | 'th' | 'thead' | 'time' | 'title' | 'tr' | 'track' | 'u' | 'ul' | 'var' | 'video' | 'wbr' | 'animate' | 'animateMotion' | 'animateTransform' | 'circle' | 'clipPath' | 'defs' | 'desc' | 'ellipse' | 'feBlend' | 'feColorMatrix' | 'feComponentTransfer' | 'feComposite' | 'feConvolveMatrix' | 'feDiffuseLighting' | 'feDisplacementMap' | 'feDistantLight' | 'feDropShadow' | 'feFlood' | 'feFuncA' | 'feFuncB' | 'feFuncG' | 'feFuncR' | 'feGaussianBlur' | 'feImage' | 'feMerge' | 'feMergeNode' | 'feMorphology' | 'feOffset' | 'fePointLight' | 'feSpecularLighting' | 'feSpotLight' | 'feTile' | 'feTurbulence' | 'filter' | 'foreignObject' | 'g' | 'image' | 'line' | 'linearGradient' | 'marker' | 'mask' | 'metadata' | 'mpath' | 'path' | 'pattern' | 'polygon' | 'polyline' | 'radialGradient' | 'rect' | 'set' | 'stop' | 'svg' | 'switch' | 'text' | 'textPath' | 'tspan' | 'use' | 'view'>( tagName: K) => Promise<HandleFor<ElementFor<K>>>;
Converts the current handle to the given element type.
Parameter tagName
The tag name of the desired element type.
Throws
An error if the handle does not match. **The handle will not be automatically disposed.**
Example 1
const element: ElementHandle<Element> = await page.$('.class-name-of-anchor',);// DO NOT DISPOSE `element`, this will be always be the same handle.const anchor: ElementHandle<HTMLAnchorElement> =await element.toElement('a');
method touchEnd
touchEnd: (this: ElementHandle<Element>) => Promise<void>;
method touchMove
touchMove: (this: ElementHandle<Element>, touch?: TouchHandle) => Promise<void>;
This method scrolls the element into view if needed, and then moves the touch to the center of the element.
Parameter touch
An optional TouchHandle. If provided, this touch will be moved. If not provided, the first active touch will be moved.
method touchStart
touchStart: (this: ElementHandle<Element>) => Promise<TouchHandle>;
This method scrolls the element into view if needed, and then starts a touch in the center of the element.
Returns
A TouchHandle representing the touch that was started
method type
type: (text: string, options?: Readonly<KeyboardTypeOptions>) => Promise<void>;
Focuses the element, and then sends a
keydown
,keypress
/input
, andkeyup
event for each character in the text.To press a special key, like
Control
orArrowDown
, use ElementHandle.press.Parameter options
Delay in milliseconds. Defaults to 0.
Example 1
await elementHandle.type('Hello'); // Types instantlyawait elementHandle.type('World', {delay: 100}); // Types slower, like a userExample 2
An example of typing into a text field and then submitting the form:
const elementHandle = await page.$('input');await elementHandle.type('some text');await elementHandle.press('Enter');
method uploadFile
abstract uploadFile: ( this: ElementHandle<HTMLInputElement>, ...paths: string[]) => Promise<void>;
Sets the value of an input element to the given file paths.
Remarks
This will not validate whether the file paths exists. Also, if a path is relative, then it is resolved against the current working directory. For locals script connecting to remote chrome environments, paths must be absolute.
method waitForSelector
waitForSelector: <Selector extends string>( selector: Selector, options?: WaitForSelectorOptions) => Promise<ElementHandle<NodeFor<Selector>> | null>;
Wait for an element matching the given selector to appear in the current element.
Unlike Frame.waitForSelector, this method does not work across navigations or if the element is detached from DOM.
Parameter selector
The selector to query and wait for.
Parameter options
Options for customizing waiting behavior.
Returns
An element matching the given selector.
Throws
Throws if an element matching the given selector doesn't appear.
Example 1
import puppeteer from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();let currentURL;page.mainFrame().waitForSelector('img').then(() => console.log('First URL with image: ' + currentURL));for (currentURL of ['https://example.com','https://google.com','https://bbc.com',]) {await page.goto(currentURL);}await browser.close();})();
class EventEmitter
class EventEmitter<Events extends Record<EventType, unknown>> implements CommonEventEmitter<EventsWithWildcard<Events>> {}
method emit
emit: <Key extends '*' | keyof Events>( type: Key, event: EventsWithWildcard<Events>[Key]) => boolean;
Emit an event and call any associated listeners.
Parameter type
the event you'd like to emit
Parameter eventData
any data you'd like to emit with the event
Returns
true
if there are any listeners,false
if there are not.
method listenerCount
listenerCount: (type: keyof EventsWithWildcard<Events>) => number;
Gets the number of listeners for a given event.
Parameter type
the event to get the listener count for
Returns
the number of listeners bound to the given event
method off
off: <Key extends '*' | keyof Events>( type: Key, handler?: Handler<EventsWithWildcard<Events>[Key]>) => this;
Remove an event listener from firing.
Parameter type
the event type you'd like to stop listening to.
Parameter handler
the function that should be removed.
Returns
this
to enable you to chain method calls.
method on
on: <Key extends '*' | keyof Events>( type: Key, handler: Handler<EventsWithWildcard<Events>[Key]>) => this;
Bind an event listener to fire when an event occurs.
Parameter type
the event type you'd like to listen to. Can be a string or symbol.
Parameter handler
the function to be called when the event occurs.
Returns
this
to enable you to chain method calls.
method once
once: <Key extends '*' | keyof Events>( type: Key, handler: Handler<EventsWithWildcard<Events>[Key]>) => this;
Like
on
but the listener will only be fired once and then it will be removed.Parameter type
the event you'd like to listen to
Parameter handler
the handler function to run when the event occurs
Returns
this
to enable you to chain method calls.
method removeAllListeners
removeAllListeners: (type?: keyof EventsWithWildcard<Events>) => this;
Removes all listeners. If given an event argument, it will remove only listeners for that event.
Parameter type
the event to remove listeners for.
Returns
this
to enable you to chain method calls.
class ExtensionTransport
class ExtensionTransport implements ConnectionTransport {}
Experimental ExtensionTransport allows establishing a connection via chrome.debugger API if Puppeteer runs in an extension. Since Chrome DevTools Protocol is restricted for extensions, the transport implements missing commands and events.
Modifiers
@experimental
@public
property onclose
onclose?: () => void;
property onmessage
onmessage?: (message: string) => void;
method close
close: () => void;
method connectTab
static connectTab: (tabId: number) => Promise<ExtensionTransport>;
method send
send: (message: string) => void;
class FileChooser
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.
Example 1
const [fileChooser] = await Promise.all([page.waitForFileChooser(),page.click('#upload-file-button'), // some button that triggers file selection]);await fileChooser.accept(['/tmp/myfile.pdf']);Modifiers
@public
method accept
accept: (paths: string[]) => Promise<void>;
Accept the file chooser request with the given file paths.
Remarks
This will not validate whether the file paths exists. Also, if a path is relative, then it is resolved against the current working directory. For locals script connecting to remote chrome environments, paths must be absolute.
method cancel
cancel: () => Promise<void>;
Closes the file chooser without selecting any files.
method isMultiple
isMultiple: () => boolean;
Whether file chooser allow for multiple file selection.
class Frame
abstract class Frame extends EventEmitter<FrameEvents> {}
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:
- PageEvent.FrameAttached - PageEvent.FrameNavigated - PageEvent.FrameDetached
Example 1
At any point in time, pages expose their current frame tree via the Page.mainFrame and Frame.childFrames methods.
Example 2
An example of dumping frame tree:
import puppeteer from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();await page.goto('https://www.google.com/chrome/browser/canary.html');dumpFrameTree(page.mainFrame(), '');await browser.close();function dumpFrameTree(frame, indent) {console.log(indent + frame.url());for (const child of frame.childFrames()) {dumpFrameTree(child, indent + ' ');}}})();Example 3
An example of getting text from an iframe element:
const frame = page.frames().find(frame => frame.name() === 'myframe');const text = await frame.$eval('.selector', element => element.textContent);console.log(text);Modifiers
@public
property detached
readonly detached: boolean;
Returns
true
if the frame has detached.false
otherwise.
method $
$: <Selector extends string>( selector: Selector) => Promise<ElementHandle<NodeFor<Selector>> | null>;
Queries the frame for an element matching the given selector.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Returns
A element handle to the first element matching the given selector. Otherwise,
null
.
method $$
$$: <Selector extends string>( selector: Selector, options?: QueryOptions) => Promise<Array<ElementHandle<NodeFor<Selector>>>>;
Queries the frame for all elements matching the given selector.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Returns
An array of element handles that point to elements matching the given selector.
method $$eval
$$eval: < Selector extends string, Params extends unknown[], Func extends EvaluateFuncWith< ParseSelector<ComplexSelector>[], Params > = EvaluateFuncWith<ParseSelector<ComplexSelector>[], Params>>( selector: Selector, pageFunction: string | Func, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
Runs the given function on an array of elements matching the given selector in the frame.
If the given function returns a promise, then this method will wait till the promise resolves.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Parameter pageFunction
The function to be evaluated in the frame's context. An array of elements matching the given selector will be passed to the function as its first argument.
Parameter args
Additional arguments to pass to
pageFunction
.Returns
A promise to the result of the function.
Example 1
const divsCounts = await frame.$$eval('div', divs => divs.length);
method $eval
$eval: < Selector extends string, Params extends unknown[], Func extends EvaluateFuncWith< ParseSelector<ComplexSelector>, Params > = EvaluateFuncWith<ParseSelector<ComplexSelector>, Params>>( selector: Selector, pageFunction: string | Func, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
Runs the given function on the first element matching the given selector in the frame.
If the given function returns a promise, then this method will wait till the promise resolves.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Parameter pageFunction
The function to be evaluated in the frame's context. The first element matching the selector will be passed to the function as its first argument.
Parameter args
Additional arguments to pass to
pageFunction
.Returns
A promise to the result of the function.
Example 1
const searchValue = await frame.$eval('#search', el => el.value);
method addScriptTag
addScriptTag: ( options: FrameAddScriptTagOptions) => Promise<ElementHandle<HTMLScriptElement>>;
Adds a
<script>
tag into the page with the desired url or content.Parameter options
Options for the script.
Returns
An element handle to the injected
<script>
element.
method addStyleTag
addStyleTag: { (options: Omit<FrameAddStyleTagOptions, 'url'>): Promise< ElementHandle<HTMLStyleElement> >; (options: FrameAddStyleTagOptions): Promise<ElementHandle<HTMLLinkElement>>;};
Adds a
HTMLStyleElement
into the frame with the desired URLReturns
An element handle to the loaded
<style>
element.Adds a
HTMLLinkElement
into the frame with the desired URLReturns
An element handle to the loaded
<link>
element.
method childFrames
abstract childFrames: () => Frame[];
An array of child frames.
method click
click: (selector: string, options?: Readonly<ClickOptions>) => Promise<void>;
Clicks the first element found that matches
selector
.Parameter selector
The selector to query for.
Remarks
If
click()
triggers a navigation event and there's a separatepage.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:const [response] = await Promise.all([page.waitForNavigation(waitOptions),frame.click(selector, clickOptions),]);
method content
content: () => Promise<string>;
The full HTML contents of the frame, including the DOCTYPE.
method evaluate
evaluate: < Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>( pageFunction: Func | string, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
Behaves identically to Page.evaluate except it's run within the context of this frame.
See Page.evaluate for details.
method evaluateHandle
evaluateHandle: < Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>( pageFunction: Func | string, ...args: Params) => Promise<HandleFor<Awaited<ReturnType<Func>>>>;
Behaves identically to Page.evaluateHandle except it's run within the context of this frame.
See Page.evaluateHandle for details.
method focus
focus: (selector: string) => Promise<void>;
Focuses the first element that matches the
selector
.Parameter selector
The selector to query for.
Throws
Throws if there's no element matching
selector
.
method frameElement
frameElement: () => Promise<HandleFor<HTMLIFrameElement> | null>;
Returns
The frame element associated with this frame (if any).
method goto
abstract goto: ( url: string, options?: GoToOptions) => Promise<HTTPResponse | null>;
Navigates the frame or page to the given
url
.Parameter url
URL to navigate the frame to. The URL should include scheme, e.g.
https://
Parameter options
Options to configure waiting behavior.
Returns
A promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
Throws
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 remote server does not respond or is unreachable.
- the main resource failed to load.
Remarks
Navigation to
about:blank
or navigation to the same URL with a different hash will succeed and returnnull
.:::warning
Headless shell mode doesn't support navigation to a PDF document. See the upstream issue.
:::
In headless shell, this method will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling HTTPResponse.status.
method hover
hover: (selector: string) => Promise<void>;
Hovers the pointer over the center of the first element that matches the
selector
.Parameter selector
The selector to query for.
Throws
Throws if there's no element matching
selector
.
method isDetached
isDetached: () => boolean;
Is
true
if the frame has been detached. Otherwise,false
.Deprecated
Use the
detached
getter.
method locator
locator: { <Selector extends string>(selector: Selector): Locator<NodeFor<Selector>>; <Ret>(func: () => Awaitable<Ret>): Locator<Ret>;};
Creates a locator for the provided selector. See Locator for details and supported actions.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Creates a locator for the provided function. See Locator for details and supported actions.
method name
name: () => string;
The frame's
name
attribute as specified in the tag.Remarks
This value is calculated once when the frame is created, and will not update if the attribute is changed later.
Deprecated
Use
const element = await frame.frameElement();const nameOrId = await element.evaluate(frame => frame.name ?? frame.id);
method page
abstract page: () => Page;
The page associated with the frame.
method parentFrame
abstract parentFrame: () => Frame | null;
The parent frame, if any. Detached and main frames return
null
.
method select
select: (selector: string, ...values: string[]) => Promise<string[]>;
Selects a set of value on the first
<select>
element that matches theselector
.Parameter selector
The selector to query for.
Parameter values
The array of values to select. If the
<select>
has themultiple
attribute, all values are considered, otherwise only the first one is taken into account.Returns
the list of values that were successfully selected.
Throws
Throws if there's no
<select>
matchingselector
.Example 1
frame.select('select#colors', 'blue'); // single selectionframe.select('select#colors', 'red', 'green', 'blue'); // multiple selections
method setContent
abstract setContent: (html: string, options?: WaitForOptions) => Promise<void>;
Set the content of the frame.
Parameter html
HTML markup to assign to the page.
Parameter options
Options to configure how long before timing out and at what point to consider the content setting successful.
method tap
tap: (selector: string) => Promise<void>;
Taps the first element that matches the
selector
.Parameter selector
The selector to query for.
Throws
Throws if there's no element matching
selector
.
method title
title: () => Promise<string>;
The frame's title.
method type
type: ( selector: string, text: string, options?: Readonly<KeyboardTypeOptions>) => Promise<void>;
Sends a
keydown
,keypress
/input
, andkeyup
event for each character in the text.Parameter selector
the selector for the element to type into. If there are multiple the first will be used.
Parameter text
text to type into the element
Parameter options
takes one option,
delay
, which sets the time to wait between key presses in milliseconds. Defaults to0
.Remarks
To press a special key, like
Control
orArrowDown
, use Keyboard.press.Example 1
await frame.type('#mytextarea', 'Hello'); // Types instantlyawait frame.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user
method url
abstract url: () => string;
The frame's URL.
method waitForFunction
waitForFunction: < Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>( pageFunction: Func | string, options?: FrameWaitForFunctionOptions, ...args: Params) => Promise<HandleFor<Awaited<ReturnType<Func>>>>;
Parameter pageFunction
the function to evaluate in the frame context.
Parameter options
options to configure the polling method and timeout.
Parameter args
arguments to pass to the
pageFunction
.Returns
the promise which resolve when the
pageFunction
returns a truthy value.Example 1
The
waitForFunction
can be used to observe viewport size change:import puppeteer from 'puppeteer';(async () => {. const browser = await puppeteer.launch();. const page = await browser.newPage();. const watchDog = page.mainFrame().waitForFunction('window.innerWidth < 100');. page.setViewport({width: 50, height: 50});. await watchDog;. await browser.close();})();To pass arguments from Node.js to the predicate of
page.waitForFunction
function:const selector = '.foo';await frame.waitForFunction(selector => !!document.querySelector(selector),{}, // empty options objectselector,);
method waitForNavigation
abstract waitForNavigation: ( options?: WaitForOptions) => Promise<HTTPResponse | null>;
Waits for the frame to navigate. It is useful for when you run code which will indirectly cause the frame to navigate.
Usage of the History API to change the URL is considered a navigation.
Parameter options
Options to configure waiting behavior.
Returns
A promise which resolves to the main resource response.
Example 1
const [response] = await Promise.all([// The navigation promise resolves after navigation has finishedframe.waitForNavigation(),// Clicking the link will indirectly cause a navigationframe.click('a.my-link'),]);
method waitForSelector
waitForSelector: <Selector extends string>( selector: Selector, options?: WaitForSelectorOptions) => Promise<ElementHandle<NodeFor<Selector>> | null>;
Waits for an element matching the given selector to appear in the frame.
This method works across navigations.
Parameter selector
The selector to query and wait for.
Parameter options
Options for customizing waiting behavior.
Returns
An element matching the given selector.
Throws
Throws if an element matching the given selector doesn't appear.
Example 1
import puppeteer from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();let currentURL;page.mainFrame().waitForSelector('img').then(() => console.log('First URL with image: ' + currentURL));for (currentURL of ['https://example.com','https://google.com','https://bbc.com',]) {await page.goto(currentURL);}await browser.close();})();
class HTTPRequest
abstract 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 therequestfailed
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.Modifiers
@public
property client
readonly client: CDPSession;
Warning! Using this client can break Puppeteer. Use with caution.
Modifiers
@experimental
method abort
abort: (errorCode?: ErrorCode, priority?: number) => Promise<void>;
Aborts a request.
Parameter errorCode
optional error code to provide.
Parameter priority
If provided, intercept is resolved using cooperative handling rules. Otherwise, intercept is resolved immediately.
Remarks
To use this, request interception should be enabled with Page.setRequestInterception. If it is not enabled, this method will throw an exception immediately.
method abortErrorReason
abortErrorReason: () => Protocol.Network.ErrorReason | null;
The most recent reason for aborting the request
method continue
continue: ( overrides?: ContinueRequestOverrides, priority?: number) => Promise<void>;
Continues request with optional request overrides.
Parameter overrides
optional overrides to apply to the request.
Parameter priority
If provided, intercept is resolved using cooperative handling rules. Otherwise, intercept is resolved immediately.
Remarks
To use this, request interception should be enabled with Page.setRequestInterception.
Exception is immediately thrown if the request interception is not enabled.
Example 1
await page.setRequestInterception(true);page.on('request', request => {// Override headersconst headers = Object.assign({}, request.headers(), {foo: 'bar', // set "foo" headerorigin: undefined, // remove "origin" header});request.continue({headers});});
method continueRequestOverrides
continueRequestOverrides: () => ContinueRequestOverrides;
The
ContinueRequestOverrides
that will be used if the interception is allowed to continue (ie,abort()
andrespond()
aren't called).
method enqueueInterceptAction
enqueueInterceptAction: ( pendingHandler: () => void | PromiseLike<unknown>) => void;
Adds an async request handler to the processing queue. Deferred handlers are not guaranteed to execute in any particular order, but they are guaranteed to resolve before the request interception is finalized.
method failure
abstract failure: () => { errorText: string } | null;
Access information about the request's failure.
Returns
null
unless the request failed. If the request fails this can return an object witherrorText
containing a human-readable error message, e.g.net::ERR_FAILED
. It is not guaranteed that there will be failure text if the request fails.Remarks
Example 1
Example of logging all failed requests:
page.on('requestfailed', request => {console.log(request.url() + ' ' + request.failure().errorText);});
method fetchPostData
abstract fetchPostData: () => Promise<string | undefined>;
Fetches the POST data for the request from the browser.
method finalizeInterceptions
finalizeInterceptions: () => Promise<void>;
Awaits pending interception handlers and then decides how to fulfill the request interception.
method frame
abstract frame: () => Frame | null;
The frame that initiated the request, or null if navigating to error pages.
method hasPostData
abstract hasPostData: () => boolean;
True when the request has POST data. Note that HTTPRequest.postData might still be undefined when this flag is true when the data is too long or not readily available in the decoded form. In that case, use HTTPRequest.fetchPostData.
method headers
abstract headers: () => Record<string, string>;
An object with HTTP headers associated with the request. All header names are lower-case.
method initiator
abstract initiator: () => Protocol.Network.Initiator | undefined;
The initiator of the request.
method interceptResolutionState
interceptResolutionState: () => InterceptResolutionState;
An InterceptResolutionState object describing the current resolution action and priority.
InterceptResolutionState contains: action: InterceptResolutionAction priority?: number
InterceptResolutionAction is one of:
abort
,respond
,continue
,disabled
,none
, oralready-handled
.
method isInterceptResolutionHandled
isInterceptResolutionHandled: () => boolean;
Is
true
if the intercept resolution has already been handled,false
otherwise.
method isNavigationRequest
abstract isNavigationRequest: () => boolean;
True if the request is the driver of the current frame's navigation.
method method
abstract method: () => string;
The method used (
GET
,POST
, etc.)
method postData
abstract postData: () => string | undefined;
The request's post body, if any.
method redirectChain
abstract redirectChain: () => HTTPRequest[];
A
redirectChain
is a chain of requests initiated to fetch a resource.Returns
the chain of requests - if a server responds with at least a single redirect, this chain will contain all requests that were redirected.
Remarks
redirectChain
is shared between all the requests of the same chain.For example, if the website
http://example.com
has a single redirect tohttps://example.com
, then the chain will contain one request:const response = await page.goto('http://example.com');const chain = response.request().redirectChain();console.log(chain.length); // 1console.log(chain[0].url()); // 'http://example.com'If the website
https://google.com
has no redirects, then the chain will be empty:const response = await page.goto('https://google.com');const chain = response.request().redirectChain();console.log(chain.length); // 0
method resourceType
abstract resourceType: () => Protocol.Network.ResourceType;
Contains the request's resource type as it was perceived by the rendering engine.
method respond
respond: ( response: Partial<ResponseForRequest>, priority?: number) => Promise<void>;
Fulfills a request with the given response.
Parameter response
the response to fulfill the request with.
Parameter priority
If provided, intercept is resolved using cooperative handling rules. Otherwise, intercept is resolved immediately.
Remarks
To use this, request interception should be enabled with Page.setRequestInterception.
Exception is immediately thrown if the request interception is not enabled.
Example 1
An example of fulfilling all requests with 404 responses:
await page.setRequestInterception(true);page.on('request', request => {request.respond({status: 404,contentType: 'text/plain',body: 'Not Found!',});});NOTE: Mocking responses for dataURL requests is not supported. Calling
request.respond
for a dataURL request is a noop.
method response
abstract response: () => HTTPResponse | null;
A matching
HTTPResponse
object, or null if the response has not been received yet.
method responseForRequest
responseForRequest: () => Partial<ResponseForRequest> | null;
The
ResponseForRequest
that gets used if the interception is allowed to respond (ie,abort()
is not called).
method url
abstract url: () => string;
The URL of the request
class HTTPResponse
abstract class HTTPResponse {}
The HTTPResponse class represents responses which are received by the Page class.
Modifiers
@public
method buffer
buffer: () => Promise<Buffer>;
See documentation for HTTPResponse.content.
method content
abstract content: () => Promise<Uint8Array>;
Promise which resolves to a buffer with response body.
Remarks
The buffer might be re-encoded by the browser based on HTTP-headers or other heuristics. If the browser failed to detect the correct encoding, the buffer might be encoded incorrectly. See https://github.com/puppeteer/puppeteer/issues/6478.
method frame
abstract frame: () => Frame | null;
A Frame that initiated this response, or
null
if navigating to error pages.
method fromCache
abstract fromCache: () => boolean;
True if the response was served from either the browser's disk cache or memory cache.
method fromServiceWorker
abstract fromServiceWorker: () => boolean;
True if the response was served by a service worker.
method headers
abstract headers: () => Record<string, string>;
An object with HTTP headers associated with the response. All header names are lower-case.
method json
json: () => Promise<any>;
Promise which resolves to a JSON representation of response body.
Remarks
This method will throw if the response body is not parsable via
JSON.parse
.
method ok
ok: () => boolean;
True if the response was successful (status in the range 200-299).
method remoteAddress
abstract remoteAddress: () => RemoteAddress;
The IP address and port number used to connect to the remote server.
method request
abstract request: () => HTTPRequest;
A matching HTTPRequest object.
method securityDetails
abstract securityDetails: () => SecurityDetails | null;
SecurityDetails if the response was received over the secure connection, or
null
otherwise.
method status
abstract status: () => number;
The status code of the response (e.g., 200 for a success).
method statusText
abstract statusText: () => string;
The status text of the response (e.g. usually an "OK" for a success).
method text
text: () => Promise<string>;
Promise which resolves to a text (utf8) representation of response body.
method timing
abstract timing: () => Protocol.Network.ResourceTiming | null;
Timing information related to the response.
method url
abstract url: () => string;
The URL of the response.
class JSCoverage
class JSCoverage {}
Modifiers
@public
class JSHandle
abstract class JSHandle<T = unknown> {}
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.
Example 1
const windowHandle = await page.evaluateHandle(() => window);Modifiers
@public
property move
move: () => this;
method asElement
abstract asElement: () => ElementHandle<Node> | null;
Either
null
or the handle itself if the handle is an instance of ElementHandle.
method dispose
abstract dispose: () => Promise<void>;
Releases the object referenced by the handle for garbage collection.
method evaluate
evaluate: < Params extends unknown[], Func extends EvaluateFuncWith<T, Params> = EvaluateFuncWith<T, Params>>( pageFunction: Func | string, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
Evaluates the given function with the current handle as its first argument.
method evaluateHandle
evaluateHandle: < Params extends unknown[], Func extends EvaluateFuncWith<T, Params> = EvaluateFuncWith<T, Params>>( pageFunction: Func | string, ...args: Params) => Promise<HandleFor<Awaited<ReturnType<Func>>>>;
Evaluates the given function with the current handle as its first argument.
method getProperties
getProperties: () => Promise<Map<string, JSHandle>>;
Gets a map of handles representing the properties of the current handle.
Example 1
const listHandle = await page.evaluateHandle(() => document.body.children);const properties = await listHandle.getProperties();const children = [];for (const property of properties.values()) {const element = property.asElement();if (element) {children.push(element);}}children; // holds elementHandles to all children of document.body
method getProperty
getProperty: { <K extends keyof T>(propertyName: HandleOr<K>): Promise<HandleFor<T[K]>>; (propertyName: string): Promise<JSHandle<unknown>>;};
Fetches a single property from the referenced object.
method jsonValue
abstract jsonValue: () => Promise<T>;
A vanilla object representing the serializable portions of the referenced object.
Throws
Throws if the object cannot be serialized due to circularity.
Remarks
If the object has a
toJSON
function, it **will not** be called.
method remoteObject
abstract remoteObject: () => Protocol.Runtime.RemoteObject;
Provides access to the Protocol.Runtime.RemoteObject backing this handle.
method toString
abstract toString: () => string;
Returns a string representation of the JSHandle.
Remarks
Useful during debugging.
class Keyboard
abstract 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.Example 1
An example of holding down
Shift
in order to select and delete some text:await page.keyboard.type('Hello World!');await page.keyboard.press('ArrowLeft');await page.keyboard.down('Shift');for (let i = 0; i < ' World'.length; i++)await page.keyboard.press('ArrowLeft');await page.keyboard.up('Shift');await page.keyboard.press('Backspace');// Result text will end up saying 'Hello!'Example 2
An example of pressing
A
await page.keyboard.down('Shift');await page.keyboard.press('KeyA');await page.keyboard.up('Shift');Modifiers
@public
method down
abstract down: ( key: KeyInput, options?: Readonly<KeyDownOptions>) => Promise<void>;
Dispatches a
keydown
event.Parameter key
Name of key to press, such as
ArrowLeft
. See KeyInput for a list of all key names.Parameter options
An object of options. Accepts text which, if specified, generates an input event with this text. Accepts commands which, if specified, is the commands of keyboard shortcuts, see Chromium Source Code for valid command names.
Remarks
If
key
is a single character and no modifier keys besidesShift
are being held down, akeypress
/input
event will also generated. Thetext
option can be specified to force an input event to be generated. Ifkey
is a modifier key,Shift
,Meta
,Control
, orAlt
, subsequent key presses will be sent with that modifier active. To release the modifier key, use Keyboard.up.After the key is pressed once, subsequent calls to Keyboard.down will have repeat set to true. To release the key, use Keyboard.up.
Modifier keys DO influence Keyboard.down. Holding down
Shift
will type the text in upper case.
method press
abstract press: ( key: KeyInput, options?: Readonly<KeyPressOptions>) => Promise<void>;
Shortcut for Keyboard.down and Keyboard.up.
Parameter key
Name of key to press, such as
ArrowLeft
. See KeyInput for a list of all key names.Parameter options
An object of options. Accepts text which, if specified, generates an input event with this text. Accepts delay which, if specified, is the time to wait between
keydown
andkeyup
in milliseconds. Defaults to 0. Accepts commands which, if specified, is the commands of keyboard shortcuts, see Chromium Source Code for valid command names.Remarks
If
key
is a single character and no modifier keys besidesShift
are being held down, akeypress
/input
event will also generated. Thetext
option can be specified to force an input event to be generated.Modifier keys DO effect Keyboard.press. Holding down
Shift
will type the text in upper case.
method sendCharacter
abstract sendCharacter: (char: string) => Promise<void>;
Dispatches a
keypress
andinput
event. This does not send akeydown
orkeyup
event.Parameter char
Character to send into the page.
Remarks
Modifier keys DO NOT effect Keyboard.sendCharacter. Holding down
Shift
will not type the text in upper case.Example 1
page.keyboard.sendCharacter('å—¨');
method type
abstract type: ( text: string, options?: Readonly<KeyboardTypeOptions>) => Promise<void>;
Sends a
keydown
,keypress
/input
, andkeyup
event for each character in the text.Parameter text
A text to type into a focused element.
Parameter options
An object of options. Accepts delay which, if specified, is the time to wait between
keydown
andkeyup
in milliseconds. Defaults to 0.Remarks
To press a special key, like
Control
orArrowDown
, use Keyboard.press.Modifier keys DO NOT effect
keyboard.type
. Holding downShift
will not type the text in upper case.Example 1
await page.keyboard.type('Hello'); // Types instantlyawait page.keyboard.type('World', {delay: 100}); // Types slower, like a user
method up
abstract up: (key: KeyInput) => Promise<void>;
Dispatches a
keyup
event.Parameter key
Name of key to release, such as
ArrowLeft
. See KeyInput for a list of all key names.
class Locator
abstract class Locator<T> extends EventEmitter<LocatorEvents> {}
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.
See https://pptr.dev/guides/page-interactions#locators for details.
Modifiers
@public
property timeout
readonly timeout: number;
method click
click: <ElementType extends Element>( this: Locator<ElementType>, options?: Readonly<LocatorClickOptions>) => Promise<void>;
Clicks the located element.
method clone
clone: () => Locator<T>;
Clones the locator.
method fill
fill: <ElementType extends Element>( this: Locator<ElementType>, value: string, options?: Readonly<ActionOptions>) => Promise<void>;
Fills out the input identified by the locator using the provided value. The type of the input is determined at runtime and the appropriate fill-out method is chosen based on the type.
contenteditable
, select, textarea and input elements are supported.
method filter
filter: <S extends T>(predicate: Predicate<T, S>) => Locator<S>;
Creates an expectation that is evaluated against located values.
If the expectations do not match, then the locator will retry.
Modifiers
@public
method hover
hover: <ElementType extends Element>( this: Locator<ElementType>, options?: Readonly<ActionOptions>) => Promise<void>;
Hovers over the located element.
method map
map: <To>(mapper: Mapper<T, To>) => Locator<To>;
Maps the locator using the provided mapper.
Modifiers
@public
method race
static race: <Locators extends readonly unknown[] | []>( locators: Locators) => Locator<AwaitedLocator<Locators[number]>>;
Creates a race between multiple locators trying to locate elements in parallel but ensures that only a single element receives the action.
Modifiers
@public
method scroll
scroll: <ElementType extends Element>( this: Locator<ElementType>, options?: Readonly<LocatorScrollOptions>) => Promise<void>;
Scrolls the located element.
method setEnsureElementIsInTheViewport
setEnsureElementIsInTheViewport: <ElementType extends Element>( this: Locator<ElementType>, value: boolean) => Locator<ElementType>;
Creates a new locator instance by cloning the current locator and specifying whether the locator should scroll the element into viewport if it is not in the viewport already.
method setTimeout
setTimeout: (timeout: number) => Locator<T>;
Creates a new locator instance by cloning the current locator and setting the total timeout for the locator actions.
Pass
0
to disable timeout.
method setVisibility
setVisibility: <NodeType extends Node>( this: Locator<NodeType>, visibility: VisibilityOption) => Locator<NodeType>;
Creates a new locator instance by cloning the current locator with the visibility property changed to the specified value.
method setWaitForEnabled
setWaitForEnabled: <NodeType extends Node>( this: Locator<NodeType>, value: boolean) => Locator<NodeType>;
Creates a new locator instance by cloning the current locator and specifying whether to wait for input elements to become enabled before the action. Applicable to
click
andfill
actions.
method setWaitForStableBoundingBox
setWaitForStableBoundingBox: <ElementType extends Element>( this: Locator<ElementType>, value: boolean) => Locator<ElementType>;
Creates a new locator instance by cloning the current locator and specifying whether the locator has to wait for the element's bounding box to be same between two consecutive animation frames.
method wait
wait: (options?: Readonly<ActionOptions>) => Promise<T>;
Waits for the locator to get the serialized value from the page.
Note this requires the value to be JSON-serializable.
Modifiers
@public
method waitHandle
waitHandle: (options?: Readonly<ActionOptions>) => Promise<HandleFor<T>>;
Waits for the locator to get a handle from the page.
Modifiers
@public
class Mouse
abstract class 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.Example 1
// Using ‘page.mouse’ to trace a 100x100 square.await page.mouse.move(0, 0);await page.mouse.down();await page.mouse.move(0, 100);await page.mouse.move(100, 100);await page.mouse.move(100, 0);await page.mouse.move(0, 0);await page.mouse.up();**Note**: The mouse events trigger synthetic
MouseEvent
s. This means that it does not fully replicate the functionality of what a normal user would be able to do with their mouse.For example, dragging and selecting text is not possible using
page.mouse
. Instead, you can use the `DocumentOrShadowRoot.getSelection()` functionality implemented in the platform.Example 2
For example, if you want to select all content between nodes:
await page.evaluate((from, to) => {const selection = from.getRootNode().getSelection();const range = document.createRange();range.setStartBefore(from);range.setEndAfter(to);selection.removeAllRanges();selection.addRange(range);},fromJSHandle,toJSHandle,);If you then would want to copy-paste your selection, you can use the clipboard api:
// The clipboard api does not allow you to copy, unless the tab is focused.await page.bringToFront();await page.evaluate(() => {// Copy the selected content to the clipboarddocument.execCommand('copy');// Obtain the content of the clipboard as a stringreturn navigator.clipboard.readText();});**Note**: If you want access to the clipboard API, you have to give it permission to do so:
await browser.defaultBrowserContext().overridePermissions('<your origin>', ['clipboard-read','clipboard-write',]);Modifiers
@public
method click
abstract click: ( x: number, y: number, options?: Readonly<MouseClickOptions>) => Promise<void>;
Shortcut for
mouse.move
,mouse.down
andmouse.up
.Parameter x
Horizontal position of the mouse.
Parameter y
Vertical position of the mouse.
Parameter options
Options to configure behavior.
method down
abstract down: (options?: Readonly<MouseOptions>) => Promise<void>;
Presses the mouse.
Parameter options
Options to configure behavior.
method drag
abstract drag: (start: Point, target: Point) => Promise<Protocol.Input.DragData>;
Dispatches a
drag
event.Parameter start
starting point for drag
Parameter target
point to drag to
method dragAndDrop
abstract dragAndDrop: ( start: Point, target: Point, options?: { delay?: number }) => Promise<void>;
Performs a drag, dragenter, dragover, and drop in sequence.
Parameter start
point to drag from
Parameter target
point to drop on
Parameter options
An object of options. Accepts delay which, if specified, is the time to wait between
dragover
anddrop
in milliseconds. Defaults to 0.
method dragEnter
abstract dragEnter: ( target: Point, data: Protocol.Input.DragData) => Promise<void>;
Dispatches a
dragenter
event.Parameter target
point for emitting
dragenter
eventParameter data
drag data containing items and operations mask
method dragOver
abstract dragOver: ( target: Point, data: Protocol.Input.DragData) => Promise<void>;
Dispatches a
dragover
event.Parameter target
point for emitting
dragover
eventParameter data
drag data containing items and operations mask
method drop
abstract drop: (target: Point, data: Protocol.Input.DragData) => Promise<void>;
Performs a dragenter, dragover, and drop in sequence.
Parameter target
point to drop on
Parameter data
drag data containing items and operations mask
method move
abstract move: ( x: number, y: number, options?: Readonly<MouseMoveOptions>) => Promise<void>;
Moves the mouse to the given coordinate.
Parameter x
Horizontal position of the mouse.
Parameter y
Vertical position of the mouse.
Parameter options
Options to configure behavior.
method reset
abstract reset: () => Promise<void>;
Resets the mouse to the default state: No buttons pressed; position at (0,0).
method up
abstract up: (options?: Readonly<MouseOptions>) => Promise<void>;
Releases the mouse.
Parameter options
Options to configure behavior.
method wheel
abstract wheel: (options?: Readonly<MouseWheelOptions>) => Promise<void>;
Dispatches a
mousewheel
event.Parameter options
Optional:
MouseWheelOptions
.Example 1
An example of zooming into an element:
await page.goto('https://mdn.mozillademos.org/en-US/docs/Web/API/Element/wheel_event$samples/Scaling_an_element_via_the_wheel?revision=1587366',);const elem = await page.$('div');const boundingBox = await elem.boundingBox();await page.mouse.move(boundingBox.x + boundingBox.width / 2,boundingBox.y + boundingBox.height / 2,);await page.mouse.wheel({deltaY: -100});
class Page
abstract class Page extends EventEmitter<PageEvents> {}
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.
:::
Example 1
This example creates a page, navigates it to a URL, and then saves a screenshot:
import puppeteer from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();await page.goto('https://example.com');await page.screenshot({path: 'screenshot.png'});await browser.close();})();The Page class extends from Puppeteer's EventEmitter class and will emit various events which are documented in the PageEvent enum.
Example 2
This example logs a message for a single page
load
event:page.once('load', () => console.log('Page loaded!'));To unsubscribe from events use the EventEmitter.off method:
function logRequest(interceptedRequest) {console.log('A request was made:', interceptedRequest.url());}page.on('request', logRequest);// Sometime later...page.off('request', logRequest);Modifiers
@public
property accessibility
readonly accessibility: Accessibility;
See documentation for Accessibility.
property coverage
readonly coverage: Coverage;
See documentation for Coverage.
property keyboard
readonly keyboard: Keyboard;
See documentation for Keyboard.
property mouse
readonly mouse: Mouse;
See documentation for Mouse.
property touchscreen
readonly touchscreen: Touchscreen;
See documentation for Touchscreen.
property tracing
readonly tracing: Tracing;
See documentation for Tracing.
method $
$: <Selector extends string>( selector: Selector) => Promise<ElementHandle<NodeFor<Selector>> | null>;
Finds the first element that matches the selector. If no element matches the selector, the return value resolves to
null
.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Remarks
Shortcut for Page.mainFrame().$(selector).
method $$
$$: <Selector extends string>( selector: Selector, options?: QueryOptions) => Promise<Array<ElementHandle<NodeFor<Selector>>>>;
Finds elements on the page that match the selector. If no elements match the selector, the return value resolves to
[]
.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Remarks
Shortcut for Page.mainFrame().$$(selector).
method $$eval
$$eval: < Selector extends string, Params extends unknown[], Func extends EvaluateFuncWith< ParseSelector<ComplexSelector>[], Params > = EvaluateFuncWith<ParseSelector<ComplexSelector>[], Params>>( selector: Selector, pageFunction: Func | string, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
This method returns all elements matching the selector and passes the resulting array as the first argument to the
pageFunction
.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Parameter pageFunction
the function to be evaluated in the page context. Will be passed an array of matching elements as its first argument.
Parameter args
any additional arguments to pass through to
pageFunction
.Returns
The result of calling
pageFunction
. If it returns an element it is wrapped in an ElementHandle, else the raw value itself is returned.Remarks
If
pageFunction
returns a promise$$eval
will wait for the promise to resolve and then return its value.Example 1
// get the amount of divs on the pageconst divCount = await page.$$eval('div', divs => divs.length);// get the text content of all the `.options` elements:const options = await page.$$eval('div > span.options', options => {return options.map(option => option.textContent);});If you are using TypeScript, you may have to provide an explicit type to the first argument of the
pageFunction
. By default it is typed asElement[]
, but you may need to provide a more specific sub-type:Example 2
await page.$$eval('input', elements => {return elements.map(e => e.value);});The compiler should be able to infer the return type from the
pageFunction
you provide. If it is unable to, you can use the generic type to tell the compiler what return type you expect from$$eval
:Example 3
const allInputValues = await page.$$eval('input', elements =>elements.map(e => e.textContent),);
method $eval
$eval: < Selector extends string, Params extends unknown[], Func extends EvaluateFuncWith< ParseSelector<ComplexSelector>, Params > = EvaluateFuncWith<ParseSelector<ComplexSelector>, Params>>( selector: Selector, pageFunction: Func | string, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
This method finds the first element within the page that matches the selector and passes the result as the first argument to the
pageFunction
.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Parameter pageFunction
the function to be evaluated in the page context. Will be passed the result of the element matching the selector as its first argument.
Parameter args
any additional arguments to pass through to
pageFunction
.Returns
The result of calling
pageFunction
. If it returns an element it is wrapped in an ElementHandle, else the raw value itself is returned.Remarks
If no element is found matching
selector
, the method will throw an error.If
pageFunction
returns a promise$eval
will wait for the promise to resolve and then return its value.Example 1
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', el => el.outerHTML);If you are using TypeScript, you may have to provide an explicit type to the first argument of the
pageFunction
. By default it is typed asElement
, but you may need to provide a more specific sub-type:Example 2
// if you don't provide HTMLInputElement here, TS will error// as `value` is not on `Element`const searchValue = await page.$eval('#search',(el: HTMLInputElement) => el.value,);The compiler should be able to infer the return type from the
pageFunction
you provide. If it is unable to, you can use the generic type to tell the compiler what return type you expect from$eval
:Example 3
// The compiler can infer the return type in this case, but if it can't// or if you want to be more explicit, provide it as the generic type.const searchValue = await page.$eval<string>('#search',(el: HTMLInputElement) => el.value,);
method addScriptTag
addScriptTag: ( options: FrameAddScriptTagOptions) => Promise<ElementHandle<HTMLScriptElement>>;
Adds a
<script>
tag into the page with the desired URL or content.Parameter options
Options for the script.
Returns
An element handle to the injected
<script>
element.Remarks
Shortcut for page.mainFrame().addScriptTag(options).
method addStyleTag
addStyleTag: { (options: Omit<FrameAddStyleTagOptions, 'url'>): Promise< ElementHandle<HTMLStyleElement> >; (options: FrameAddStyleTagOptions): Promise<ElementHandle<HTMLLinkElement>>;};
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).
Returns
An element handle to the injected
<link>
or<style>
element.
method authenticate
abstract authenticate: (credentials: Credentials | null) => Promise<void>;
Provide credentials for
HTTP authentication
.:::note
Request interception will be turned on behind the scenes to implement authentication. This might affect performance.
:::
Remarks
To disable authentication, pass
null
.
method bringToFront
abstract bringToFront: () => Promise<void>;
Brings page to front (activates tab).
method browser
abstract browser: () => Browser;
Get the browser the page belongs to.
method browserContext
abstract browserContext: () => BrowserContext;
Get the browser context that the page belongs to.
method click
click: (selector: string, options?: Readonly<ClickOptions>) => Promise<void>;
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 matchingselector
, the method throws an error.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix. If there are multiple elements satisfying the
selector
, the first will be clickedParameter options
Object
Returns
Promise which resolves when the element matching
selector
is successfully clicked. The Promise will be rejected if there is no element matchingselector
.Remarks
Bear in mind that if
click()
triggers a navigation event and there's a separatepage.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:const [response] = await Promise.all([page.waitForNavigation(waitOptions),page.click(selector, clickOptions),]);Shortcut for page.mainFrame().click(selector[, options]).
method close
abstract close: (options?: { runBeforeUnload?: boolean }) => Promise<void>;
method content
content: () => Promise<string>;
The full HTML contents of the page, including the DOCTYPE.
method cookies
abstract cookies: (...urls: string[]) => Promise<Cookie[]>;
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.
method createCDPSession
abstract createCDPSession: () => Promise<CDPSession>;
Creates a Chrome Devtools Protocol session attached to the page.
method createPDFStream
abstract createPDFStream: ( options?: PDFOptions) => Promise<ReadableStream<Uint8Array>>;
Generates a PDF of the page with the
print
CSS media type.Parameter options
options for generating the PDF.
Remarks
To generate a PDF with the
screen
media type, call `page.emulateMediaType('screen')` before callingpage.pdf()
.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.
method deleteCookie
abstract deleteCookie: (...cookies: DeleteCookiesRequest[]) => Promise<void>;
method emulate
emulate: (device: Device) => Promise<void>;
Emulates a given device's metrics and user agent.
To aid emulation, Puppeteer provides a list of known devices that can be via KnownDevices.
Remarks
This method is a shortcut for calling two methods: Page.setUserAgent and Page.setViewport.
This method will resize the page. A lot of websites don't expect phones to change size, so you should emulate before navigating to the page.
Example 1
import {KnownDevices} from 'puppeteer';const iPhone = KnownDevices['iPhone 15 Pro'];(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();await page.emulate(iPhone);await page.goto('https://www.google.com');// other actions...await browser.close();})();
method emulateCPUThrottling
abstract emulateCPUThrottling: (factor: number | null) => Promise<void>;
Enables CPU throttling to emulate slow CPUs.
Parameter factor
slowdown factor (1 is no throttle, 2 is 2x slowdown, etc).
method emulateIdleState
abstract emulateIdleState: (overrides?: { isUserActive: boolean; isScreenUnlocked: boolean;}) => Promise<void>;
Emulates the idle state. If no arguments set, clears idle state emulation.
Parameter overrides
Mock idle state. If not set, clears idle overrides
Example 1
// set idle emulationawait page.emulateIdleState({isUserActive: true, isScreenUnlocked: false});// do some checks here...// clear idle emulationawait page.emulateIdleState();
method emulateMediaFeatures
abstract emulateMediaFeatures: (features?: MediaFeature[]) => Promise<void>;
Parameter features
<?Array<Object>>
Given an array of media feature objects, emulates CSS media features on the page. Each media feature object must have the following properties:Example 1
await page.emulateMediaFeatures([{name: 'prefers-color-scheme', value: 'dark'},]);await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches,);// → trueawait page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches,);// → falseawait page.emulateMediaFeatures([{name: 'prefers-reduced-motion', value: 'reduce'},]);await page.evaluate(() => matchMedia('(prefers-reduced-motion: reduce)').matches,);// → trueawait page.evaluate(() => matchMedia('(prefers-reduced-motion: no-preference)').matches,);// → falseawait page.emulateMediaFeatures([{name: 'prefers-color-scheme', value: 'dark'},{name: 'prefers-reduced-motion', value: 'reduce'},]);await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches,);// → trueawait page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches,);// → falseawait page.evaluate(() => matchMedia('(prefers-reduced-motion: reduce)').matches,);// → trueawait page.evaluate(() => matchMedia('(prefers-reduced-motion: no-preference)').matches,);// → falseawait page.emulateMediaFeatures([{name: 'color-gamut', value: 'p3'}]);await page.evaluate(() => matchMedia('(color-gamut: srgb)').matches);// → trueawait page.evaluate(() => matchMedia('(color-gamut: p3)').matches);// → trueawait page.evaluate(() => matchMedia('(color-gamut: rec2020)').matches);// → false
method emulateMediaType
abstract emulateMediaType: (type?: string) => Promise<void>;
Parameter type
Changes the CSS media type of the page. The only allowed values are
screen
,print
andnull
. Passingnull
disables CSS media emulation.Example 1
await page.evaluate(() => matchMedia('screen').matches);// → trueawait page.evaluate(() => matchMedia('print').matches);// → falseawait page.emulateMediaType('print');await page.evaluate(() => matchMedia('screen').matches);// → falseawait page.evaluate(() => matchMedia('print').matches);// → trueawait page.emulateMediaType(null);await page.evaluate(() => matchMedia('screen').matches);// → trueawait page.evaluate(() => matchMedia('print').matches);// → false
method emulateNetworkConditions
abstract emulateNetworkConditions: ( networkConditions: NetworkConditions | null) => Promise<void>;
This does not affect WebSockets and WebRTC PeerConnections (see https://crbug.com/563644). To set the page offline, you can use Page.setOfflineMode.
A list of predefined network conditions can be used by importing PredefinedNetworkConditions.
Parameter networkConditions
Passing
null
disables network condition emulation.Example 1
import {PredefinedNetworkConditions} from 'puppeteer';const slow3G = PredefinedNetworkConditions['Slow 3G'];(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();await page.emulateNetworkConditions(slow3G);await page.goto('https://www.google.com');// other actions...await browser.close();})();
method emulateTimezone
abstract emulateTimezone: (timezoneId?: string) => Promise<void>;
Parameter timezoneId
Changes the timezone of the page. See ICU’s metaZones.txt for a list of supported timezone IDs. Passing
null
disables timezone emulation.
method emulateVisionDeficiency
abstract emulateVisionDeficiency: ( type?: Protocol.Emulation.SetEmulatedVisionDeficiencyRequest) => Promise<void>;
Simulates the given vision deficiency on the page.
Parameter type
the type of deficiency to simulate, or
'none'
to reset.Example 1
import puppeteer from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();await page.goto('https://v8.dev/blog/10-years');await page.emulateVisionDeficiency('achromatopsia');await page.screenshot({path: 'achromatopsia.png'});await page.emulateVisionDeficiency('deuteranopia');await page.screenshot({path: 'deuteranopia.png'});await page.emulateVisionDeficiency('blurredVision');await page.screenshot({path: 'blurred-vision.png'});await browser.close();})();
method evaluate
evaluate: < Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>( pageFunction: Func | string, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
Evaluates a function in the page's context and returns the result.
If the function passed to
page.evaluate
returns a Promise, the function will wait for the promise to resolve and return its value.Parameter pageFunction
a function that is run within the page
Parameter args
arguments to be passed to the pageFunction
Returns
the return value of
pageFunction
.Example 1
const result = await frame.evaluate(() => {return Promise.resolve(8 * 7);});console.log(result); // prints "56"You can pass a string instead of a function (although functions are recommended as they are easier to debug and use with TypeScript):
Example 2
const aHandle = await page.evaluate('1 + 2');To get the best TypeScript experience, you should pass in as the generic the type of
pageFunction
:const aHandle = await page.evaluate(() => 2);Example 3
ElementHandle instances (including JSHandles) can be passed as arguments to the
pageFunction
:const bodyHandle = await page.$('body');const html = await page.evaluate(body => body.innerHTML, bodyHandle);await bodyHandle.dispose();
method evaluateHandle
evaluateHandle: < Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>( pageFunction: Func | string, ...args: Params) => Promise<HandleFor<Awaited<ReturnType<Func>>>>;
Parameter pageFunction
a function that is run within the page
Parameter args
arguments to be passed to the pageFunction
Remarks
The only difference between page.evaluate and
page.evaluateHandle
is thatevaluateHandle
will return the value wrapped in an in-page object.If the function passed to
page.evaluateHandle
returns a Promise, the function will wait for the promise to resolve and return its value.You can pass a string instead of a function (although functions are recommended as they are easier to debug and use with TypeScript):
Example 1
const aHandle = await page.evaluateHandle('document');Example 2
JSHandle instances can be passed as arguments to the
pageFunction
:const aHandle = await page.evaluateHandle(() => document.body);const resultHandle = await page.evaluateHandle(body => body.innerHTML,aHandle,);console.log(await resultHandle.jsonValue());await resultHandle.dispose();Most of the time this function returns a JSHandle, but if
pageFunction
returns a reference to an element, you instead get an ElementHandle back:Example 3
const button = await page.evaluateHandle(() =>document.querySelector('button'),);// can call `click` because `button` is an `ElementHandle`await button.click();The TypeScript definitions assume that
evaluateHandle
returns aJSHandle
, but if you know it's going to return anElementHandle
, pass it as the generic argument:const button = await page.evaluateHandle<ElementHandle>(...);
method evaluateOnNewDocument
abstract evaluateOnNewDocument: < Params extends unknown[], Func extends (...args: Params) => unknown = (...args: Params) => unknown>( pageFunction: Func | string, ...args: Params) => Promise<NewDocumentScriptEvaluation>;
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
.Parameter pageFunction
Function to be evaluated in browser context
Parameter args
Arguments to pass to
pageFunction
Example 1
An example of overriding the navigator.languages property before the page loads:
// preload.js// overwrite the `languages` property to use a custom getterObject.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);
method exposeFunction
abstract exposeFunction: ( name: string, pptrFunction: Function | { default: Function }) => Promise<void>;
The method adds a function called
name
on the page'swindow
object. When called, the function executespuppeteerFunction
in node.js and returns aPromise
which resolves to the return value ofpuppeteerFunction
.If the puppeteerFunction returns a
Promise
, it will be awaited.:::note
Functions installed via
page.exposeFunction
survive navigations.:::
Parameter name
Name of the function on the window object
Parameter pptrFunction
Callback function which will be called in Puppeteer's context.
Example 1
An example of adding an
md5
function into the page:import puppeteer from 'puppeteer';import crypto from 'crypto';(async () => {const browser = await puppeteer.launch();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 hashesconst myString = 'PUPPETEER';const myHash = await window.md5(myString);console.log(`md5 of ${myString} is ${myHash}`);});await browser.close();})();Example 2
An example of adding a
window.readfile
function into the page:import puppeteer from 'puppeteer';import fs from 'fs';(async () => {const browser = await puppeteer.launch();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 fileconst content = await window.readfile('/etc/hosts');console.log(content);});await browser.close();})();
method focus
focus: (selector: string) => Promise<void>;
This method fetches an element with
selector
and focuses it. If there's no element matchingselector
, the method throws an error.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix. 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.
Remarks
Shortcut for page.mainFrame().focus(selector).
method frames
abstract frames: () => Frame[];
An array of all frames attached to the page.
method getDefaultTimeout
abstract getDefaultTimeout: () => number;
Maximum time in milliseconds.
method goBack
abstract goBack: (options?: WaitForOptions) => Promise<HTTPResponse | null>;
This method navigate to the previous page in history.
Parameter options
Navigation parameters
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
.
method goForward
abstract goForward: (options?: WaitForOptions) => Promise<HTTPResponse | null>;
This method navigate to the next page in history.
Parameter options
Navigation Parameter
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
.
method goto
goto: (url: string, options?: GoToOptions) => Promise<HTTPResponse | null>;
See documentation for Frame.goto.
method hover
hover: (selector: string) => Promise<void>;
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 matchingselector
, the method throws an error.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix. 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 matchingselector
.Remarks
Shortcut for page.mainFrame().hover(selector).
method isClosed
abstract isClosed: () => boolean;
Indicates that the page has been closed.
Returns
method isDragInterceptionEnabled
abstract isDragInterceptionEnabled: () => boolean;
true
if drag events are being intercepted,false
otherwise.Deprecated
We no longer support intercepting drag payloads. Use the new drag APIs found on ElementHandle to drag (or just use the Page.mouse).
method isJavaScriptEnabled
abstract isJavaScriptEnabled: () => boolean;
true
if the page has JavaScript enabled,false
otherwise.
method isServiceWorkerBypassed
abstract isServiceWorkerBypassed: () => boolean;
true
if the service worker are being bypassed,false
otherwise.
method locator
locator: { <Selector extends string>(selector: Selector): Locator<NodeFor<Selector>>; <Ret>(func: () => Awaitable<Ret>): Locator<Ret>;};
Creates a locator for the provided selector. See Locator for details and supported actions.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Creates a locator for the provided function. See Locator for details and supported actions.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
method mainFrame
abstract mainFrame: () => Frame;
The page's main frame.
method metrics
abstract metrics: () => Promise<Metrics>;
Object containing metrics as key/value pairs.
Returns
-
Timestamp
: The timestamp when the metrics sample was taken.-
Documents
: Number of documents in the page.-
Frames
: Number of frames in the page.-
JSEventListeners
: Number of events in the page.-
Nodes
: Number of DOM nodes in the page.-
LayoutCount
: Total number of full or partial page layout.-
RecalcStyleCount
: Total number of page style recalculations.-
LayoutDuration
: Combined durations of all page layouts.-
RecalcStyleDuration
: Combined duration of all page style recalculations.-
ScriptDuration
: Combined duration of JavaScript execution.-
TaskDuration
: Combined duration of all tasks performed by the browser.-
JSHeapUsedSize
: Used JavaScript heap size.-
JSHeapTotalSize
: Total JavaScript heap size.Remarks
All timestamps are in monotonic time: monotonically increasing time in seconds since an arbitrary point in the past.
method pdf
abstract pdf: (options?: PDFOptions) => Promise<Uint8Array>;
See documentation for Page.createPDFStream.
method queryObjects
abstract queryObjects: <Prototype>( prototypeHandle: JSHandle<Prototype>) => Promise<JSHandle<Prototype[]>>;
This method iterates the JavaScript heap and finds all objects with the given prototype.
Parameter prototypeHandle
a handle to the object prototype.
Returns
Promise which resolves to a handle to an array of objects with this prototype.
Example 1
// Create a Map objectawait page.evaluate(() => (window.map = new Map()));// Get a handle to the Map object prototypeconst mapPrototype = await page.evaluateHandle(() => Map.prototype);// Query all map instances into an arrayconst mapInstances = await page.queryObjects(mapPrototype);// Count amount of map objects in heapconst count = await page.evaluate(maps => maps.length, mapInstances);await mapInstances.dispose();await mapPrototype.dispose();
method reload
abstract reload: (options?: WaitForOptions) => Promise<HTTPResponse | null>;
Reloads the page.
Parameter options
Options to configure waiting behavior.
Returns
A promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
method removeExposedFunction
abstract removeExposedFunction: (name: string) => Promise<void>;
The method removes a previously added function via $Page.exposeFunction called
name
from the page'swindow
object.
method removeScriptToEvaluateOnNewDocument
abstract removeScriptToEvaluateOnNewDocument: ( identifier: string) => Promise<void>;
Removes script that injected into page by Page.evaluateOnNewDocument.
Parameter identifier
script identifier
method screencast
screencast: (options?: Readonly<ScreencastOptions>) => Promise<ScreenRecorder>;
Captures a screencast of this page.
Parameter options
Configures screencast behavior.
Remarks
All recordings will be WebM format using the VP9 video codec. The FPS is 30.
You must have ffmpeg installed on your system.
Example 1
Recording a page:
import puppeteer from 'puppeteer';// Launch a browserconst browser = await puppeteer.launch();// Create a new pageconst page = await browser.newPage();// Go to your site.await page.goto("https://www.example.com");// Start recording.const recorder = await page.screencast({path: 'recording.webm'});// Do something.// Stop recording.await recorder.stop();browser.close();Modifiers
@experimental
method screenshot
screenshot: { ( options: Readonly<ScreenshotOptions> & { encoding: 'base64' } ): Promise<string>; (options?: Readonly<ScreenshotOptions>): Promise<Uint8Array>;};
Captures a screenshot of this page.
Parameter options
Configures screenshot behavior.
Remarks
While a screenshot is being taken in a BrowserContext, the following methods will automatically wait for the screenshot to finish to prevent interference with the screenshot process: BrowserContext.newPage, Browser.newPage, Page.close.
Calling Page.bringToFront will not wait for existing screenshot operations.
method select
select: (selector: string, ...values: string[]) => Promise<string[]>;
Triggers a
change
andinput
event once all the provided options have been selected. If there's no<select>
element matchingselector
, the method throws an error.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Parameter values
Values of options to select. If the
<select>
has themultiple
attribute, all values are considered, otherwise only the first one is taken into account.Returns
Remarks
Shortcut for page.mainFrame().select()
Example 1
page.select('select#colors', 'blue'); // single selectionpage.select('select#colors', 'red', 'green', 'blue'); // multiple selections
method setBypassCSP
abstract setBypassCSP: (enabled: boolean) => Promise<void>;
Toggles bypassing page's Content-Security-Policy.
Parameter enabled
sets bypassing of page's Content-Security-Policy.
Remarks
NOTE: CSP bypassing happens at the moment of CSP initialization rather than evaluation. Usually, this means that
page.setBypassCSP
should be called before navigating to the domain.
method setBypassServiceWorker
abstract setBypassServiceWorker: (bypass: boolean) => Promise<void>;
Toggles ignoring of service worker for each request.
Parameter bypass
Whether to bypass service worker and load from network.
method setCacheEnabled
abstract setCacheEnabled: (enabled?: boolean) => Promise<void>;
Toggles ignoring cache for each request based on the enabled state. By default, caching is enabled.
Parameter enabled
sets the
enabled
state of cache
method setContent
setContent: (html: string, options?: WaitForOptions) => Promise<void>;
Set the content of the page.
Parameter html
HTML markup to assign to the page.
Parameter options
Parameters that has some properties.
method setCookie
abstract setCookie: (...cookies: CookieParam[]) => Promise<void>;
Example 1
await page.setCookie(cookieObject1, cookieObject2);
method setDefaultNavigationTimeout
abstract setDefaultNavigationTimeout: (timeout: number) => void;
This setting will change the default maximum navigation time for the following methods and related shortcuts:
Parameter timeout
Maximum navigation time in milliseconds.
method setDefaultTimeout
abstract setDefaultTimeout: (timeout: number) => void;
Parameter timeout
Maximum time in milliseconds.
method setDragInterception
abstract setDragInterception: (enabled: boolean) => Promise<void>;
Parameter enabled
Whether to enable drag interception.
Deprecated
We no longer support intercepting drag payloads. Use the new drag APIs found on ElementHandle to drag (or just use the Page.mouse).
method setExtraHTTPHeaders
abstract setExtraHTTPHeaders: (headers: Record<string, string>) => Promise<void>;
The extra HTTP headers will be sent with every request the page initiates.
:::tip
All HTTP header names are lowercased. (HTTP headers are case-insensitive, so this shouldn’t impact your server code.)
:::
:::note
page.setExtraHTTPHeaders does not guarantee the order of headers in the outgoing requests.
:::
Parameter headers
An object containing additional HTTP headers to be sent with every request. All header values must be strings.
method setGeolocation
abstract setGeolocation: (options: GeolocationOptions) => Promise<void>;
Sets the page's geolocation.
Remarks
Consider using BrowserContext.overridePermissions to grant permissions for the page to read its geolocation.
Example 1
await page.setGeolocation({latitude: 59.95, longitude: 30.31667});
method setJavaScriptEnabled
abstract setJavaScriptEnabled: (enabled: boolean) => Promise<void>;
Parameter enabled
Whether or not to enable JavaScript on the page.
Remarks
NOTE: changing this value won't affect scripts that have already been run. It will take full effect on the next navigation.
method setOfflineMode
abstract setOfflineMode: (enabled: boolean) => Promise<void>;
Sets the network connection to offline.
It does not change the parameters used in Page.emulateNetworkConditions
Parameter enabled
When
true
, enables offline mode for the page.
method setRequestInterception
abstract setRequestInterception: (value: boolean) => Promise<void>;
Activating request interception enables HTTPRequest.abort, HTTPRequest.continue and HTTPRequest.respond methods. This provides the capability to modify network requests that are made by a page.
Once request interception is enabled, every request will stall unless it's continued, responded or aborted; or completed using the browser cache.
See the Request interception guide for more details.
Parameter value
Whether to enable request interception.
Example 1
An example of a naïve request interceptor that aborts all image requests:
import puppeteer from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();await page.setRequestInterception(true);page.on('request', interceptedRequest => {if (interceptedRequest.url().endsWith('.png') ||interceptedRequest.url().endsWith('.jpg'))interceptedRequest.abort();else interceptedRequest.continue();});await page.goto('https://example.com');await browser.close();})();
method setUserAgent
abstract setUserAgent: ( userAgent: string, userAgentMetadata?: Protocol.Emulation.UserAgentMetadata) => Promise<void>;
Parameter userAgent
Specific user agent to use in this page
Parameter userAgentData
Specific user agent client hint data to use in this page
Returns
Promise which resolves when the user agent is set.
method setViewport
abstract setViewport: (viewport: Viewport | null) => Promise<void>;
page.setViewport
will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport before navigating to the page.In the case of multiple pages in a single browser, each page can have its own viewport size. Setting the viewport to
null
resets the viewport to its default value.Parameter viewport
Remarks
NOTE: in certain cases, setting viewport will reload the page in order to set the isMobile or hasTouch properties.
Example 1
const page = await browser.newPage();await page.setViewport({width: 640,height: 480,deviceScaleFactor: 1,});await page.goto('https://example.com');
method tap
tap: (selector: string) => Promise<void>;
This method fetches an element with
selector
, scrolls it into view if needed, and then uses Page.touchscreen to tap in the center of the element. If there's no element matchingselector
, the method throws an error.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix. If there are multiple elements satisfying the selector, the first will be tapped.
Remarks
Shortcut for page.mainFrame().tap(selector).
method target
abstract target: () => Target;
A target this page was created from.
Deprecated
Use Page.createCDPSession directly.
method title
title: () => Promise<string>;
The page's title
Remarks
Shortcut for page.mainFrame().title().
method type
type: ( selector: string, text: string, options?: Readonly<KeyboardTypeOptions>) => Promise<void>;
Sends a
keydown
,keypress/input
, andkeyup
event for each character in the text.To press a special key, like
Control
orArrowDown
, use Keyboard.press.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Parameter text
A text to type into a focused element.
Parameter options
have property
delay
which is the Time to wait between key presses in milliseconds. Defaults to0
.Returns
Example 1
await page.type('#mytextarea', 'Hello');// Types instantlyawait page.type('#mytextarea', 'World', {delay: 100});// Types slower, like a user
method url
url: () => string;
The page's URL.
Remarks
Shortcut for page.mainFrame().url().
method viewport
abstract viewport: () => Viewport | null;
Returns the current page viewport settings without checking the actual page viewport.
This is either the viewport set with the previous Page.setViewport call or the default viewport set via BrowserConnectOptions.defaultViewport.
method waitForDevicePrompt
abstract waitForDevicePrompt: ( options?: WaitTimeoutOptions) => Promise<DeviceRequestPrompt>;
This method is typically coupled with an action that triggers a device request from an api such as WebBluetooth.
:::caution
This must be called before the device request is made. It will not return a currently active device prompt.
:::
Example 1
const [devicePrompt] = Promise.all([page.waitForDevicePrompt(),page.click('#connect-bluetooth'),]);await devicePrompt.select(await devicePrompt.waitForDevice(({name}) => name.includes('My Device')),);
method waitForFileChooser
abstract waitForFileChooser: ( options?: WaitTimeoutOptions) => Promise<FileChooser>;
This method is typically coupled with an action that triggers file choosing.
:::caution
This must be called before the file chooser is launched. It will not return a currently active file chooser.
:::
:::caution
Interception of file dialogs triggered via DOM APIs such as window.showOpenFilePicker is currently not supported.
:::
Remarks
In the "headful" browser, this method results in the native file picker dialog
not showing up
for the user.Example 1
The following example clicks a button that issues a file chooser and then responds with
/tmp/myfile.pdf
as if a user has selected this file.const [fileChooser] = await Promise.all([page.waitForFileChooser(),page.click('#upload-file-button'),// some button that triggers file selection]);await fileChooser.accept(['/tmp/myfile.pdf']);
method waitForFrame
waitForFrame: ( urlOrPredicate: string | ((frame: Frame) => Awaitable<boolean>), options?: WaitTimeoutOptions) => Promise<Frame>;
Waits for a frame matching the given conditions to appear.
Example 1
const frame = await page.waitForFrame(async frame => {return frame.name() === 'Test';});
method waitForFunction
waitForFunction: < Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>( pageFunction: Func | string, options?: FrameWaitForFunctionOptions, ...args: Params) => Promise<HandleFor<Awaited<ReturnType<Func>>>>;
Waits for the provided function,
pageFunction
, to return a truthy value when evaluated in the page's context.Parameter pageFunction
Function to be evaluated in browser context until it returns a truthy value.
Parameter options
Options for configuring waiting behavior.
Example 1
Page.waitForFunction can be used to observe a viewport size change:
import puppeteer from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();const watchDog = page.waitForFunction('window.innerWidth < 100');await page.setViewport({width: 50, height: 50});await watchDog;await browser.close();})();Example 2
Arguments can be passed from Node.js to
pageFunction
:const selector = '.foo';await page.waitForFunction(selector => !!document.querySelector(selector),{},selector,);Example 3
The provided
pageFunction
can be asynchronous:const username = 'github-username';await page.waitForFunction(async username => {const githubResponse = await fetch(`https://api.github.com/users/${username}`,);const githubUser = await githubResponse.json();// show the avatarconst img = document.createElement('img');img.src = githubUser.avatar_url;// wait 3 secondsawait new Promise((resolve, reject) => setTimeout(resolve, 3000));img.remove();},{},username,);
method waitForNavigation
waitForNavigation: (options?: WaitForOptions) => Promise<HTTPResponse | null>;
Waits for the page to navigate to a new URL or to reload. It is useful when you run code that will indirectly cause the page to navigate.
Parameter options
Navigation parameters which might have the following properties:
Returns
A
Promise
which resolves to the main resource response.- In case of multiple redirects, the navigation will resolve with the response of the last redirect. - In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with
null
.Remarks
Usage of the History API to change the URL is considered a navigation.
Example 1
const [response] = await Promise.all([page.waitForNavigation(), // The promise resolves after navigation has finishedpage.click('a.my-link'), // Clicking the link will indirectly cause a navigation]);
method waitForNetworkIdle
waitForNetworkIdle: (options?: WaitForNetworkIdleOptions) => Promise<void>;
Waits for the network to be idle.
Parameter options
Options to configure waiting behavior.
Returns
A promise which resolves once the network is idle.
method waitForRequest
waitForRequest: ( urlOrPredicate: string | AwaitablePredicate<HTTPRequest>, options?: WaitTimeoutOptions) => Promise<HTTPRequest>;
Parameter urlOrPredicate
A URL or predicate to wait for
Parameter options
Optional waiting parameters
Returns
Promise which resolves to the matched request
Remarks
Optional Waiting Parameters have:
-
timeout
: Maximum wait time in milliseconds, defaults to30
seconds, pass0
to disable the timeout. The default value can be changed by using the Page.setDefaultTimeout method.Example 1
const firstRequest = await page.waitForRequest('https://example.com/resource',);const finalRequest = await page.waitForRequest(request => request.url() === 'https://example.com',);return finalRequest.response()?.ok();
method waitForResponse
waitForResponse: ( urlOrPredicate: string | AwaitablePredicate<HTTPResponse>, options?: WaitTimeoutOptions) => Promise<HTTPResponse>;
Parameter urlOrPredicate
A URL or predicate to wait for.
Parameter options
Optional waiting parameters
Returns
Promise which resolves to the matched response.
Remarks
Optional Parameter have:
-
timeout
: Maximum wait time in milliseconds, defaults to30
seconds, pass0
to disable the timeout. The default value can be changed by using the Page.setDefaultTimeout method.Example 1
const firstResponse = await page.waitForResponse('https://example.com/resource',);const finalResponse = await page.waitForResponse(response =>response.url() === 'https://example.com' && response.status() === 200,);const finalResponse = await page.waitForResponse(async response => {return (await response.text()).includes('<html>');});return finalResponse.ok();
method waitForSelector
waitForSelector: <Selector extends string>( selector: Selector, options?: WaitForSelectorOptions) => Promise<ElementHandle<NodeFor<Selector>> | null>;
Wait for the
selector
to appear in page. If at the moment of calling the method theselector
already exists, the method will return immediately. If theselector
doesn't appear after thetimeout
milliseconds of waiting, the function will throw.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Parameter options
Optional waiting parameters
Returns
Promise which resolves when element specified by selector string is added to DOM. Resolves to
null
if waiting for hidden:true
and selector is not found in DOM.Remarks
The optional Parameter in Arguments
options
are:-
visible
: A boolean wait for element to be present in DOM and to be visible, i.e. to not havedisplay: none
orvisibility: hidden
CSS properties. Defaults tofalse
.-
hidden
: Wait for element to not be found in the DOM or to be hidden, i.e. havedisplay: none
orvisibility: hidden
CSS properties. Defaults tofalse
.-
timeout
: maximum time to wait for in milliseconds. Defaults to30000
(30 seconds). Pass0
to disable timeout. The default value can be changed by using the Page.setDefaultTimeout method.Example 1
This method works across navigations:
import puppeteer from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();let currentURL;page.waitForSelector('img').then(() => console.log('First URL with image: ' + currentURL));for (currentURL of ['https://example.com','https://google.com','https://bbc.com',]) {await page.goto(currentURL);}await browser.close();})();
method workers
abstract workers: () => WebWorker[];
All of the dedicated WebWorkers associated with the page.
Remarks
This does not contain ServiceWorkers
class ProtocolError
class ProtocolError extends PuppeteerError {}
ProtocolError is emitted whenever there is an error from the protocol.
Modifiers
@public
property code
code: number;
Modifiers
@readonly
@public
property originalMessage
originalMessage: string;
Modifiers
@readonly
@public
class Puppeteer
class 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 extendsPuppeteer
, so has all the methods documented below as well as all that are defined on PuppeteerNode.Modifiers
@public
method clearCustomQueryHandlers
static clearCustomQueryHandlers: () => void;
Unregisters all custom query handlers.
method connect
connect: (options: ConnectOptions) => Promise<Browser>;
This method attaches Puppeteer to an existing browser instance.
Parameter options
Set of configurable options to set on the browser.
Returns
Promise which resolves to browser instance.
Remarks
method customQueryHandlerNames
static customQueryHandlerNames: () => string[];
Gets the names of all custom query handlers.
method registerCustomQueryHandler
static registerCustomQueryHandler: ( name: string, queryHandler: CustomQueryHandler) => void;
Registers a custom query handler.
Parameter name
The name that the custom query handler will be registered under.
Parameter queryHandler
The custom query handler to register.
Remarks
After registration, the handler can be used everywhere where a selector is expected by prepending the selection string with
<name>/
. The name is only allowed to consist of lower- and upper case latin letters.Example 1
import {Puppeteer}, puppeteer from 'puppeteer';Puppeteer.registerCustomQueryHandler('text', { … });const aHandle = await page.$('text/…');Modifiers
@public
method unregisterCustomQueryHandler
static unregisterCustomQueryHandler: (name: string) => void;
Unregisters a custom query handler for a given name.
class PuppeteerError
class PuppeteerError extends Error {}
The base class for all Puppeteer-specific errors
Modifiers
@public
class PuppeteerNode
class PuppeteerNode extends Puppeteer {}
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 ESimport
).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.
Example 1
The following is a typical example of using Puppeteer to drive automation:
import puppeteer from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();await page.goto('https://www.google.com');// other actions...await browser.close();})();Once you have created a
page
you have access to a large API to interact with the page, navigate, or find certain elements in that page. The `page` documentation lists all the available methods.Modifiers
@public
property defaultBrowser
readonly defaultBrowser: SupportedBrowser;
The name of the browser that will be launched by default. For
puppeteer
, this is influenced by your configuration. Otherwise, it'schrome
.
property lastLaunchedBrowser
readonly lastLaunchedBrowser: SupportedBrowser;
The name of the browser that was last launched.
property product
readonly product: string;
Returns
The name of the browser that is under automation.
Deprecated
Do not use as this field as it does not take into account multiple browsers of different types. Use defaultBrowser or lastLaunchedBrowser.
method connect
connect: (options: ConnectOptions) => Promise<Browser>;
This method attaches Puppeteer to an existing browser instance.
Parameter options
Set of configurable options to set on the browser.
Returns
Promise which resolves to browser instance.
method defaultArgs
defaultArgs: (options?: BrowserLaunchArgumentOptions) => string[];
Parameter options
Set of configurable options to set on the browser.
Returns
The default flags that Chromium will be launched with.
method executablePath
executablePath: (channel?: ChromeReleaseChannel) => string;
The default executable path.
method launch
launch: (options?: PuppeteerLaunchOptions) => Promise<Browser>;
Launches a browser instance with given arguments and options when specified.
When using with
puppeteer-core
, options.executablePath or options.channel must be provided.Parameter options
Options to configure launching behavior.
Remarks
Puppeteer can also be used to control the Chrome browser, but it works best with the version of Chrome for Testing downloaded by default. There is no guarantee it will work with any other version. If Google Chrome (rather than Chrome for Testing) is preferred, a Chrome Canary or Dev Channel build is suggested. See this article for a description of the differences between Chromium and Chrome. This article describes some differences for Linux users. See this doc for the description of Chrome for Testing.
Example 1
You can use options.ignoreDefaultArgs to filter out
--mute-audio
from default arguments:const browser = await puppeteer.launch({ignoreDefaultArgs: ['--mute-audio'],});
method trimCache
trimCache: () => Promise<void>;
Removes all non-current Firefox and Chrome binaries in the cache directory identified by the provided Puppeteer configuration. The current browser version is determined by resolving PUPPETEER_REVISIONS from Puppeteer unless
configuration.browserRevision
is provided.Remarks
Note that the method does not check if any other Puppeteer versions installed on the host that use the same cache directory require the non-current binaries.
Modifiers
@public
class ScreenRecorder
class ScreenRecorder extends PassThrough {}
Modifiers
@public
method stop
stop: () => Promise<void>;
Stops the recorder.
Modifiers
@public
class SecurityDetails
class SecurityDetails {}
The SecurityDetails class represents the security details of a response that was received over a secure connection.
Modifiers
@public
method issuer
issuer: () => string;
The name of the issuer of the certificate.
method protocol
protocol: () => string;
The security protocol being used, e.g. "TLS 1.2".
method subjectAlternativeNames
subjectAlternativeNames: () => string[];
The list of subject alternative names (SANs) of the certificate.
method subjectName
subjectName: () => string;
The name of the subject to which the certificate was issued.
method validFrom
validFrom: () => number;
Unix timestamp marking the start of the certificate's validity.
method validTo
validTo: () => number;
Unix timestamp marking the end of the certificate's validity.
class Target
abstract 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.
Modifiers
@public
method asPage
abstract asPage: () => Promise<Page>;
Forcefully creates a page for a target of any type. It is useful if you want to handle a CDP target of type
other
as a page. If you deal with a regular page target, use Target.page.
method browser
abstract browser: () => Browser;
Get the browser the target belongs to.
method browserContext
abstract browserContext: () => BrowserContext;
Get the browser context the target belongs to.
method createCDPSession
abstract createCDPSession: () => Promise<CDPSession>;
Creates a Chrome Devtools Protocol session attached to the target.
method opener
abstract opener: () => Target | undefined;
Get the target that opened this target. Top-level targets return
null
.
method page
page: () => Promise<Page | null>;
If the target is not of type
"page"
,"webview"
or"background_page"
, returnsnull
.
method type
abstract type: () => TargetType;
Identifies what kind of target this is.
Remarks
See docs for more info about background pages.
method url
abstract url: () => string;
method worker
worker: () => Promise<WebWorker | null>;
If the target is not of type
"service_worker"
or"shared_worker"
, returnsnull
.
class TimeoutError
class TimeoutError extends PuppeteerError {}
TimeoutError is emitted whenever certain operations are terminated due to timeout.
Remarks
Example operations are page.waitForSelector or puppeteer.launch.
Modifiers
@public
class TouchError
class TouchError extends PuppeteerError {}
TouchError is thrown when an attempt is made to move or end a touch that does not exist.
Modifiers
@public
class Touchscreen
abstract class Touchscreen {}
The Touchscreen class exposes touchscreen events.
Modifiers
@public
method tap
tap: (x: number, y: number) => Promise<void>;
Dispatches a
touchstart
andtouchend
event.Parameter x
Horizontal position of the tap.
Parameter y
Vertical position of the tap.
method touchEnd
touchEnd: () => Promise<void>;
Dispatches a
touchend
event on the first touch that is active.
method touchMove
touchMove: (x: number, y: number) => Promise<void>;
Dispatches a
touchMove
event on the first touch that is active.Parameter x
Horizontal position of the move.
Parameter y
Vertical position of the move.
Remarks
Not every
touchMove
call results in atouchmove
event being emitted, depending on the browser's optimizations. For example, Chrome throttles touch move events.
method touchStart
abstract touchStart: (x: number, y: number) => Promise<TouchHandle>;
Dispatches a
touchstart
event.Parameter x
Horizontal position of the tap.
Parameter y
Vertical position of the tap.
Returns
A handle for the touch that was started.
class Tracing
class Tracing {}
The Tracing class exposes the tracing audit interface.
Remarks
You can use
tracing.start
andtracing.stop
to create a trace file which can be opened in Chrome DevTools or timeline viewer.Example 1
await page.tracing.start({path: 'trace.json'});await page.goto('https://www.google.com');await page.tracing.stop();Modifiers
@public
method start
start: (options?: TracingOptions) => Promise<void>;
Starts a trace for the current page.
Parameter options
Optional
TracingOptions
.Remarks
Only one trace can be active at a time per browser.
method stop
stop: () => Promise<Uint8Array | undefined>;
Stops a trace started with the
start
method.Returns
Promise which resolves to buffer with trace data.
class UnsupportedOperation
class UnsupportedOperation extends PuppeteerError {}
Puppeteer will throw this error if a method is not supported by the currently used protocol
Modifiers
@public
class WebWorker
abstract class WebWorker extends EventEmitter<Record<EventType, unknown>> {}
This class represents a WebWorker.
Remarks
The events
workercreated
andworkerdestroyed
are emitted on the page object to signal the worker lifecycle.Example 1
page.on('workercreated', worker =>console.log('Worker created: ' + worker.url()),);page.on('workerdestroyed', worker =>console.log('Worker destroyed: ' + worker.url()),);console.log('Current workers:');for (const worker of page.workers()) {console.log(' ' + worker.url());}Modifiers
@public
property client
readonly client: CDPSession;
The CDP session client the WebWorker belongs to.
method close
close: () => Promise<void>;
method evaluate
evaluate: < Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>( func: Func | string, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
Evaluates a given function in the worker.
Parameter func
Function to be evaluated.
Parameter args
Arguments to pass into
func
.Returns
The result of
func
.Remarks
If the given function returns a promise, evaluate will wait for the promise to resolve.
As a rule of thumb, if the return value of the given function is more complicated than a JSON object (e.g. most classes), then evaluate will _likely_ return some truncated value (or
{}
). This is because we are not returning the actual return value, but a deserialized version as a result of transferring the return value through a protocol to Puppeteer.In general, you should use evaluateHandle if evaluate cannot serialize the return value properly or you need a mutable handle to the return object.
method evaluateHandle
evaluateHandle: < Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>( func: Func | string, ...args: Params) => Promise<HandleFor<Awaited<ReturnType<Func>>>>;
Evaluates a given function in the worker.
Parameter func
Function to be evaluated.
Parameter args
Arguments to pass into
func
.Returns
A handle to the return value of
func
.Remarks
If the given function returns a promise, evaluate will wait for the promise to resolve.
In general, you should use evaluateHandle if evaluate cannot serialize the return value properly or you need a mutable handle to the return object.
method url
url: () => string;
The URL of this web worker.
Interfaces
interface ActionOptions
interface ActionOptions {}
Modifiers
@public
property signal
signal?: AbortSignal;
A signal to abort the locator action.
interface AutofillData
interface AutofillData {}
Modifiers
@public
property creditCard
creditCard: { number: string; name: string; expiryMonth: string; expiryYear: string; cvc: string;};
interface BoundingBox
interface BoundingBox extends Point {}
Modifiers
@public
interface BoxModel
interface BoxModel {}
Modifiers
@public
interface BrowserConnectOptions
interface BrowserConnectOptions {}
Generic browser options that can be passed when launching any browser or when connecting to an existing browser instance.
Modifiers
@public
property acceptInsecureCerts
acceptInsecureCerts?: boolean;
Whether to ignore HTTPS errors during navigation.
property defaultViewport
defaultViewport?: Viewport | null;
Sets the viewport for each page.
property protocol
protocol?: ProtocolType;
Modifiers
@public
property protocolTimeout
protocolTimeout?: number;
Timeout setting for individual protocol (CDP) calls.
property slowMo
slowMo?: number;
Slows down Puppeteer operations by the specified amount of milliseconds to aid debugging.
property targetFilter
targetFilter?: TargetFilterCallback;
Callback to decide if Puppeteer should connect to a given target or not.
interface BrowserContextEvents
interface BrowserContextEvents extends Record<EventType, unknown> {}
Modifiers
@public
property [BrowserContextEvent.TargetChanged]
[BrowserContextEvent.TargetChanged]: Target;
property [BrowserContextEvent.TargetCreated]
[BrowserContextEvent.TargetCreated]: Target;
property [BrowserContextEvent.TargetDestroyed]
[BrowserContextEvent.TargetDestroyed]: Target;
interface BrowserContextOptions
interface BrowserContextOptions {}
Modifiers
@public
property proxyBypassList
proxyBypassList?: string[];
Bypass the proxy for the given list of hosts.
property proxyServer
proxyServer?: string;
Proxy server with optional port to use for all requests. Username and password can be set in
Page.authenticate
.
interface BrowserEvents
interface BrowserEvents extends Record<EventType, unknown> {}
Modifiers
@public
property [BrowserEvent.Disconnected]
[BrowserEvent.Disconnected]: undefined;
property [BrowserEvent.TargetChanged]
[BrowserEvent.TargetChanged]: Target;
property [BrowserEvent.TargetCreated]
[BrowserEvent.TargetCreated]: Target;
property [BrowserEvent.TargetDestroyed]
[BrowserEvent.TargetDestroyed]: Target;
interface BrowserLaunchArgumentOptions
interface BrowserLaunchArgumentOptions {}
Launcher options that only apply to Chrome.
Modifiers
@public
property args
args?: string[];
Additional command line arguments to pass to the browser instance.
property debuggingPort
debuggingPort?: number;
Specify the debugging port number to use
property devtools
devtools?: boolean;
Whether to auto-open a DevTools panel for each tab. If this is set to
true
, thenheadless
will be forced tofalse
.
property headless
headless?: boolean | 'shell';
Whether to run the browser in headless mode.
Remarks
-
true
launches the browser in the new headless mode.-
'shell'
launches shell known as the old headless mode.
property userDataDir
userDataDir?: string;
Path to a user data directory. see the Chromium docs for more info.
interface CDPSessionEvents
interface CDPSessionEvents extends CDPEvents, Record<EventType, unknown> {}
Modifiers
@public
property [CDPSessionEvent.SessionAttached]
[CDPSessionEvent.SessionAttached]: CDPSession;
property [CDPSessionEvent.SessionDetached]
[CDPSessionEvent.SessionDetached]: CDPSession;
interface ChromeHeadlessShellSettings
interface ChromeHeadlessShellSettings {}
Modifiers
@public
property downloadBaseUrl
downloadBaseUrl?: string;
Specifies the URL prefix that is used to download the browser.
Can be overridden by
PUPPETEER_CHROME_HEADLESS_SHELL_DOWNLOAD_BASE_URL
.Remarks
This must include the protocol and may even need a path prefix. This must **not** include a trailing slash similar to the default.
property skipDownload
skipDownload?: boolean;
Tells Puppeteer to not download the browser during installation.
Can be overridden by
PUPPETEER_CHROME_HEADLESS_SHELL_SKIP_DOWNLOAD
orPUPPETEER_SKIP_CHROME_HEADLESS_SHELL_DOWNLOAD
.
property version
version?: string;
Specifies a certain version of the browser you'd like Puppeteer to use.
Can be overridden by
PUPPETEER_CHROME_HEADLESS_SHELL_VERSION
.See puppeteer.launch on how executable path is inferred.
Example 1
119.0.6045.105
interface ChromeSettings
interface ChromeSettings {}
Modifiers
@public
property downloadBaseUrl
downloadBaseUrl?: string;
Specifies the URL prefix that is used to download the browser.
Can be overridden by
PUPPETEER_CHROME_DOWNLOAD_BASE_URL
.Remarks
This must include the protocol and may even need a path prefix. This must **not** include a trailing slash similar to the default.
property skipDownload
skipDownload?: boolean;
Tells Puppeteer to not download the browser during installation.
Can be overridden by
PUPPETEER_CHROME_SKIP_DOWNLOAD
.
property version
version?: string;
Specifies a certain version of the browser you'd like Puppeteer to use.
Can be overridden by
PUPPETEER_CHROME_VERSION
orPUPPETEER_SKIP_CHROME_DOWNLOAD
.See puppeteer.launch on how executable path is inferred.
Example 1
119.0.6045.105
interface ClickOptions
interface ClickOptions extends MouseClickOptions {}
Modifiers
@public
property offset
offset?: Offset;
Offset for the clickable point relative to the top-left corner of the border box.
interface CommandOptions
interface CommandOptions {}
Modifiers
@public
property timeout
timeout: number;
interface CommonEventEmitter
interface CommonEventEmitter<Events extends Record<EventType, unknown>> {}
Modifiers
@public
method emit
emit: <Key extends keyof Events>(type: Key, event: Events[Key]) => boolean;
method listenerCount
listenerCount: (event: keyof Events) => number;
method off
off: <Key extends keyof Events>( type: Key, handler?: Handler<Events[Key]>) => this;
method on
on: <Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>) => this;
method once
once: <Key extends keyof Events>( type: Key, handler: Handler<Events[Key]>) => this;
method removeAllListeners
removeAllListeners: (event?: keyof Events) => this;
interface Configuration
interface Configuration {}
Defines options to configure Puppeteer's behavior during installation and runtime.
See individual properties for more information.
Modifiers
@public
property ['chrome-headless-shell']
['chrome-headless-shell']?: ChromeHeadlessShellSettings;
property cacheDirectory
cacheDirectory?: string;
Defines the directory to be used by Puppeteer for caching.
Can be overridden by
PUPPETEER_CACHE_DIR
.
property chrome
chrome?: ChromeSettings;
property defaultBrowser
defaultBrowser?: SupportedBrowser;
Specifies which browser you'd like Puppeteer to use.
Can be overridden by
PUPPETEER_BROWSER
.
property executablePath
executablePath?: string;
Specifies an executable path to be used in puppeteer.launch.
Can be overridden by
PUPPETEER_EXECUTABLE_PATH
.
property experiments
experiments?: ExperimentsConfiguration;
Defines experimental options for Puppeteer.
property firefox
firefox?: FirefoxSettings;
property logLevel
logLevel?: 'silent' | 'error' | 'warn';
Tells Puppeteer to log at the given level.
property skipDownload
skipDownload?: boolean;
Tells Puppeteer to not download during installation.
Can be overridden by
PUPPETEER_SKIP_DOWNLOAD
.
property temporaryDirectory
temporaryDirectory?: string;
Defines the directory to be used by Puppeteer for creating temporary files.
Can be overridden by
PUPPETEER_TMP_DIR
.
interface ConnectionTransport
interface ConnectionTransport {}
Modifiers
@public
interface ConnectOptions
interface ConnectOptions extends BrowserConnectOptions {}
Modifiers
@public
property browserURL
browserURL?: string;
property browserWSEndpoint
browserWSEndpoint?: string;
property capabilities
capabilities?: SupportedWebDriverCapabilities;
WebDriver BiDi capabilities passed to BiDi
session.new
.Remarks
Only works for
protocol="webDriverBiDi"
and Puppeteer.connect.
property headers
headers?: Record<string, string>;
Headers to use for the web socket connection.
Remarks
Only works in the Node.js environment.
property transport
transport?: ConnectionTransport;
interface ConsoleMessageLocation
interface ConsoleMessageLocation {}
Modifiers
@public
property columnNumber
columnNumber?: number;
0-based column number in the resource if known or
undefined
otherwise.
property lineNumber
lineNumber?: number;
0-based line number in the resource if known or
undefined
otherwise.
property url
url?: string;
URL of the resource if known or
undefined
otherwise.
interface ContinueRequestOverrides
interface ContinueRequestOverrides {}
Modifiers
@public
interface Cookie
interface Cookie {}
Represents a cookie object.
Modifiers
@public
property domain
domain: string;
Cookie domain.
property expires
expires: number;
Cookie expiration date as the number of seconds since the UNIX epoch. Set to
-1
for session cookies
property httpOnly
httpOnly: boolean;
True if cookie is http-only.
property name
name: string;
Cookie name.
property partitionKey
partitionKey?: string;
Cookie partition key. In Chrome, it is the top-level site the partitioned cookie is available in. In Firefox, it matches the source origin (https://w3c.github.io/webdriver-bidi/#type-storage-PartitionKey).
property partitionKeyOpaque
partitionKeyOpaque?: boolean;
True if cookie partition key is opaque. Supported only in Chrome.
property path
path: string;
Cookie path.
property priority
priority?: CookiePriority;
Cookie Priority. Supported only in Chrome.
property sameParty
sameParty?: boolean;
True if cookie is SameParty. Supported only in Chrome.
property sameSite
sameSite?: CookieSameSite;
Cookie SameSite type.
property secure
secure: boolean;
True if cookie is secure.
property session
session: boolean;
True in case of session cookie.
property size
size: number;
Cookie size.
property sourceScheme
sourceScheme?: CookieSourceScheme;
Cookie source scheme type. Supported only in Chrome.
property value
value: string;
Cookie value.
interface CookieParam
interface CookieParam {}
Cookie parameter object
Modifiers
@public
property domain
domain?: string;
Cookie domain.
property expires
expires?: number;
Cookie expiration date, session cookie if not set
property httpOnly
httpOnly?: boolean;
True if cookie is http-only.
property name
name: string;
Cookie name.
property partitionKey
partitionKey?: string;
Cookie partition key. In Chrome, it matches the top-level site the partitioned cookie is available in. In Firefox, it matches the source origin (https://w3c.github.io/webdriver-bidi/#type-storage-PartitionKey).
property path
path?: string;
Cookie path.
property priority
priority?: CookiePriority;
Cookie Priority. Supported only in Chrome.
property sameParty
sameParty?: boolean;
True if cookie is SameParty. Supported only in Chrome.
property sameSite
sameSite?: CookieSameSite;
Cookie SameSite type.
property secure
secure?: boolean;
True if cookie is secure.
property sourceScheme
sourceScheme?: CookieSourceScheme;
Cookie source scheme type. Supported only in Chrome.
property url
url?: string;
The request-URI to associate with the setting of the cookie. This value can affect the default domain, path, and source scheme values of the created cookie.
property value
value: string;
Cookie value.
interface CoverageEntry
interface CoverageEntry {}
The CoverageEntry class represents one entry of the coverage report.
Modifiers
@public
interface Credentials
interface Credentials {}
Modifiers
@public
interface CSSCoverageOptions
interface CSSCoverageOptions {}
Set of configurable options for CSS coverage.
Modifiers
@public
property resetOnNavigation
resetOnNavigation?: boolean;
Whether to reset coverage on every navigation.
interface CustomQueryHandler
interface CustomQueryHandler {}
Modifiers
@public
interface DebugInfo
interface DebugInfo {}
Modifiers
@public
@experimental
property pendingProtocolErrors
pendingProtocolErrors: Error[];
interface DeleteCookiesRequest
interface DeleteCookiesRequest {}
Modifiers
@public
property domain
domain?: string;
If specified, deletes only cookies with the exact domain.
property name
name: string;
Name of the cookies to remove.
property partitionKey
partitionKey?: string;
If specified, deletes cookies in the given partition key. In Chrome, partitionKey matches the top-level site the partitioned cookie is available in. In Firefox, it matches the source origin (https://w3c.github.io/webdriver-bidi/#type-storage-PartitionKey).
property path
path?: string;
If specified, deletes only cookies with the exact path.
property url
url?: string;
If specified, deletes all the cookies with the given name where domain and path match provided URL. Otherwise, deletes only cookies related to the current page's domain.
interface Device
interface Device {}
Modifiers
@public
interface ElementScreenshotOptions
interface ElementScreenshotOptions extends ScreenshotOptions {}
Modifiers
@public
property scrollIntoView
scrollIntoView?: boolean;
interface FirefoxSettings
interface FirefoxSettings {}
Modifiers
@public
property downloadBaseUrl
downloadBaseUrl?: string;
Specifies the URL prefix that is used to download the browser.
Can be overridden by
PUPPETEER_FIREFOX_DOWNLOAD_BASE_URL
.Remarks
This must include the protocol and may even need a path prefix. This must **not** include a trailing slash similar to the default.
property skipDownload
skipDownload?: boolean;
Tells Puppeteer to not download the browser during installation.
Can be overridden by
PUPPETEER_FIREFOX_SKIP_DOWNLOAD
.
property version
version?: string;
Specifies a certain version of the browser you'd like Puppeteer to use.
Can be overridden by
PUPPETEER_FIREFOX_VERSION
.See puppeteer.launch on how executable path is inferred.
Example 1
stable_129.0
interface FrameAddScriptTagOptions
interface FrameAddScriptTagOptions {}
Modifiers
@public
property content
content?: string;
JavaScript to be injected into the frame.
property id
id?: string;
Sets the
id
of the script.
property path
path?: string;
Path to a JavaScript file to be injected into the frame.
Remarks
If
path
is a relative path, it is resolved relative to the current working directory (process.cwd()
in Node.js).
property type
type?: string;
Sets the
type
of the script. Usemodule
in order to load an ES2015 module.
property url
url?: string;
URL of the script to be added.
interface FrameAddStyleTagOptions
interface FrameAddStyleTagOptions {}
Modifiers
@public
property content
content?: string;
Raw CSS content to be injected into the frame.
property path
path?: string;
The path to a CSS file to be injected into the frame.
Remarks
If
path
is a relative path, it is resolved relative to the current working directory (process.cwd()
in Node.js).
property url
url?: string;
the URL of the CSS file to be added.
interface FrameEvents
interface FrameEvents extends Record<EventType, unknown> {}
Modifiers
@public
interface FrameWaitForFunctionOptions
interface FrameWaitForFunctionOptions {}
Modifiers
@public
property polling
polling?: 'raf' | 'mutation' | number;
An interval at which the
pageFunction
is executed, defaults toraf
. Ifpolling
is a number, then it is treated as an interval in milliseconds at which the function would be executed. Ifpolling
is a string, then it can be one of the following values:-
raf
- to constantly executepageFunction
inrequestAnimationFrame
callback. This is the tightest polling mode which is suitable to observe styling changes.-
mutation
- to executepageFunction
on every DOM mutation.
property signal
signal?: AbortSignal;
A signal object that allows you to cancel a waitForFunction call.
property timeout
timeout?: number;
Maximum time to wait in milliseconds. Defaults to
30000
(30 seconds). Pass0
to disable the timeout. Puppeteer's default timeout can be changed using Page.setDefaultTimeout.
interface GeolocationOptions
interface GeolocationOptions {}
Modifiers
@public
interface GoToOptions
interface GoToOptions extends WaitForOptions {}
Modifiers
@public
property referer
referer?: string;
If provided, it will take preference over the referer header value set by page.setExtraHTTPHeaders().
property referrerPolicy
referrerPolicy?: string;
If provided, it will take preference over the referer-policy header value set by page.setExtraHTTPHeaders().
interface InterceptResolutionState
interface InterceptResolutionState {}
Modifiers
@public
interface InternalNetworkConditions
interface InternalNetworkConditions extends NetworkConditions {}
Modifiers
@public
property offline
offline: boolean;
interface JSCoverageEntry
interface JSCoverageEntry extends CoverageEntry {}
The CoverageEntry class for JavaScript
Modifiers
@public
property rawScriptCoverage
rawScriptCoverage?: Protocol.Profiler.ScriptCoverage;
Raw V8 script coverage entry.
interface JSCoverageOptions
interface JSCoverageOptions {}
Set of configurable options for JS coverage.
Modifiers
@public
property includeRawScriptCoverage
includeRawScriptCoverage?: boolean;
Whether the result includes raw V8 script coverage entries.
property reportAnonymousScripts
reportAnonymousScripts?: boolean;
Whether anonymous scripts generated by the page should be reported.
property resetOnNavigation
resetOnNavigation?: boolean;
Whether to reset coverage on every navigation.
property useBlockCoverage
useBlockCoverage?: boolean;
Whether to collect coverage information at the block level. If true, coverage will be collected at the block level (this is the default). If false, coverage will be collected at the function level.
interface KeyboardTypeOptions
interface KeyboardTypeOptions {}
Modifiers
@public
property delay
delay?: number;
interface KeyDownOptions
interface KeyDownOptions {}
Modifiers
@public
interface LaunchOptions
interface LaunchOptions {}
Generic launch options that can be passed when launching any browser.
Modifiers
@public
property browser
browser?: SupportedBrowser;
Which browser to launch.
property channel
channel?: ChromeReleaseChannel;
Chrome Release Channel
property dumpio
dumpio?: boolean;
If true, pipes the browser process stdout and stderr to
process.stdout
andprocess.stderr
.
property env
env?: Record<string, string | undefined>;
Specify environment variables that will be visible to the browser.
property executablePath
executablePath?: string;
Path to a browser executable to use instead of the bundled browser. Note that Puppeteer is only guaranteed to work with the bundled browser, so use this setting at your own risk.
Remarks
When using this is recommended to set the
browser
property as well as Puppeteer will default tochrome
by default.
property extraPrefsFirefox
extraPrefsFirefox?: Record<string, unknown>;
Additional preferences that can be passed when launching with Firefox.
property handleSIGHUP
handleSIGHUP?: boolean;
Close the browser process on
SIGHUP
.
property handleSIGINT
handleSIGINT?: boolean;
Close the browser process on
Ctrl+C
.
property handleSIGTERM
handleSIGTERM?: boolean;
Close the browser process on
SIGTERM
.
property ignoreDefaultArgs
ignoreDefaultArgs?: boolean | string[];
If
true
, do not usepuppeteer.defaultArgs()
when creating a browser. If an array is provided, these args will be filtered out. Use this with care - you probably want the default arguments Puppeteer uses.
property pipe
pipe?: boolean;
Connect to a browser over a pipe instead of a WebSocket. Only supported with Chrome.
property timeout
timeout?: number;
Maximum time in milliseconds to wait for the browser to start. Pass
0
to disable the timeout.
property waitForInitialPage
waitForInitialPage?: boolean;
Whether to wait for the initial page to be ready. Useful when a user explicitly disables that (e.g.
--no-startup-window
for Chrome).
interface LocatorEvents
interface LocatorEvents extends Record<EventType, unknown> {}
Modifiers
@public
property [LocatorEvent.Action]
[LocatorEvent.Action]: undefined;
interface LocatorScrollOptions
interface LocatorScrollOptions extends ActionOptions {}
Modifiers
@public
property scrollLeft
scrollLeft?: number;
property scrollTop
scrollTop?: number;
interface MediaFeature
interface MediaFeature {}
A media feature to emulate.
Modifiers
@public
interface Metrics
interface Metrics {}
Modifiers
@public
property Documents
Documents?: number;
property Frames
Frames?: number;
property JSEventListeners
JSEventListeners?: number;
property JSHeapTotalSize
JSHeapTotalSize?: number;
property JSHeapUsedSize
JSHeapUsedSize?: number;
property LayoutCount
LayoutCount?: number;
property LayoutDuration
LayoutDuration?: number;
property Nodes
Nodes?: number;
property RecalcStyleCount
RecalcStyleCount?: number;
property RecalcStyleDuration
RecalcStyleDuration?: number;
property ScriptDuration
ScriptDuration?: number;
property TaskDuration
TaskDuration?: number;
property Timestamp
Timestamp?: number;
interface MouseClickOptions
interface MouseClickOptions extends MouseOptions {}
Modifiers
@public
interface MouseMoveOptions
interface MouseMoveOptions {}
Modifiers
@public
property steps
steps?: number;
Determines the number of movements to make from the current mouse position to the new one.
interface MouseOptions
interface MouseOptions {}
Modifiers
@public
property button
button?: MouseButton;
Determines which button will be pressed.
property clickCount
clickCount?: number;
Determines the click count for the mouse event. This does not perform multiple clicks.
Deprecated
interface MouseWheelOptions
interface MouseWheelOptions {}
Modifiers
@public
interface Moveable
interface Moveable {}
Modifiers
@public
method move
move: () => this;
Moves the resource when 'using'.
interface NetworkConditions
interface NetworkConditions {}
Modifiers
@public
interface NewDocumentScriptEvaluation
interface NewDocumentScriptEvaluation {}
Modifiers
@public
property identifier
identifier: string;
interface Offset
interface Offset {}
Modifiers
@public
interface PageEvents
interface PageEvents extends Record<EventType, unknown> {}
Denotes the objects received by callback functions for page events.
See PageEvent for more detail on the events and when they are emitted.
Modifiers
@public
property [PageEvent.Close]
[PageEvent.Close]: undefined;
property [PageEvent.Console]
[PageEvent.Console]: ConsoleMessage;
property [PageEvent.Dialog]
[PageEvent.Dialog]: Dialog;
property [PageEvent.DOMContentLoaded]
[PageEvent.DOMContentLoaded]: undefined;
property [PageEvent.Error]
[PageEvent.Error]: Error;
property [PageEvent.FrameAttached]
[PageEvent.FrameAttached]: Frame;
property [PageEvent.FrameDetached]
[PageEvent.FrameDetached]: Frame;
property [PageEvent.FrameNavigated]
[PageEvent.FrameNavigated]: Frame;
property [PageEvent.Load]
[PageEvent.Load]: undefined;
property [PageEvent.Metrics]
[PageEvent.Metrics]: { title: string; metrics: Metrics;};
property [PageEvent.PageError]
[PageEvent.PageError]: Error;
property [PageEvent.Popup]
[PageEvent.Popup]: Page | null;
property [PageEvent.Request]
[PageEvent.Request]: HTTPRequest;
property [PageEvent.RequestFailed]
[PageEvent.RequestFailed]: HTTPRequest;
property [PageEvent.RequestFinished]
[PageEvent.RequestFinished]: HTTPRequest;
property [PageEvent.RequestServedFromCache]
[PageEvent.RequestServedFromCache]: HTTPRequest;
property [PageEvent.Response]
[PageEvent.Response]: HTTPResponse;
property [PageEvent.WorkerCreated]
[PageEvent.WorkerCreated]: WebWorker;
property [PageEvent.WorkerDestroyed]
[PageEvent.WorkerDestroyed]: WebWorker;
interface PDFMargin
interface PDFMargin {}
Modifiers
@public
interface PDFOptions
interface PDFOptions {}
Valid options to configure PDF generation via Page.pdf.
Modifiers
@public
property displayHeaderFooter
displayHeaderFooter?: boolean;
Whether to show the header and footer.
property footerTemplate
footerTemplate?: string;
HTML template for the print footer. Has the same constraints and support for special classes as PDFOptions.headerTemplate.
property format
format?: PaperFormat;
Remarks
If set, this takes priority over the
width
andheight
options.
property headerTemplate
headerTemplate?: string;
HTML template for the print header. Should be valid HTML with the following classes used to inject values into them:
-
date
formatted print date-
title
document title-
url
document location-
pageNumber
current page number-
totalPages
total pages in the document
property height
height?: string | number;
Sets the height of paper. You can pass in a number or a string with a unit.
property landscape
landscape?: boolean;
Whether to print in landscape orientation.
property margin
margin?: PDFMargin;
Set the PDF margins.
property omitBackground
omitBackground?: boolean;
Hides default white background and allows generating pdfs with transparency.
property outline
outline?: boolean;
Generate document outline.
Modifiers
@experimental
property pageRanges
pageRanges?: string;
Paper ranges to print, e.g.
1-5, 8, 11-13
.
property path
path?: string;
The path to save the file to.
Remarks
If the path is relative, it's resolved relative to the current working directory.
property preferCSSPageSize
preferCSSPageSize?: boolean;
Give any CSS
@page
size declared in the page priority over what is declared in thewidth
orheight
orformat
option.
property printBackground
printBackground?: boolean;
Set to
true
to print background graphics.
property scale
scale?: number;
Scales the rendering of the web page. Amount must be between
0.1
and2
.
property tagged
tagged?: boolean;
Generate tagged (accessible) PDF.
Modifiers
@experimental
property timeout
timeout?: number;
Timeout in milliseconds. Pass
0
to disable timeout.The default value can be changed by using Page.setDefaultTimeout
property waitForFonts
waitForFonts?: boolean;
If true, waits for
document.fonts.ready
to resolve. This might require activating the page using Page.bringToFront if the page is in the background.
property width
width?: string | number;
Sets the width of paper. You can pass in a number or a string with a unit.
interface PuppeteerLaunchOptions
interface PuppeteerLaunchOptions extends LaunchOptions, BrowserLaunchArgumentOptions, BrowserConnectOptions {}
Modifiers
@public
property browser
browser?: SupportedBrowser;
property extraPrefsFirefox
extraPrefsFirefox?: Record<string, unknown>;
interface QueryOptions
interface QueryOptions {}
Modifiers
@public
interface RemoteAddress
interface RemoteAddress {}
Modifiers
@public
interface ResponseForRequest
interface ResponseForRequest {}
Required response data to fulfill a request with.
Modifiers
@public
property body
body: string | Uint8Array;
property contentType
contentType: string;
property headers
headers: Record<string, string | string[] | unknown>;
Optional response headers.
The record values will be converted to string following: Arrays' values will be mapped to String (Used when you need multiple headers with the same name). Non-arrays will be converted to String.
property status
status: number;
interface ScreencastOptions
interface ScreencastOptions {}
Modifiers
@public
@experimental
property crop
crop?: BoundingBox;
Specifies the region of the viewport to crop.
property ffmpegPath
ffmpegPath?: string;
Path to the ffmpeg.
Required if
ffmpeg
is not in your PATH.
property path
path?: `${string}.webm`;
File path to save the screencast to.
property scale
scale?: number;
Scales the output video.
For example,
0.5
will shrink the width and height of the output video by half.2
will double the width and height of the output video.
property speed
speed?: number;
Specifies the speed to record at.
For example,
0.5
will slowdown the output video by 50%.2
will double the speed of the output video.
interface ScreenshotClip
interface ScreenshotClip extends BoundingBox {}
Modifiers
@public
property scale
scale?: number;
interface ScreenshotOptions
interface ScreenshotOptions {}
Modifiers
@public
property captureBeyondViewport
captureBeyondViewport?: boolean;
Capture the screenshot beyond the viewport.
property clip
clip?: ScreenshotClip;
Specifies the region of the page/element to clip.
property encoding
encoding?: 'base64' | 'binary';
Encoding of the image.
property fromSurface
fromSurface?: boolean;
Capture the screenshot from the surface, rather than the view.
property fullPage
fullPage?: boolean;
When
true
, takes a screenshot of the full page.
property omitBackground
omitBackground?: boolean;
Hides default white background and allows capturing screenshots with transparency.
property optimizeForSpeed
optimizeForSpeed?: boolean;
property path
path?: string;
The file path to save the image to. The screenshot type will be inferred from file extension. If path is a relative path, then it is resolved relative to current working directory. If no path is provided, the image won't be saved to the disk.
property quality
quality?: number;
Quality of the image, between 0-100. Not applicable to
png
images.
property type
type?: 'png' | 'jpeg' | 'webp';
interface SerializedAXNode
interface SerializedAXNode {}
Represents a Node and the properties of it that are relevant to Accessibility.
Modifiers
@public
property autocomplete
autocomplete?: string;
property checked
checked?: boolean | 'mixed';
Whether the checkbox is checked, or in a mixed state.
property children
children?: SerializedAXNode[];
Children of this node, if there are any.
property description
description?: string;
An additional human readable description of the node.
property disabled
disabled?: boolean;
property expanded
expanded?: boolean;
property focused
focused?: boolean;
property haspopup
haspopup?: string;
property invalid
invalid?: string;
Whether and in what way this node's value is invalid.
property keyshortcuts
keyshortcuts?: string;
Any keyboard shortcuts associated with this node.
property level
level?: number;
The level of a heading.
property modal
modal?: boolean;
property multiline
multiline?: boolean;
property multiselectable
multiselectable?: boolean;
Whether more than one child can be selected.
property name
name?: string;
A human readable name for the node.
property orientation
orientation?: string;
property pressed
pressed?: boolean | 'mixed';
Whether the node is checked or in a mixed state.
property readonly
readonly?: boolean;
property required
required?: boolean;
property role
role: string;
The role of the node.
property roledescription
roledescription?: string;
A human readable alternative to the role.
property selected
selected?: boolean;
property value
value?: string | number;
The current value of the node.
property valuemax
valuemax?: number;
property valuemin
valuemin?: number;
property valuetext
valuetext?: string;
A description of the current value.
method elementHandle
elementHandle: () => Promise<ElementHandle | null>;
Get an ElementHandle for this AXNode if available.
If the underlying DOM element has been disposed, the method might return an error.
interface SnapshotOptions
interface SnapshotOptions {}
Modifiers
@public
property interestingOnly
interestingOnly?: boolean;
Prune uninteresting nodes from the tree.
property root
root?: ElementHandle<Node>;
Root node to get the accessibility tree for
interface SupportedWebDriverCapabilities
interface SupportedWebDriverCapabilities {}
WebDriver BiDi capabilities that are not set by Puppeteer itself.
Modifiers
@public
property alwaysMatch
alwaysMatch?: SupportedWebDriverCapability;
property firstMatch
firstMatch?: SupportedWebDriverCapability[];
interface TouchHandle
interface TouchHandle {}
The TouchHandle interface exposes methods to manipulate touches that have been started
Modifiers
@public
interface TracingOptions
interface TracingOptions {}
Modifiers
@public
property categories
categories?: string[];
property path
path?: string;
property screenshots
screenshots?: boolean;
interface Viewport
interface Viewport {}
Modifiers
@public
property deviceScaleFactor
deviceScaleFactor?: number;
Specify device scale factor. See devicePixelRatio for more info.
Remarks
Setting this value to
0
will reset this value to the system default.
property hasTouch
hasTouch?: boolean;
Specify if the viewport supports touch events.
property height
height: number;
The page height in CSS pixels.
Remarks
Setting this value to
0
will reset this value to the system default.
property isLandscape
isLandscape?: boolean;
Specifies if the viewport is in landscape mode.
property isMobile
isMobile?: boolean;
Whether the
meta viewport
tag is taken into account.
property width
width: number;
The page width in CSS pixels.
Remarks
Setting this value to
0
will reset this value to the system default.
interface WaitForNetworkIdleOptions
interface WaitForNetworkIdleOptions extends WaitTimeoutOptions {}
Modifiers
@public
property concurrency
concurrency?: number;
Maximum number concurrent of network connections to be considered inactive.
property idleTime
idleTime?: number;
Time (in milliseconds) the network should be idle.
interface WaitForOptions
interface WaitForOptions {}
Modifiers
@public
property signal
signal?: AbortSignal;
A signal object that allows you to cancel the call.
property timeout
timeout?: number;
Maximum wait time in milliseconds. Pass 0 to disable the timeout.
The default value can be changed by using the Page.setDefaultTimeout or Page.setDefaultNavigationTimeout methods.
property waitUntil
waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[];
When to consider waiting succeeds. Given an array of event strings, waiting is considered to be successful after all events have been fired.
interface WaitForSelectorOptions
interface WaitForSelectorOptions {}
Modifiers
@public
property hidden
hidden?: boolean;
Wait for the selected element to not be found in the DOM or to be hidden. See ElementHandle.isHidden for the definition of element invisibility.
property signal
signal?: AbortSignal;
A signal object that allows you to cancel a waitForSelector call.
property timeout
timeout?: number;
Maximum time to wait in milliseconds. Pass
0
to disable timeout.The default value can be changed by using Page.setDefaultTimeout
property visible
visible?: boolean;
Wait for the selected element to be present in DOM and to be visible. See ElementHandle.isVisible for the definition of element visibility.
interface WaitForTargetOptions
interface WaitForTargetOptions {}
Modifiers
@public
interface WaitTimeoutOptions
interface WaitTimeoutOptions {}
Modifiers
@public
property signal
signal?: AbortSignal;
A signal object that allows you to cancel a waitFor call.
property timeout
timeout?: number;
Maximum wait time in milliseconds. Pass 0 to disable the timeout.
The default value can be changed by using the Page.setDefaultTimeout method.
Enums
enum BrowserContextEvent
const enum BrowserContextEvent { TargetChanged = 'targetchanged', TargetCreated = 'targetcreated', TargetDestroyed = 'targetdestroyed',}
Modifiers
@public
member TargetChanged
TargetChanged = 'targetchanged'
Emitted when the url of a target inside the browser context changes. Contains a Target instance.
member TargetCreated
TargetCreated = 'targetcreated'
Emitted when a target is created within the browser context, for example when a new page is opened by window.open or by browserContext.newPage
Contains a Target instance.
member TargetDestroyed
TargetDestroyed = 'targetdestroyed'
Emitted when a target is destroyed within the browser context, for example when a page is closed. Contains a Target instance.
enum BrowserEvent
const enum BrowserEvent { Disconnected = 'disconnected', TargetChanged = 'targetchanged', TargetCreated = 'targetcreated', TargetDestroyed = 'targetdestroyed',}
All the events a browser instance may emit.
Modifiers
@public
member Disconnected
Disconnected = 'disconnected'
Emitted when Puppeteer gets disconnected from the browser instance. This might happen because either:
- The browser closes/crashes or - Browser.disconnect was called.
member TargetChanged
TargetChanged = 'targetchanged'
Emitted when the URL of a target changes. Contains a Target instance.
Remarks
Note that this includes target changes in all browser contexts.
member TargetCreated
TargetCreated = 'targetcreated'
Emitted when a target is created, for example when a new page is opened by window.open or by browser.newPage
Contains a Target instance.
Remarks
Note that this includes target creations in all browser contexts.
member TargetDestroyed
TargetDestroyed = 'targetdestroyed'
Emitted when a target is destroyed, for example when a page is closed. Contains a Target instance.
Remarks
Note that this includes target destructions in all browser contexts.
enum InterceptResolutionAction
enum InterceptResolutionAction { Abort = 'abort', Respond = 'respond', Continue = 'continue', Disabled = 'disabled', None = 'none', AlreadyHandled = 'already-handled',}
Modifiers
@public
enum LocatorEvent
enum LocatorEvent { Action = 'action',}
All the events that a locator instance may emit.
Modifiers
@public
member Action
Action = 'action'
Emitted every time before the locator performs an action on the located element(s).
enum PageEvent
const enum PageEvent { Close = 'close', Console = 'console', Dialog = 'dialog', DOMContentLoaded = 'domcontentloaded', Error = 'error', FrameAttached = 'frameattached', FrameDetached = 'framedetached', FrameNavigated = 'framenavigated', Load = 'load', Metrics = 'metrics', PageError = 'pageerror', Popup = 'popup', Request = 'request', RequestServedFromCache = 'requestservedfromcache', RequestFailed = 'requestfailed', RequestFinished = 'requestfinished', Response = 'response', WorkerCreated = 'workercreated', WorkerDestroyed = 'workerdestroyed',}
All the events that a page instance may emit.
Modifiers
@public
member Close
Close = 'close'
Emitted when the page closes.
member Console
Console = 'console'
Emitted when JavaScript within the page calls one of console API methods, e.g.
console.log
orconsole.dir
. Also emitted if the page throws an error or a warning.Remarks
A
console
event provides a ConsoleMessage representing the console message that was logged.Example 1
An example of handling
console
event: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'}));
member Dialog
Dialog = 'dialog'
Emitted when a JavaScript dialog appears, such as
alert
,prompt
,confirm
orbeforeunload
. Puppeteer can respond to the dialog via Dialog.accept or Dialog.dismiss.
member DOMContentLoaded
DOMContentLoaded = 'domcontentloaded'
Emitted when the JavaScript DOMContentLoaded event is dispatched.
member Error
Error = 'error'
Emitted when the page crashes. Will contain an
Error
.
member FrameAttached
FrameAttached = 'frameattached'
Emitted when a frame is attached. Will contain a Frame.
member FrameDetached
FrameDetached = 'framedetached'
Emitted when a frame is detached. Will contain a Frame.
member FrameNavigated
FrameNavigated = 'framenavigated'
Emitted when a frame is navigated to a new URL. Will contain a Frame.
member Load
Load = 'load'
Emitted when the JavaScript load event is dispatched.
member Metrics
Metrics = 'metrics'
Emitted when the JavaScript code makes a call to
console.timeStamp
. For the list of metrics see page.metrics.Remarks
Contains an object with two properties:
-
title
: the title passed toconsole.timeStamp
-metrics
: object containing metrics as key/value pairs. The values will benumber
s.
member PageError
PageError = 'pageerror'
Emitted when an uncaught exception happens within the page. Contains an
Error
.
member Popup
Popup = 'popup'
Emitted when the page opens a new tab or window.
Contains a Page corresponding to the popup window.
Example 1
const [popup] = await Promise.all([new Promise(resolve => page.once('popup', resolve)),page.click('a[target=_blank]'),]);const [popup] = await Promise.all([new Promise(resolve => page.once('popup', resolve)),page.evaluate(() => window.open('https://example.com')),]);
member Request
Request = 'request'
Emitted when a page issues a request and contains a HTTPRequest.
Remarks
The object is readonly. See Page.setRequestInterception for intercepting and mutating requests.
member RequestFailed
RequestFailed = 'requestfailed'
Emitted when a request fails, for example by timing out.
Contains a HTTPRequest.
Remarks
HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with
requestfinished
event and not withrequestfailed
.
member RequestFinished
RequestFinished = 'requestfinished'
Emitted when a request finishes successfully. Contains a HTTPRequest.
member RequestServedFromCache
RequestServedFromCache = 'requestservedfromcache'
Emitted when a request ended up loading from cache. Contains a HTTPRequest.
Remarks
For certain requests, might contain undefined. https://crbug.com/750469
member Response
Response = 'response'
Emitted when a response is received. Contains a HTTPResponse.
member WorkerCreated
WorkerCreated = 'workercreated'
Emitted when a dedicated WebWorker is spawned by the page.
member WorkerDestroyed
WorkerDestroyed = 'workerdestroyed'
Emitted when a dedicated WebWorker is destroyed by the page.
enum TargetType
enum TargetType { PAGE = 'page', BACKGROUND_PAGE = 'background_page', SERVICE_WORKER = 'service_worker', SHARED_WORKER = 'shared_worker', BROWSER = 'browser', WEBVIEW = 'webview', OTHER = 'other',}
Modifiers
@public
member BACKGROUND_PAGE
BACKGROUND_PAGE = 'background_page'
member BROWSER
BROWSER = 'browser'
member OTHER
OTHER = 'other'
member PAGE
PAGE = 'page'
member SERVICE_WORKER
SERVICE_WORKER = 'service_worker'
member SHARED_WORKER
SHARED_WORKER = 'shared_worker'
member WEBVIEW
WEBVIEW = 'webview'
Type Aliases
type ActionResult
type ActionResult = 'continue' | 'abort' | 'respond';
Modifiers
@public
type Awaitable
type Awaitable<T> = T | PromiseLike<T>;
Modifiers
@public
type AwaitableIterable
type AwaitableIterable<T> = Iterable<T> | AsyncIterable<T>;
Modifiers
@public
type AwaitablePredicate
type AwaitablePredicate<T> = (value: T) => Awaitable<boolean>;
Modifiers
@public
type AwaitedLocator
type AwaitedLocator<T> = T extends Locator<infer S> ? S : never;
Modifiers
@public
type CDPEvents
type CDPEvents = { [Property in keyof ProtocolMapping.Events]: ProtocolMapping.Events[Property][0];};
Modifiers
@public
type ChromeReleaseChannel
type ChromeReleaseChannel = | 'chrome' | 'chrome-beta' | 'chrome-canary' | 'chrome-dev';
Modifiers
@public
type ConsoleMessageType
type ConsoleMessageType = | 'log' | 'debug' | 'info' | 'error' | 'warn' | 'dir' | 'dirxml' | 'table' | 'trace' | 'clear' | 'startGroup' | 'startGroupCollapsed' | 'endGroup' | 'assert' | 'profile' | 'profileEnd' | 'count' | 'timeEnd' | 'verbose';
The supported types for console messages.
Modifiers
@public
type CookiePriority
type CookiePriority = 'Low' | 'Medium' | 'High';
Represents the cookie's 'Priority' status: https://tools.ietf.org/html/draft-west-cookie-priority-00
Modifiers
@public
type CookieSameSite
type CookieSameSite = 'Strict' | 'Lax' | 'None';
Represents the cookie's 'SameSite' status: https://tools.ietf.org/html/draft-west-first-party-cookies
Modifiers
@public
type CookieSourceScheme
type CookieSourceScheme = 'Unset' | 'NonSecure' | 'Secure';
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.
Modifiers
@public
type ElementFor
type ElementFor< TagName extends keyof HTMLElementTagNameMap | keyof SVGElementTagNameMap> = TagName extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[TagName] : TagName extends keyof SVGElementTagNameMap ? SVGElementTagNameMap[TagName] : never;
Modifiers
@public
type ErrorCode
type ErrorCode = | 'aborted' | 'accessdenied' | 'addressunreachable' | 'blockedbyclient' | 'blockedbyresponse' | 'connectionaborted' | 'connectionclosed' | 'connectionfailed' | 'connectionrefused' | 'connectionreset' | 'internetdisconnected' | 'namenotresolved' | 'timedout' | 'failed';
Modifiers
@public
type EvaluateFunc
type EvaluateFunc<T extends unknown[]> = ( ...params: InnerParams<T>) => Awaitable<unknown>;
Modifiers
@public
type EvaluateFuncWith
type EvaluateFuncWith<V, T extends unknown[]> = ( ...params: [V, ...InnerParams<T>]) => Awaitable<unknown>;
Modifiers
@public
type EventsWithWildcard
type EventsWithWildcard<Events extends Record<EventType, unknown>> = Events & { '*': Events[keyof Events];};
Modifiers
@public
type EventType
type EventType = string | symbol;
Modifiers
@public
type ExperimentsConfiguration
type ExperimentsConfiguration = Record<string, never>;
Defines experiment options for Puppeteer.
See individual properties for more information.
Modifiers
@public
type FlattenHandle
type FlattenHandle<T> = T extends HandleOr<infer U> ? U : never;
Modifiers
@public
type HandleFor
type HandleFor<T> = T extends Node ? ElementHandle<T> : JSHandle<T>;
Modifiers
@public
type HandleOr
type HandleOr<T> = HandleFor<T> | JSHandle<T> | T;
Modifiers
@public
type Handler
type Handler<T = unknown> = (event: T) => void;
Modifiers
@public
type InnerParams
type InnerParams<T extends unknown[]> = { [K in keyof T]: FlattenHandle<T[K]>;};
Modifiers
@public
type KeyInput
type KeyInput = | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | 'Power' | 'Eject' | 'Abort' | 'Help' | 'Backspace' | 'Tab' | 'Numpad5' | 'NumpadEnter' | 'Enter' | '\r' | '\n' | 'ShiftLeft' | 'ShiftRight' | 'ControlLeft' | 'ControlRight' | 'AltLeft' | 'AltRight' | 'Pause' | 'CapsLock' | 'Escape' | 'Convert' | 'NonConvert' | 'Space' | 'Numpad9' | 'PageUp' | 'Numpad3' | 'PageDown' | 'End' | 'Numpad1' | 'Home' | 'Numpad7' | 'ArrowLeft' | 'Numpad4' | 'Numpad8' | 'ArrowUp' | 'ArrowRight' | 'Numpad6' | 'Numpad2' | 'ArrowDown' | 'Select' | 'Open' | 'PrintScreen' | 'Insert' | 'Numpad0' | 'Delete' | 'NumpadDecimal' | 'Digit0' | 'Digit1' | 'Digit2' | 'Digit3' | 'Digit4' | 'Digit5' | 'Digit6' | 'Digit7' | 'Digit8' | 'Digit9' | 'KeyA' | 'KeyB' | 'KeyC' | 'KeyD' | 'KeyE' | 'KeyF' | 'KeyG' | 'KeyH' | 'KeyI' | 'KeyJ' | 'KeyK' | 'KeyL' | 'KeyM' | 'KeyN' | 'KeyO' | 'KeyP' | 'KeyQ' | 'KeyR' | 'KeyS' | 'KeyT' | 'KeyU' | 'KeyV' | 'KeyW' | 'KeyX' | 'KeyY' | 'KeyZ' | 'MetaLeft' | 'MetaRight' | 'ContextMenu' | 'NumpadMultiply' | 'NumpadAdd' | 'NumpadSubtract' | 'NumpadDivide' | 'F1' | 'F2' | 'F3' | 'F4' | 'F5' | 'F6' | 'F7' | 'F8' | 'F9' | 'F10' | 'F11' | 'F12' | 'F13' | 'F14' | 'F15' | 'F16' | 'F17' | 'F18' | 'F19' | 'F20' | 'F21' | 'F22' | 'F23' | 'F24' | 'NumLock' | 'ScrollLock' | 'AudioVolumeMute' | 'AudioVolumeDown' | 'AudioVolumeUp' | 'MediaTrackNext' | 'MediaTrackPrevious' | 'MediaStop' | 'MediaPlayPause' | 'Semicolon' | 'Equal' | 'NumpadEqual' | 'Comma' | 'Minus' | 'Period' | 'Slash' | 'Backquote' | 'BracketLeft' | 'Backslash' | 'BracketRight' | 'Quote' | 'AltGraph' | 'Props' | 'Cancel' | 'Clear' | 'Shift' | 'Control' | 'Alt' | 'Accept' | 'ModeChange' | ' ' | 'Print' | 'Execute' | '\u0000' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z' | 'Meta' | '*' | '+' | '-' | '/' | ';' | '=' | ',' | '.' | '`' | '[' | '\\' | ']' | "'" | 'Attn' | 'CrSel' | 'ExSel' | 'EraseEof' | 'Play' | 'ZoomOut' | ')' | '!' | '@' | '#' | '$' | '%' | '^' | '&' | '(' | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z' | ':' | '<' | '_' | '>' | '?' | '~' | '{' | '|' | '}' | '"' | 'SoftLeft' | 'SoftRight' | 'Camera' | 'Call' | 'EndCall' | 'VolumeDown' | 'VolumeUp';
All the valid keys that can be passed to functions that take user input, such as keyboard.press
Modifiers
@public
type KeyPressOptions
type KeyPressOptions = KeyDownOptions & KeyboardTypeOptions;
Modifiers
@public
type LocatorClickOptions
type LocatorClickOptions = ClickOptions & ActionOptions;
Modifiers
@public
type LowerCasePaperFormat
type LowerCasePaperFormat = | 'letter' | 'legal' | 'tabloid' | 'ledger' | 'a0' | 'a1' | 'a2' | 'a3' | 'a4' | 'a5' | 'a6';
Modifiers
@public
type Mapper
type Mapper<From, To> = (value: From) => Awaitable<To>;
Modifiers
@public
type MouseButton
type MouseButton = (typeof MouseButton)[keyof typeof MouseButton];
Modifiers
@public
type NodeFor
type NodeFor<ComplexSelector extends string> = ParseSelector<ComplexSelector>;
Modifiers
@public
type PaperFormat
type PaperFormat = | Uppercase<LowerCasePaperFormat> | Capitalize<LowerCasePaperFormat> | LowerCasePaperFormat;
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.1102in x 46.811in-
A1
: 23.3858in x 33.1102in-
A2
: 16.5354in x 23.3858in-
A3
: 11.6929in x 16.5354in-
A4
: 8.2677in x 11.6929in-
A5
: 5.8268in x 8.2677in-
A6
: 4.1339in x 5.8268inModifiers
@public
type Permission
type Permission = | 'geolocation' | 'midi' | 'notifications' | 'camera' | 'microphone' | 'background-sync' | 'ambient-light-sensor' | 'accelerometer' | 'gyroscope' | 'magnetometer' | 'accessibility-events' | 'clipboard-read' | 'clipboard-write' | 'clipboard-sanitized-write' | 'payment-handler' | 'persistent-storage' | 'idle-detection' | 'midi-sysex';
Modifiers
@public
type Predicate
type Predicate<From, To extends From = From> = | ((value: From) => value is To) | ((value: From) => Awaitable<boolean>);
Modifiers
@public
type ProtocolLifeCycleEvent
type ProtocolLifeCycleEvent = | 'load' | 'DOMContentLoaded' | 'networkIdle' | 'networkAlmostIdle';
Modifiers
@public
type ProtocolType
type ProtocolType = 'cdp' | 'webDriverBiDi';
Modifiers
@public
type PuppeteerLifeCycleEvent
type PuppeteerLifeCycleEvent = /** * Waits for the 'load' event. */ | 'load' /** * Waits for the 'DOMContentLoaded' event. */ | 'domcontentloaded' /** * Waits till there are no more than 0 network connections for at least `500` * ms. */ | 'networkidle0' /** * Waits till there are no more than 2 network connections for at least `500` * ms. */ | 'networkidle2';
Modifiers
@public
type PuppeteerNodeLaunchOptions
type PuppeteerNodeLaunchOptions = BrowserLaunchArgumentOptions & LaunchOptions & BrowserConnectOptions;
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.Modifiers
@public
type Quad
type Quad = [Point, Point, Point, Point];
Modifiers
@public
type ResourceType
type ResourceType = Lowercase<Protocol.Network.ResourceType>;
Resource types for HTTPRequests as perceived by the rendering engine.
Modifiers
@public
type SupportedBrowser
type SupportedBrowser = 'chrome' | 'firefox';
Browsers supported by Puppeteer.
Modifiers
@public
type SupportedWebDriverCapability
type SupportedWebDriverCapability = Exclude< Session.CapabilityRequest, 'unhandledPromptBehavior' | 'acceptInsecureCerts'>;
Modifiers
@public
type TargetFilterCallback
type TargetFilterCallback = (target: Target) => boolean;
Modifiers
@public
type VisibilityOption
type VisibilityOption = 'hidden' | 'visible' | null;
Namespaces
namespace CDPSessionEvent
namespace CDPSessionEvent {}
Events that the CDPSession class emits.
Modifiers
@public
variable SessionAttached
const SessionAttached: string;
variable SessionDetached
const SessionDetached: string;
namespace CustomQuerySelectors
namespace CustomQuerySelectors {}
variable customQuerySelectors
const customQuerySelectors: CustomQuerySelectorRegistry;
interface CustomQuerySelector
interface CustomQuerySelector {}
method querySelector
querySelector: (root: Node, selector: string) => Awaitable<Node | null>;
method querySelectorAll
querySelectorAll: (root: Node, selector: string) => AwaitableIterable<Node>;
namespace PQuerySelector
namespace PQuerySelector {}
namespace Puppeteer_2
namespace Puppeteer_2 {}
variable DEFAULT_INTERCEPT_RESOLUTION_PRIORITY
const DEFAULT_INTERCEPT_RESOLUTION_PRIORITY: number;
The default cooperative request interception resolution priority
Modifiers
@public
variable KnownDevices
const KnownDevices: Readonly< Record< | 'Blackberry PlayBook' | 'Blackberry PlayBook landscape' | 'BlackBerry Z30' | 'BlackBerry Z30 landscape' | 'Galaxy Note 3' | 'Galaxy Note 3 landscape' | 'Galaxy Note II' | 'Galaxy Note II landscape' | 'Galaxy S III' | 'Galaxy S III landscape' | 'Galaxy S5' | 'Galaxy S5 landscape' | 'Galaxy S8' | 'Galaxy S8 landscape' | 'Galaxy S9+' | 'Galaxy S9+ landscape' | 'Galaxy Tab S4' | 'Galaxy Tab S4 landscape' | 'iPad' | 'iPad landscape' | 'iPad (gen 6)' | 'iPad (gen 6) landscape' | 'iPad (gen 7)' | 'iPad (gen 7) landscape' | 'iPad Mini' | 'iPad Mini landscape' | 'iPad Pro' | 'iPad Pro landscape' | 'iPad Pro 11' | 'iPad Pro 11 landscape' | 'iPhone 4' | 'iPhone 4 landscape' | 'iPhone 5' | 'iPhone 5 landscape' | 'iPhone 6' | 'iPhone 6 landscape' | 'iPhone 6 Plus' | 'iPhone 6 Plus landscape' | 'iPhone 7' | 'iPhone 7 landscape' | 'iPhone 7 Plus' | 'iPhone 7 Plus landscape' | 'iPhone 8' | 'iPhone 8 landscape' | 'iPhone 8 Plus' | 'iPhone 8 Plus landscape' | 'iPhone SE' | 'iPhone SE landscape' | 'iPhone X' | 'iPhone X landscape' | 'iPhone XR' | 'iPhone XR landscape' | 'iPhone 11' | 'iPhone 11 landscape' | 'iPhone 11 Pro' | 'iPhone 11 Pro landscape' | 'iPhone 11 Pro Max' | 'iPhone 11 Pro Max landscape' | 'iPhone 12' | 'iPhone 12 landscape' | 'iPhone 12 Pro' | 'iPhone 12 Pro landscape' | 'iPhone 12 Pro Max' | 'iPhone 12 Pro Max landscape' | 'iPhone 12 Mini' | 'iPhone 12 Mini landscape' | 'iPhone 13' | 'iPhone 13 landscape' | 'iPhone 13 Pro' | 'iPhone 13 Pro landscape' | 'iPhone 13 Pro Max' | 'iPhone 13 Pro Max landscape' | 'iPhone 13 Mini' | 'iPhone 13 Mini landscape' | 'iPhone 14' | 'iPhone 14 landscape' | 'iPhone 14 Plus' | 'iPhone 14 Plus landscape' | 'iPhone 14 Pro' | 'iPhone 14 Pro landscape' | 'iPhone 14 Pro Max' | 'iPhone 14 Pro Max landscape' | 'iPhone 15' | 'iPhone 15 landscape' | 'iPhone 15 Plus' | 'iPhone 15 Plus landscape' | 'iPhone 15 Pro' | 'iPhone 15 Pro landscape' | 'iPhone 15 Pro Max' | 'iPhone 15 Pro Max landscape' | 'JioPhone 2' | 'JioPhone 2 landscape' | 'Kindle Fire HDX' | 'Kindle Fire HDX landscape' | 'LG Optimus L70' | 'LG Optimus L70 landscape' | 'Microsoft Lumia 550' | 'Microsoft Lumia 950' | 'Microsoft Lumia 950 landscape' | 'Nexus 10' | 'Nexus 10 landscape' | 'Nexus 4' | 'Nexus 4 landscape' | 'Nexus 5' | 'Nexus 5 landscape' | 'Nexus 5X' | 'Nexus 5X landscape' | 'Nexus 6' | 'Nexus 6 landscape' | 'Nexus 6P' | 'Nexus 6P landscape' | 'Nexus 7' | 'Nexus 7 landscape' | 'Nokia Lumia 520' | 'Nokia Lumia 520 landscape' | 'Nokia N9' | 'Nokia N9 landscape' | 'Pixel 2' | 'Pixel 2 landscape' | 'Pixel 2 XL' | 'Pixel 2 XL landscape' | 'Pixel 3' | 'Pixel 3 landscape' | 'Pixel 4' | 'Pixel 4 landscape' | 'Pixel 4a (5G)' | 'Pixel 4a (5G) landscape' | 'Pixel 5' | 'Pixel 5 landscape' | 'Moto G4' | 'Moto G4 landscape', Device >>;
A list of devices to be used with Page.emulate.
Example 1
import {KnownDevices} from 'puppeteer';const iPhone = KnownDevices['iPhone 15 Pro'];(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();await page.emulate(iPhone);await page.goto('https://www.google.com');// other actions...await browser.close();})();Modifiers
@public
variable MouseButton
const MouseButton: Readonly<{ Left: 'left'; Right: 'right'; Middle: 'middle'; Back: 'back'; Forward: 'forward';}>;
Enum of valid mouse buttons.
Modifiers
@public
variable PredefinedNetworkConditions
const PredefinedNetworkConditions: Readonly<{ 'Slow 3G': NetworkConditions; 'Fast 3G': NetworkConditions; 'Slow 4G': NetworkConditions; 'Fast 4G': NetworkConditions;}>;
A list of pre-defined network conditions to be used with Page.emulateNetworkConditions.
Example 1
import {PredefinedNetworkConditions} from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();await page.emulateNetworkConditions(PredefinedNetworkConditions['Slow 3G'],);await page.goto('https://www.google.com');await page.emulateNetworkConditions(PredefinedNetworkConditions['Fast 3G'],);await page.goto('https://www.google.com');await page.emulateNetworkConditions(PredefinedNetworkConditions['Slow 4G'],); // alias to Fast 3G.await page.goto('https://www.google.com');await page.emulateNetworkConditions(PredefinedNetworkConditions['Fast 4G'],);await page.goto('https://www.google.com');// other actions...await browser.close();})();Modifiers
@public
class Accessibility
class 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.
Modifiers
@public
method snapshot
snapshot: (options?: SnapshotOptions) => Promise<SerializedAXNode | null>;
Captures the current state of the accessibility tree. The returned object represents the root accessible node of the page.
Returns
An AXNode object representing the snapshot.
Remarks
**NOTE** The Chrome 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 tofalse
.Example 1
An example of dumping the entire accessibility tree:
const snapshot = await page.accessibility.snapshot();console.log(snapshot);Example 2
An example of logging the focused node's name:
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;}
class Browser
abstract class Browser extends EventEmitter<BrowserEvents> {}
Browser represents a browser instance that is either:
- connected to via Puppeteer.connect or - launched by PuppeteerNode.launch.
Browser emits various events which are documented in the BrowserEvent enum.
Example 1
Using a Browser to create a Page:
import puppeteer from 'puppeteer';const browser = await puppeteer.launch();const page = await browser.newPage();await page.goto('https://example.com');await browser.close();Example 2
Disconnecting from and reconnecting to a Browser:
import puppeteer from 'puppeteer';const browser = await puppeteer.launch();// Store the endpoint to be able to reconnect to the browser.const browserWSEndpoint = browser.wsEndpoint();// Disconnect puppeteer from the browser.await browser.disconnect();// Use the endpoint to reestablish a connectionconst browser2 = await puppeteer.connect({browserWSEndpoint});// Close the browser.await browser2.close();Modifiers
@public
property connected
readonly connected: boolean;
Whether Puppeteer is connected to this browser.
property debugInfo
readonly debugInfo: DebugInfo;
Get debug information from Puppeteer.
Remarks
Currently, includes pending protocol calls. In the future, we might add more info.
Modifiers
@public
@experimental
method browserContexts
abstract browserContexts: () => BrowserContext[];
Gets a list of open browser contexts.
In a newly-created browser, this will return a single instance of BrowserContext.
method close
abstract close: () => Promise<void>;
method createBrowserContext
abstract createBrowserContext: ( options?: BrowserContextOptions) => Promise<BrowserContext>;
Creates a new browser context.
This won't share cookies/cache with other browser contexts.
Example 1
import puppeteer from 'puppeteer';const browser = await puppeteer.launch();// Create a new browser context.const context = await browser.createBrowserContext();// Create a new page in a pristine context.const page = await context.newPage();// Do stuffawait page.goto('https://example.com');
method defaultBrowserContext
abstract defaultBrowserContext: () => BrowserContext;
Gets the default browser context.
Remarks
The default browser context cannot be closed.
method disconnect
abstract disconnect: () => Promise<void>;
Disconnects Puppeteer from this browser, but leaves the process running.
method isConnected
isConnected: () => boolean;
Whether Puppeteer is connected to this browser.
Deprecated
Use Browser.connected.
method newPage
abstract newPage: () => Promise<Page>;
Creates a new page in the default browser context.
method pages
pages: () => Promise<Page[]>;
Gets a list of all open pages inside this Browser.
If there are multiple browser contexts, this returns all pages in all browser contexts.
Remarks
Non-visible pages, such as
"background_page"
, will not be listed here. You can find them using Target.page.
method process
abstract process: () => ChildProcess | null;
Gets the associated ChildProcess.
Returns
null
if this instance was connected to via Puppeteer.connect.
method target
abstract target: () => Target;
Gets the target associated with the default browser context).
method targets
abstract targets: () => Target[];
Gets all active targets.
In case of multiple browser contexts, this returns all targets in all browser contexts.
method userAgent
abstract userAgent: () => Promise<string>;
Gets this browser's original user agent.
Pages can override the user agent with Page.setUserAgent.
method version
abstract version: () => Promise<string>;
Gets a string representing this browser's name and version.
For headless browser, this is similar to
"HeadlessChrome/61.0.3153.0"
. For non-headless or new-headless, this is similar to"Chrome/61.0.3153.0"
. For Firefox, it is similar to"Firefox/116.0a1"
.The format of Browser.version might change with future releases of browsers.
method waitForTarget
waitForTarget: ( predicate: (x: Target) => boolean | Promise<boolean>, options?: WaitForTargetOptions) => Promise<Target>;
Waits until a target matching the given
predicate
appears and returns it.This will look all open browser contexts.
Example 1
Finding a target for a page opened via
window.open
:await page.evaluate(() => window.open('https://www.example.com/'));const newWindowTarget = await browser.waitForTarget(target => target.url() === 'https://www.example.com/',);
method wsEndpoint
abstract wsEndpoint: () => string;
Gets the WebSocket URL to connect to this browser.
This is usually used with Puppeteer.connect.
You can find the debugger URL (
webSocketDebuggerUrl
) fromhttp://HOST:PORT/json/version
.See browser endpoint for more information.
Remarks
The format is always
ws://HOST:PORT/devtools/browser/<id>
.
class BrowserContext
abstract class BrowserContext extends EventEmitter<BrowserContextEvents> {}
BrowserContext represents individual user contexts within a browser.
When a browser is launched, it has at least one default browser context. 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
In Chrome all non-default contexts are incognito, and default browser context might be incognito if you provide the
--incognito
argument when launching the browser.Example 1
Creating a new browser context:
// Create a new browser contextconst context = await browser.createBrowserContext();// 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();Modifiers
@public
property closed
readonly closed: boolean;
Whether this browser context is closed.
property id
readonly id: string;
Identifier for this browser context.
method browser
abstract browser: () => Browser;
Gets the browser associated with this browser context.
method clearPermissionOverrides
abstract clearPermissionOverrides: () => Promise<void>;
Clears all permission overrides for this browser context.
Example 1
Clearing overridden permissions in the default browser context:
const context = browser.defaultBrowserContext();context.overridePermissions('https://example.com', ['clipboard-read']);// do stuff ..context.clearPermissionOverrides();
method close
abstract close: () => Promise<void>;
Closes this browser context and all associated pages.
Remarks
The default browser context cannot be closed.
method newPage
abstract newPage: () => Promise<Page>;
Creates a new page in this browser context.
method overridePermissions
abstract overridePermissions: ( origin: string, permissions: Permission[]) => Promise<void>;
Grants this browser context the given
permissions
within the givenorigin
.Parameter origin
The origin to grant permissions to, e.g. "https://example.com".
Parameter permissions
An array of permissions to grant. All permissions that are not listed here will be automatically denied.
Example 1
Overriding permissions in the default browser context:
const context = browser.defaultBrowserContext();await context.overridePermissions('https://html5demos.com', ['geolocation',]);
method pages
abstract pages: () => Promise<Page[]>;
Gets a list of all open pages inside this browser context.
Remarks
Non-visible pages, such as
"background_page"
, will not be listed here. You can find them using Target.page.
method targets
abstract targets: () => Target[];
Gets all active targets inside this browser context.
method waitForTarget
waitForTarget: ( predicate: (x: Target) => boolean | Promise<boolean>, options?: WaitForTargetOptions) => Promise<Target>;
Waits until a target matching the given
predicate
appears and returns it.This will look all open browser contexts.
Example 1
Finding a target for a page opened via
window.open
:await page.evaluate(() => window.open('https://www.example.com/'));const newWindowTarget = await browserContext.waitForTarget(target => target.url() === 'https://www.example.com/',);
class BrowserLauncher
abstract class BrowserLauncher {}
Describes a launcher - a class that is able to create and launch a browser instance.
Modifiers
@public
property browser
readonly browser: SupportedBrowser;
method defaultArgs
abstract defaultArgs: (object: BrowserLaunchArgumentOptions) => string[];
method executablePath
abstract executablePath: (channel?: ChromeReleaseChannel) => string;
method launch
launch: (options?: PuppeteerNodeLaunchOptions) => Promise<Browser>;
class CDPSession
abstract class CDPSession extends EventEmitter<CDPSessionEvents> {}
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.
Example 1
const client = await page.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,});Modifiers
@public
method connection
abstract connection: () => Connection | undefined;
method detach
abstract detach: () => Promise<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.
method id
abstract id: () => string;
Returns the session's id.
method send
abstract send: <T extends string | number | symbol>( method: T, params?: ProtocolMapping.Commands, options?: CommandOptions) => Promise<ProtocolMapping.Commands[T]['returnType']>;
class Connection
class Connection extends EventEmitter<CDPSessionEvents> {}
Modifiers
@public
constructor
constructor( url: string, transport: ConnectionTransport, delay?: number, timeout?: number);
property timeout
readonly timeout: number;
method createSession
createSession: (targetInfo: Protocol.Target.TargetInfo) => Promise<CDPSession>;
Parameter targetInfo
The target info
Returns
The CDP session that is created
method dispose
dispose: () => void;
method fromSession
static fromSession: (session: CDPSession) => Connection | undefined;
method send
send: <T extends string | number | symbol>( method: T, params?: ProtocolMapping.Commands, options?: CommandOptions) => Promise<ProtocolMapping.Commands[T]['returnType']>;
method session
session: (sessionId: string) => CDPSession | null;
Parameter sessionId
The session id
Returns
The current CDP session if it exists
method url
url: () => string;
class ConsoleMessage
class ConsoleMessage {}
ConsoleMessage objects are dispatched by page via the 'console' event.
Modifiers
@public
method args
args: () => JSHandle[];
An array of arguments passed to the console.
method location
location: () => ConsoleMessageLocation;
The location of the console message.
method stackTrace
stackTrace: () => ConsoleMessageLocation[];
The array of locations on the stack of the console message.
method text
text: () => string;
The text of the console message.
method type
type: () => ConsoleMessageType;
The type of the console message.
class Coverage
class 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.
Example 1
An example of using JavaScript and CSS coverage to get percentage of initially executed code:
// Enable both JavaScript and CSS coverageawait Promise.all([page.coverage.startJSCoverage(),page.coverage.startCSSCoverage(),]);// Navigate to pageawait page.goto('https://example.com');// Disable both JavaScript and CSS coverageconst [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}%`);Modifiers
@public
method startCSSCoverage
startCSSCoverage: (options?: CSSCoverageOptions) => Promise<void>;
Parameter options
Set of configurable options for coverage, defaults to
resetOnNavigation : true
Returns
Promise that resolves when coverage is started.
method startJSCoverage
startJSCoverage: (options?: JSCoverageOptions) => Promise<void>;
Parameter options
Set of configurable options for coverage defaults to
resetOnNavigation : true, reportAnonymousScripts : false,
includeRawScriptCoverage : false, useBlockCoverage : true
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
ornew Function
. IfreportAnonymousScripts
is set totrue
, anonymous scripts URL will start withdebugger://VM
(unless a magic //# sourceURL comment is present, in which case that will the be URL).
method stopCSSCoverage
stopCSSCoverage: () => Promise<CoverageEntry[]>;
Promise that resolves to the array of coverage reports for all stylesheets.
Remarks
CSS Coverage doesn't include dynamically injected style tags without sourceURLs.
method stopJSCoverage
stopJSCoverage: () => Promise<JSCoverageEntry[]>;
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.
class CSSCoverage
class CSSCoverage {}
Modifiers
@public
constructor
constructor(client: CDPSession);
method start
start: (options?: { resetOnNavigation?: boolean }) => Promise<void>;
method stop
stop: () => Promise<CoverageEntry[]>;
class DeviceRequestPrompt
class 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.Example 1
const [devicePrompt] = Promise.all([page.waitForDevicePrompt(),page.click('#connect-bluetooth'),]);await devicePrompt.select(await devicePrompt.waitForDevice(({name}) => name.includes('My Device')),);Modifiers
@public
property devices
devices: DeviceRequestPromptDevice[];
Current list of selectable devices.
method cancel
cancel: () => Promise<void>;
Cancel the prompt.
method select
select: (device: DeviceRequestPromptDevice) => Promise<void>;
Select a device in the prompt's list.
method waitForDevice
waitForDevice: ( filter: (device: DeviceRequestPromptDevice) => boolean, options?: WaitTimeoutOptions) => Promise<DeviceRequestPromptDevice>;
Resolve to the first device in the prompt matching a filter.
class DeviceRequestPromptDevice
class DeviceRequestPromptDevice {}
Device in a request prompt.
Modifiers
@public
class Dialog
abstract class Dialog {}
Dialog instances are dispatched by the Page via the
dialog
event.Remarks
Example 1
import puppeteer from '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'));})();Modifiers
@public
method accept
accept: (promptText?: string) => Promise<void>;
A promise that resolves when the dialog has been accepted.
Parameter promptText
optional text that will be entered in the dialog prompt. Has no effect if the dialog's type is not
prompt
.
method defaultValue
defaultValue: () => string;
The default value of the prompt, or an empty string if the dialog is not a
prompt
.
method dismiss
dismiss: () => Promise<void>;
A promise which will resolve once the dialog has been dismissed
method message
message: () => string;
The message displayed in the dialog.
method type
type: () => Protocol.Page.DialogType;
The type of the dialog.
class ElementHandle
abstract class ElementHandle< ElementType extends Node = Element> extends JSHandle<ElementType> {}
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 asElementHandle<HTMLSelectElement>
and you get some nicer type checks.Modifiers
@public
property frame
readonly frame: Frame;
Frame corresponding to the current handle.
method $
$: <Selector extends string>( selector: Selector) => Promise<ElementHandle<NodeFor<Selector>> | null>;
Queries the current element for an element matching the given selector.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Returns
A element handle to the first element matching the given selector. Otherwise,
null
.
method $$
$$: <Selector extends string>( selector: Selector, options?: QueryOptions) => Promise<Array<ElementHandle<NodeFor<Selector>>>>;
Queries the current element for all elements matching the given selector.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Returns
An array of element handles that point to elements matching the given selector.
method $$eval
$$eval: < Selector extends string, Params extends unknown[], Func extends EvaluateFuncWith< ParseSelector<ComplexSelector>[], Params > = EvaluateFuncWith<ParseSelector<ComplexSelector>[], Params>>( selector: Selector, pageFunction: Func | string, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
Runs the given function on an array of elements matching the given selector in the current element.
If the given function returns a promise, then this method will wait till the promise resolves.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Parameter pageFunction
The function to be evaluated in the element's page's context. An array of elements matching the given selector will be passed to the function as its first argument.
Parameter args
Additional arguments to pass to
pageFunction
.Returns
A promise to the result of the function.
Example 1
HTML:
<div class="feed"><div class="tweet">Hello!</div><div class="tweet">Hi!</div></div>JavaScript:
const feedHandle = await page.$('.feed');expect(await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText)),).toEqual(['Hello!', 'Hi!']);
method $eval
$eval: < Selector extends string, Params extends unknown[], Func extends EvaluateFuncWith< ParseSelector<ComplexSelector>, Params > = EvaluateFuncWith<ParseSelector<ComplexSelector>, Params>>( selector: Selector, pageFunction: Func | string, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
Runs the given function on the first element matching the given selector in the current element.
If the given function returns a promise, then this method will wait till the promise resolves.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Parameter pageFunction
The function to be evaluated in this element's page's context. The first element matching the selector will be passed in as the first argument.
Parameter args
Additional arguments to pass to
pageFunction
.Returns
A promise to the result of the function.
Example 1
const tweetHandle = await page.$('.tweet');expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100',);expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10',);
method autofill
abstract autofill: (data: AutofillData) => Promise<void>;
If the element is a form input, you can use ElementHandle.autofill to test if the form is compatible with the browser's autofill implementation. Throws an error if the form cannot be autofilled.
Remarks
Currently, Puppeteer supports auto-filling credit card information only and in Chrome in the new headless and headful modes only.
// Select an input on the credit card form.const name = await page.waitForSelector('form #name');// Trigger autofill with the desired data.await name.autofill({creditCard: {number: '4444444444444444',name: 'John Smith',expiryMonth: '01',expiryYear: '2030',cvc: '123',},});
method boundingBox
boundingBox: () => Promise<BoundingBox | null>;
This method returns the bounding box of the element (relative to the main frame), or
null
if the element is not part of the layout (example:display: none
).
method boxModel
boxModel: () => Promise<BoxModel | null>;
This method returns boxes of the element, or
null
if the element is not part of the layout (example:display: none
).Remarks
Boxes are represented as an array of points; Each Point is an object
{x, y}
. Box points are sorted clock-wise.
method click
click: ( this: ElementHandle<Element>, options?: Readonly<ClickOptions>) => Promise<void>;
This method scrolls element into view if needed, and then uses Page.mouse to click in the center of the element. If the element is detached from DOM, the method throws an error.
method clickablePoint
clickablePoint: (offset?: Offset) => Promise<Point>;
Returns the middle point within an element unless a specific offset is provided.
method contentFrame
abstract contentFrame: { (this: ElementHandle<HTMLIFrameElement>): Promise<Frame>; (): Promise<Frame>;};
Resolves the frame associated with the element, if any. Always exists for HTMLIFrameElements.
method drag
drag: ( this: ElementHandle<Element>, target: Point | ElementHandle<Element>) => Promise<Protocol.Input.DragData | void>;
Drags an element over the given element or point.
Returns
DEPRECATED. When drag interception is enabled, the drag payload is returned.
method dragAndDrop
dragAndDrop: ( this: ElementHandle<Element>, target: ElementHandle<Node>, options?: { delay: number }) => Promise<void>;
Deprecated
Use
ElementHandle.drop
instead.
method dragEnter
dragEnter: ( this: ElementHandle<Element>, data?: Protocol.Input.DragData) => Promise<void>;
Deprecated
Do not use.
dragenter
will automatically be performed during dragging.
method dragOver
dragOver: ( this: ElementHandle<Element>, data?: Protocol.Input.DragData) => Promise<void>;
Deprecated
Do not use.
dragover
will automatically be performed during dragging.
method drop
drop: { ( this: ElementHandle<Element>, element: ElementHandle<Element> ): Promise<void>; ( this: ElementHandle<Element>, data?: Protocol.Input.DragData ): Promise<void>;};
Drops the given element onto the current one.
Deprecated
No longer supported.
method focus
focus: () => Promise<void>;
Calls focus on the element.
method hover
hover: (this: ElementHandle<Element>) => Promise<void>;
This method scrolls element into view if needed, and then uses Page.mouse to hover over the center of the element. If the element is detached from DOM, the method throws an error.
method isHidden
isHidden: () => Promise<boolean>;
An element is considered to be hidden if at least one of the following is true:
- the element has no computed styles.
- the element has an empty bounding client rect.
- the element's visibility is
hidden
orcollapse
.
method isIntersectingViewport
isIntersectingViewport: ( this: ElementHandle<Element>, options?: { threshold?: number }) => Promise<boolean>;
Resolves to true if the element is visible in the current viewport. If an element is an SVG, we check if the svg owner element is in the viewport instead. See https://crbug.com/963246.
Parameter options
Threshold for the intersection between 0 (no intersection) and 1 (full intersection). Defaults to 1.
method isVisible
isVisible: () => Promise<boolean>;
An element is considered to be visible if all of the following is true:
- the element has computed styles.
- the element has a non-empty bounding client rect.
- the element's visibility is not
hidden
orcollapse
.
method press
press: (key: KeyInput, options?: Readonly<KeyPressOptions>) => Promise<void>;
Focuses the element, and then uses Keyboard.down and Keyboard.up.
Parameter key
Name of key to press, such as
ArrowLeft
. See KeyInput for a list of all key names.Remarks
If
key
is a single character and no modifier keys besidesShift
are being held down, akeypress
/input
event will also be generated. Thetext
option can be specified to force an input event to be generated.**NOTE** Modifier keys DO affect
elementHandle.press
. Holding downShift
will type the text in upper case.
method screenshot
screenshot: { ( options: Readonly<ScreenshotOptions> & { encoding: 'base64' } ): Promise<string>; (options?: Readonly<ScreenshotOptions>): Promise<Uint8Array>;};
This method scrolls element into view if needed, and then uses Page.screenshot to take a screenshot of the element. If the element is detached from DOM, the method throws an error.
method scrollIntoView
scrollIntoView: (this: ElementHandle<Element>) => Promise<void>;
Scrolls the element into view using either the automation protocol client or by calling element.scrollIntoView.
method select
select: (...values: string[]) => Promise<string[]>;
Triggers a
change
andinput
event once all the provided options have been selected. If there's no<select>
element matchingselector
, the method throws an error.Parameter values
Values of options to select. If the
<select>
has themultiple
attribute, all values are considered, otherwise only the first one is taken into account.Example 1
handle.select('blue'); // single selectionhandle.select('red', 'green', 'blue'); // multiple selections
method tap
tap: (this: ElementHandle<Element>) => Promise<void>;
This method scrolls element into view if needed, and then uses Touchscreen.tap to tap in the center of the element. If the element is detached from DOM, the method throws an error.
method toElement
toElement: < K extends | 'symbol' | 'object' | 'dir' | 'table' | 'a' | 'abbr' | 'address' | 'area' | 'article' | 'aside' | 'audio' | 'b' | 'base' | 'bdi' | 'bdo' | 'blockquote' | 'body' | 'br' | 'button' | 'canvas' | 'caption' | 'cite' | 'code' | 'col' | 'colgroup' | 'data' | 'datalist' | 'dd' | 'del' | 'details' | 'dfn' | 'dialog' | 'div' | 'dl' | 'dt' | 'em' | 'embed' | 'fieldset' | 'figcaption' | 'figure' | 'font' | 'footer' | 'form' | 'frame' | 'frameset' | 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'head' | 'header' | 'hgroup' | 'hr' | 'html' | 'i' | 'iframe' | 'img' | 'input' | 'ins' | 'kbd' | 'label' | 'legend' | 'li' | 'link' | 'main' | 'map' | 'mark' | 'marquee' | 'menu' | 'meta' | 'meter' | 'nav' | 'noscript' | 'ol' | 'optgroup' | 'option' | 'output' | 'p' | 'param' | 'picture' | 'pre' | 'progress' | 'q' | 'rp' | 'rt' | 'ruby' | 's' | 'samp' | 'script' | 'section' | 'select' | 'slot' | 'small' | 'source' | 'span' | 'strong' | 'style' | 'sub' | 'summary' | 'sup' | 'tbody' | 'td' | 'template' | 'textarea' | 'tfoot' | 'th' | 'thead' | 'time' | 'title' | 'tr' | 'track' | 'u' | 'ul' | 'var' | 'video' | 'wbr' | 'animate' | 'animateMotion' | 'animateTransform' | 'circle' | 'clipPath' | 'defs' | 'desc' | 'ellipse' | 'feBlend' | 'feColorMatrix' | 'feComponentTransfer' | 'feComposite' | 'feConvolveMatrix' | 'feDiffuseLighting' | 'feDisplacementMap' | 'feDistantLight' | 'feDropShadow' | 'feFlood' | 'feFuncA' | 'feFuncB' | 'feFuncG' | 'feFuncR' | 'feGaussianBlur' | 'feImage' | 'feMerge' | 'feMergeNode' | 'feMorphology' | 'feOffset' | 'fePointLight' | 'feSpecularLighting' | 'feSpotLight' | 'feTile' | 'feTurbulence' | 'filter' | 'foreignObject' | 'g' | 'image' | 'line' | 'linearGradient' | 'marker' | 'mask' | 'metadata' | 'mpath' | 'path' | 'pattern' | 'polygon' | 'polyline' | 'radialGradient' | 'rect' | 'set' | 'stop' | 'svg' | 'switch' | 'text' | 'textPath' | 'tspan' | 'use' | 'view'>( tagName: K) => Promise<HandleFor<ElementFor<K>>>;
Converts the current handle to the given element type.
Parameter tagName
The tag name of the desired element type.
Throws
An error if the handle does not match. **The handle will not be automatically disposed.**
Example 1
const element: ElementHandle<Element> = await page.$('.class-name-of-anchor',);// DO NOT DISPOSE `element`, this will be always be the same handle.const anchor: ElementHandle<HTMLAnchorElement> =await element.toElement('a');
method touchEnd
touchEnd: (this: ElementHandle<Element>) => Promise<void>;
method touchMove
touchMove: (this: ElementHandle<Element>, touch?: TouchHandle) => Promise<void>;
This method scrolls the element into view if needed, and then moves the touch to the center of the element.
Parameter touch
An optional TouchHandle. If provided, this touch will be moved. If not provided, the first active touch will be moved.
method touchStart
touchStart: (this: ElementHandle<Element>) => Promise<TouchHandle>;
This method scrolls the element into view if needed, and then starts a touch in the center of the element.
Returns
A TouchHandle representing the touch that was started
method type
type: (text: string, options?: Readonly<KeyboardTypeOptions>) => Promise<void>;
Focuses the element, and then sends a
keydown
,keypress
/input
, andkeyup
event for each character in the text.To press a special key, like
Control
orArrowDown
, use ElementHandle.press.Parameter options
Delay in milliseconds. Defaults to 0.
Example 1
await elementHandle.type('Hello'); // Types instantlyawait elementHandle.type('World', {delay: 100}); // Types slower, like a userExample 2
An example of typing into a text field and then submitting the form:
const elementHandle = await page.$('input');await elementHandle.type('some text');await elementHandle.press('Enter');
method uploadFile
abstract uploadFile: ( this: ElementHandle<HTMLInputElement>, ...paths: string[]) => Promise<void>;
Sets the value of an input element to the given file paths.
Remarks
This will not validate whether the file paths exists. Also, if a path is relative, then it is resolved against the current working directory. For locals script connecting to remote chrome environments, paths must be absolute.
method waitForSelector
waitForSelector: <Selector extends string>( selector: Selector, options?: WaitForSelectorOptions) => Promise<ElementHandle<NodeFor<Selector>> | null>;
Wait for an element matching the given selector to appear in the current element.
Unlike Frame.waitForSelector, this method does not work across navigations or if the element is detached from DOM.
Parameter selector
The selector to query and wait for.
Parameter options
Options for customizing waiting behavior.
Returns
An element matching the given selector.
Throws
Throws if an element matching the given selector doesn't appear.
Example 1
import puppeteer from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();let currentURL;page.mainFrame().waitForSelector('img').then(() => console.log('First URL with image: ' + currentURL));for (currentURL of ['https://example.com','https://google.com','https://bbc.com',]) {await page.goto(currentURL);}await browser.close();})();
class EventEmitter
class EventEmitter<Events extends Record<EventType, unknown>> implements CommonEventEmitter<EventsWithWildcard<Events>> {}
method emit
emit: <Key extends '*' | keyof Events>( type: Key, event: EventsWithWildcard<Events>[Key]) => boolean;
Emit an event and call any associated listeners.
Parameter type
the event you'd like to emit
Parameter eventData
any data you'd like to emit with the event
Returns
true
if there are any listeners,false
if there are not.
method listenerCount
listenerCount: (type: keyof EventsWithWildcard<Events>) => number;
Gets the number of listeners for a given event.
Parameter type
the event to get the listener count for
Returns
the number of listeners bound to the given event
method off
off: <Key extends '*' | keyof Events>( type: Key, handler?: Handler<EventsWithWildcard<Events>[Key]>) => this;
Remove an event listener from firing.
Parameter type
the event type you'd like to stop listening to.
Parameter handler
the function that should be removed.
Returns
this
to enable you to chain method calls.
method on
on: <Key extends '*' | keyof Events>( type: Key, handler: Handler<EventsWithWildcard<Events>[Key]>) => this;
Bind an event listener to fire when an event occurs.
Parameter type
the event type you'd like to listen to. Can be a string or symbol.
Parameter handler
the function to be called when the event occurs.
Returns
this
to enable you to chain method calls.
method once
once: <Key extends '*' | keyof Events>( type: Key, handler: Handler<EventsWithWildcard<Events>[Key]>) => this;
Like
on
but the listener will only be fired once and then it will be removed.Parameter type
the event you'd like to listen to
Parameter handler
the handler function to run when the event occurs
Returns
this
to enable you to chain method calls.
method removeAllListeners
removeAllListeners: (type?: keyof EventsWithWildcard<Events>) => this;
Removes all listeners. If given an event argument, it will remove only listeners for that event.
Parameter type
the event to remove listeners for.
Returns
this
to enable you to chain method calls.
class ExtensionTransport
class ExtensionTransport implements ConnectionTransport {}
Experimental ExtensionTransport allows establishing a connection via chrome.debugger API if Puppeteer runs in an extension. Since Chrome DevTools Protocol is restricted for extensions, the transport implements missing commands and events.
Modifiers
@experimental
@public
property onclose
onclose?: () => void;
property onmessage
onmessage?: (message: string) => void;
method close
close: () => void;
method connectTab
static connectTab: (tabId: number) => Promise<ExtensionTransport>;
method send
send: (message: string) => void;
class FileChooser
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.
Example 1
const [fileChooser] = await Promise.all([page.waitForFileChooser(),page.click('#upload-file-button'), // some button that triggers file selection]);await fileChooser.accept(['/tmp/myfile.pdf']);Modifiers
@public
method accept
accept: (paths: string[]) => Promise<void>;
Accept the file chooser request with the given file paths.
Remarks
This will not validate whether the file paths exists. Also, if a path is relative, then it is resolved against the current working directory. For locals script connecting to remote chrome environments, paths must be absolute.
method cancel
cancel: () => Promise<void>;
Closes the file chooser without selecting any files.
method isMultiple
isMultiple: () => boolean;
Whether file chooser allow for multiple file selection.
class Frame
abstract class Frame extends EventEmitter<FrameEvents> {}
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:
- PageEvent.FrameAttached - PageEvent.FrameNavigated - PageEvent.FrameDetached
Example 1
At any point in time, pages expose their current frame tree via the Page.mainFrame and Frame.childFrames methods.
Example 2
An example of dumping frame tree:
import puppeteer from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();await page.goto('https://www.google.com/chrome/browser/canary.html');dumpFrameTree(page.mainFrame(), '');await browser.close();function dumpFrameTree(frame, indent) {console.log(indent + frame.url());for (const child of frame.childFrames()) {dumpFrameTree(child, indent + ' ');}}})();Example 3
An example of getting text from an iframe element:
const frame = page.frames().find(frame => frame.name() === 'myframe');const text = await frame.$eval('.selector', element => element.textContent);console.log(text);Modifiers
@public
property detached
readonly detached: boolean;
Returns
true
if the frame has detached.false
otherwise.
method $
$: <Selector extends string>( selector: Selector) => Promise<ElementHandle<NodeFor<Selector>> | null>;
Queries the frame for an element matching the given selector.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Returns
A element handle to the first element matching the given selector. Otherwise,
null
.
method $$
$$: <Selector extends string>( selector: Selector, options?: QueryOptions) => Promise<Array<ElementHandle<NodeFor<Selector>>>>;
Queries the frame for all elements matching the given selector.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Returns
An array of element handles that point to elements matching the given selector.
method $$eval
$$eval: < Selector extends string, Params extends unknown[], Func extends EvaluateFuncWith< ParseSelector<ComplexSelector>[], Params > = EvaluateFuncWith<ParseSelector<ComplexSelector>[], Params>>( selector: Selector, pageFunction: string | Func, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
Runs the given function on an array of elements matching the given selector in the frame.
If the given function returns a promise, then this method will wait till the promise resolves.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Parameter pageFunction
The function to be evaluated in the frame's context. An array of elements matching the given selector will be passed to the function as its first argument.
Parameter args
Additional arguments to pass to
pageFunction
.Returns
A promise to the result of the function.
Example 1
const divsCounts = await frame.$$eval('div', divs => divs.length);
method $eval
$eval: < Selector extends string, Params extends unknown[], Func extends EvaluateFuncWith< ParseSelector<ComplexSelector>, Params > = EvaluateFuncWith<ParseSelector<ComplexSelector>, Params>>( selector: Selector, pageFunction: string | Func, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
Runs the given function on the first element matching the given selector in the frame.
If the given function returns a promise, then this method will wait till the promise resolves.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Parameter pageFunction
The function to be evaluated in the frame's context. The first element matching the selector will be passed to the function as its first argument.
Parameter args
Additional arguments to pass to
pageFunction
.Returns
A promise to the result of the function.
Example 1
const searchValue = await frame.$eval('#search', el => el.value);
method addScriptTag
addScriptTag: ( options: FrameAddScriptTagOptions) => Promise<ElementHandle<HTMLScriptElement>>;
Adds a
<script>
tag into the page with the desired url or content.Parameter options
Options for the script.
Returns
An element handle to the injected
<script>
element.
method addStyleTag
addStyleTag: { (options: Omit<FrameAddStyleTagOptions, 'url'>): Promise< ElementHandle<HTMLStyleElement> >; (options: FrameAddStyleTagOptions): Promise<ElementHandle<HTMLLinkElement>>;};
Adds a
HTMLStyleElement
into the frame with the desired URLReturns
An element handle to the loaded
<style>
element.Adds a
HTMLLinkElement
into the frame with the desired URLReturns
An element handle to the loaded
<link>
element.
method childFrames
abstract childFrames: () => Frame[];
An array of child frames.
method click
click: (selector: string, options?: Readonly<ClickOptions>) => Promise<void>;
Clicks the first element found that matches
selector
.Parameter selector
The selector to query for.
Remarks
If
click()
triggers a navigation event and there's a separatepage.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:const [response] = await Promise.all([page.waitForNavigation(waitOptions),frame.click(selector, clickOptions),]);
method content
content: () => Promise<string>;
The full HTML contents of the frame, including the DOCTYPE.
method evaluate
evaluate: < Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>( pageFunction: Func | string, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
Behaves identically to Page.evaluate except it's run within the context of this frame.
See Page.evaluate for details.
method evaluateHandle
evaluateHandle: < Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>( pageFunction: Func | string, ...args: Params) => Promise<HandleFor<Awaited<ReturnType<Func>>>>;
Behaves identically to Page.evaluateHandle except it's run within the context of this frame.
See Page.evaluateHandle for details.
method focus
focus: (selector: string) => Promise<void>;
Focuses the first element that matches the
selector
.Parameter selector
The selector to query for.
Throws
Throws if there's no element matching
selector
.
method frameElement
frameElement: () => Promise<HandleFor<HTMLIFrameElement> | null>;
Returns
The frame element associated with this frame (if any).
method goto
abstract goto: ( url: string, options?: GoToOptions) => Promise<HTTPResponse | null>;
Navigates the frame or page to the given
url
.Parameter url
URL to navigate the frame to. The URL should include scheme, e.g.
https://
Parameter options
Options to configure waiting behavior.
Returns
A promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
Throws
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 remote server does not respond or is unreachable.
- the main resource failed to load.
Remarks
Navigation to
about:blank
or navigation to the same URL with a different hash will succeed and returnnull
.:::warning
Headless shell mode doesn't support navigation to a PDF document. See the upstream issue.
:::
In headless shell, this method will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling HTTPResponse.status.
method hover
hover: (selector: string) => Promise<void>;
Hovers the pointer over the center of the first element that matches the
selector
.Parameter selector
The selector to query for.
Throws
Throws if there's no element matching
selector
.
method isDetached
isDetached: () => boolean;
Is
true
if the frame has been detached. Otherwise,false
.Deprecated
Use the
detached
getter.
method locator
locator: { <Selector extends string>(selector: Selector): Locator<NodeFor<Selector>>; <Ret>(func: () => Awaitable<Ret>): Locator<Ret>;};
Creates a locator for the provided selector. See Locator for details and supported actions.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Creates a locator for the provided function. See Locator for details and supported actions.
method name
name: () => string;
The frame's
name
attribute as specified in the tag.Remarks
This value is calculated once when the frame is created, and will not update if the attribute is changed later.
Deprecated
Use
const element = await frame.frameElement();const nameOrId = await element.evaluate(frame => frame.name ?? frame.id);
method page
abstract page: () => Page;
The page associated with the frame.
method parentFrame
abstract parentFrame: () => Frame | null;
The parent frame, if any. Detached and main frames return
null
.
method select
select: (selector: string, ...values: string[]) => Promise<string[]>;
Selects a set of value on the first
<select>
element that matches theselector
.Parameter selector
The selector to query for.
Parameter values
The array of values to select. If the
<select>
has themultiple
attribute, all values are considered, otherwise only the first one is taken into account.Returns
the list of values that were successfully selected.
Throws
Throws if there's no
<select>
matchingselector
.Example 1
frame.select('select#colors', 'blue'); // single selectionframe.select('select#colors', 'red', 'green', 'blue'); // multiple selections
method setContent
abstract setContent: (html: string, options?: WaitForOptions) => Promise<void>;
Set the content of the frame.
Parameter html
HTML markup to assign to the page.
Parameter options
Options to configure how long before timing out and at what point to consider the content setting successful.
method tap
tap: (selector: string) => Promise<void>;
Taps the first element that matches the
selector
.Parameter selector
The selector to query for.
Throws
Throws if there's no element matching
selector
.
method title
title: () => Promise<string>;
The frame's title.
method type
type: ( selector: string, text: string, options?: Readonly<KeyboardTypeOptions>) => Promise<void>;
Sends a
keydown
,keypress
/input
, andkeyup
event for each character in the text.Parameter selector
the selector for the element to type into. If there are multiple the first will be used.
Parameter text
text to type into the element
Parameter options
takes one option,
delay
, which sets the time to wait between key presses in milliseconds. Defaults to0
.Remarks
To press a special key, like
Control
orArrowDown
, use Keyboard.press.Example 1
await frame.type('#mytextarea', 'Hello'); // Types instantlyawait frame.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user
method url
abstract url: () => string;
The frame's URL.
method waitForFunction
waitForFunction: < Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>( pageFunction: Func | string, options?: FrameWaitForFunctionOptions, ...args: Params) => Promise<HandleFor<Awaited<ReturnType<Func>>>>;
Parameter pageFunction
the function to evaluate in the frame context.
Parameter options
options to configure the polling method and timeout.
Parameter args
arguments to pass to the
pageFunction
.Returns
the promise which resolve when the
pageFunction
returns a truthy value.Example 1
The
waitForFunction
can be used to observe viewport size change:import puppeteer from 'puppeteer';(async () => {. const browser = await puppeteer.launch();. const page = await browser.newPage();. const watchDog = page.mainFrame().waitForFunction('window.innerWidth < 100');. page.setViewport({width: 50, height: 50});. await watchDog;. await browser.close();})();To pass arguments from Node.js to the predicate of
page.waitForFunction
function:const selector = '.foo';await frame.waitForFunction(selector => !!document.querySelector(selector),{}, // empty options objectselector,);
method waitForNavigation
abstract waitForNavigation: ( options?: WaitForOptions) => Promise<HTTPResponse | null>;
Waits for the frame to navigate. It is useful for when you run code which will indirectly cause the frame to navigate.
Usage of the History API to change the URL is considered a navigation.
Parameter options
Options to configure waiting behavior.
Returns
A promise which resolves to the main resource response.
Example 1
const [response] = await Promise.all([// The navigation promise resolves after navigation has finishedframe.waitForNavigation(),// Clicking the link will indirectly cause a navigationframe.click('a.my-link'),]);
method waitForSelector
waitForSelector: <Selector extends string>( selector: Selector, options?: WaitForSelectorOptions) => Promise<ElementHandle<NodeFor<Selector>> | null>;
Waits for an element matching the given selector to appear in the frame.
This method works across navigations.
Parameter selector
The selector to query and wait for.
Parameter options
Options for customizing waiting behavior.
Returns
An element matching the given selector.
Throws
Throws if an element matching the given selector doesn't appear.
Example 1
import puppeteer from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();let currentURL;page.mainFrame().waitForSelector('img').then(() => console.log('First URL with image: ' + currentURL));for (currentURL of ['https://example.com','https://google.com','https://bbc.com',]) {await page.goto(currentURL);}await browser.close();})();
class HTTPRequest
abstract 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 therequestfailed
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.Modifiers
@public
property client
readonly client: CDPSession;
Warning! Using this client can break Puppeteer. Use with caution.
Modifiers
@experimental
method abort
abort: (errorCode?: ErrorCode, priority?: number) => Promise<void>;
Aborts a request.
Parameter errorCode
optional error code to provide.
Parameter priority
If provided, intercept is resolved using cooperative handling rules. Otherwise, intercept is resolved immediately.
Remarks
To use this, request interception should be enabled with Page.setRequestInterception. If it is not enabled, this method will throw an exception immediately.
method abortErrorReason
abortErrorReason: () => Protocol.Network.ErrorReason | null;
The most recent reason for aborting the request
method continue
continue: ( overrides?: ContinueRequestOverrides, priority?: number) => Promise<void>;
Continues request with optional request overrides.
Parameter overrides
optional overrides to apply to the request.
Parameter priority
If provided, intercept is resolved using cooperative handling rules. Otherwise, intercept is resolved immediately.
Remarks
To use this, request interception should be enabled with Page.setRequestInterception.
Exception is immediately thrown if the request interception is not enabled.
Example 1
await page.setRequestInterception(true);page.on('request', request => {// Override headersconst headers = Object.assign({}, request.headers(), {foo: 'bar', // set "foo" headerorigin: undefined, // remove "origin" header});request.continue({headers});});
method continueRequestOverrides
continueRequestOverrides: () => ContinueRequestOverrides;
The
ContinueRequestOverrides
that will be used if the interception is allowed to continue (ie,abort()
andrespond()
aren't called).
method enqueueInterceptAction
enqueueInterceptAction: ( pendingHandler: () => void | PromiseLike<unknown>) => void;
Adds an async request handler to the processing queue. Deferred handlers are not guaranteed to execute in any particular order, but they are guaranteed to resolve before the request interception is finalized.
method failure
abstract failure: () => { errorText: string } | null;
Access information about the request's failure.
Returns
null
unless the request failed. If the request fails this can return an object witherrorText
containing a human-readable error message, e.g.net::ERR_FAILED
. It is not guaranteed that there will be failure text if the request fails.Remarks
Example 1
Example of logging all failed requests:
page.on('requestfailed', request => {console.log(request.url() + ' ' + request.failure().errorText);});
method fetchPostData
abstract fetchPostData: () => Promise<string | undefined>;
Fetches the POST data for the request from the browser.
method finalizeInterceptions
finalizeInterceptions: () => Promise<void>;
Awaits pending interception handlers and then decides how to fulfill the request interception.
method frame
abstract frame: () => Frame | null;
The frame that initiated the request, or null if navigating to error pages.
method hasPostData
abstract hasPostData: () => boolean;
True when the request has POST data. Note that HTTPRequest.postData might still be undefined when this flag is true when the data is too long or not readily available in the decoded form. In that case, use HTTPRequest.fetchPostData.
method headers
abstract headers: () => Record<string, string>;
An object with HTTP headers associated with the request. All header names are lower-case.
method initiator
abstract initiator: () => Protocol.Network.Initiator | undefined;
The initiator of the request.
method interceptResolutionState
interceptResolutionState: () => InterceptResolutionState;
An InterceptResolutionState object describing the current resolution action and priority.
InterceptResolutionState contains: action: InterceptResolutionAction priority?: number
InterceptResolutionAction is one of:
abort
,respond
,continue
,disabled
,none
, oralready-handled
.
method isInterceptResolutionHandled
isInterceptResolutionHandled: () => boolean;
Is
true
if the intercept resolution has already been handled,false
otherwise.
method isNavigationRequest
abstract isNavigationRequest: () => boolean;
True if the request is the driver of the current frame's navigation.
method method
abstract method: () => string;
The method used (
GET
,POST
, etc.)
method postData
abstract postData: () => string | undefined;
The request's post body, if any.
method redirectChain
abstract redirectChain: () => HTTPRequest[];
A
redirectChain
is a chain of requests initiated to fetch a resource.Returns
the chain of requests - if a server responds with at least a single redirect, this chain will contain all requests that were redirected.
Remarks
redirectChain
is shared between all the requests of the same chain.For example, if the website
http://example.com
has a single redirect tohttps://example.com
, then the chain will contain one request:const response = await page.goto('http://example.com');const chain = response.request().redirectChain();console.log(chain.length); // 1console.log(chain[0].url()); // 'http://example.com'If the website
https://google.com
has no redirects, then the chain will be empty:const response = await page.goto('https://google.com');const chain = response.request().redirectChain();console.log(chain.length); // 0
method resourceType
abstract resourceType: () => Protocol.Network.ResourceType;
Contains the request's resource type as it was perceived by the rendering engine.
method respond
respond: ( response: Partial<ResponseForRequest>, priority?: number) => Promise<void>;
Fulfills a request with the given response.
Parameter response
the response to fulfill the request with.
Parameter priority
If provided, intercept is resolved using cooperative handling rules. Otherwise, intercept is resolved immediately.
Remarks
To use this, request interception should be enabled with Page.setRequestInterception.
Exception is immediately thrown if the request interception is not enabled.
Example 1
An example of fulfilling all requests with 404 responses:
await page.setRequestInterception(true);page.on('request', request => {request.respond({status: 404,contentType: 'text/plain',body: 'Not Found!',});});NOTE: Mocking responses for dataURL requests is not supported. Calling
request.respond
for a dataURL request is a noop.
method response
abstract response: () => HTTPResponse | null;
A matching
HTTPResponse
object, or null if the response has not been received yet.
method responseForRequest
responseForRequest: () => Partial<ResponseForRequest> | null;
The
ResponseForRequest
that gets used if the interception is allowed to respond (ie,abort()
is not called).
method url
abstract url: () => string;
The URL of the request
class HTTPResponse
abstract class HTTPResponse {}
The HTTPResponse class represents responses which are received by the Page class.
Modifiers
@public
method buffer
buffer: () => Promise<Buffer>;
See documentation for HTTPResponse.content.
method content
abstract content: () => Promise<Uint8Array>;
Promise which resolves to a buffer with response body.
Remarks
The buffer might be re-encoded by the browser based on HTTP-headers or other heuristics. If the browser failed to detect the correct encoding, the buffer might be encoded incorrectly. See https://github.com/puppeteer/puppeteer/issues/6478.
method frame
abstract frame: () => Frame | null;
A Frame that initiated this response, or
null
if navigating to error pages.
method fromCache
abstract fromCache: () => boolean;
True if the response was served from either the browser's disk cache or memory cache.
method fromServiceWorker
abstract fromServiceWorker: () => boolean;
True if the response was served by a service worker.
method headers
abstract headers: () => Record<string, string>;
An object with HTTP headers associated with the response. All header names are lower-case.
method json
json: () => Promise<any>;
Promise which resolves to a JSON representation of response body.
Remarks
This method will throw if the response body is not parsable via
JSON.parse
.
method ok
ok: () => boolean;
True if the response was successful (status in the range 200-299).
method remoteAddress
abstract remoteAddress: () => RemoteAddress;
The IP address and port number used to connect to the remote server.
method request
abstract request: () => HTTPRequest;
A matching HTTPRequest object.
method securityDetails
abstract securityDetails: () => SecurityDetails | null;
SecurityDetails if the response was received over the secure connection, or
null
otherwise.
method status
abstract status: () => number;
The status code of the response (e.g., 200 for a success).
method statusText
abstract statusText: () => string;
The status text of the response (e.g. usually an "OK" for a success).
method text
text: () => Promise<string>;
Promise which resolves to a text (utf8) representation of response body.
method timing
abstract timing: () => Protocol.Network.ResourceTiming | null;
Timing information related to the response.
method url
abstract url: () => string;
The URL of the response.
class JSCoverage
class JSCoverage {}
Modifiers
@public
class JSHandle
abstract class JSHandle<T = unknown> {}
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.
Example 1
const windowHandle = await page.evaluateHandle(() => window);Modifiers
@public
property move
move: () => this;
method asElement
abstract asElement: () => ElementHandle<Node> | null;
Either
null
or the handle itself if the handle is an instance of ElementHandle.
method dispose
abstract dispose: () => Promise<void>;
Releases the object referenced by the handle for garbage collection.
method evaluate
evaluate: < Params extends unknown[], Func extends EvaluateFuncWith<T, Params> = EvaluateFuncWith<T, Params>>( pageFunction: Func | string, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
Evaluates the given function with the current handle as its first argument.
method evaluateHandle
evaluateHandle: < Params extends unknown[], Func extends EvaluateFuncWith<T, Params> = EvaluateFuncWith<T, Params>>( pageFunction: Func | string, ...args: Params) => Promise<HandleFor<Awaited<ReturnType<Func>>>>;
Evaluates the given function with the current handle as its first argument.
method getProperties
getProperties: () => Promise<Map<string, JSHandle>>;
Gets a map of handles representing the properties of the current handle.
Example 1
const listHandle = await page.evaluateHandle(() => document.body.children);const properties = await listHandle.getProperties();const children = [];for (const property of properties.values()) {const element = property.asElement();if (element) {children.push(element);}}children; // holds elementHandles to all children of document.body
method getProperty
getProperty: { <K extends keyof T>(propertyName: HandleOr<K>): Promise<HandleFor<T[K]>>; (propertyName: string): Promise<JSHandle<unknown>>;};
Fetches a single property from the referenced object.
method jsonValue
abstract jsonValue: () => Promise<T>;
A vanilla object representing the serializable portions of the referenced object.
Throws
Throws if the object cannot be serialized due to circularity.
Remarks
If the object has a
toJSON
function, it **will not** be called.
method remoteObject
abstract remoteObject: () => Protocol.Runtime.RemoteObject;
Provides access to the Protocol.Runtime.RemoteObject backing this handle.
method toString
abstract toString: () => string;
Returns a string representation of the JSHandle.
Remarks
Useful during debugging.
class Keyboard
abstract 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.Example 1
An example of holding down
Shift
in order to select and delete some text:await page.keyboard.type('Hello World!');await page.keyboard.press('ArrowLeft');await page.keyboard.down('Shift');for (let i = 0; i < ' World'.length; i++)await page.keyboard.press('ArrowLeft');await page.keyboard.up('Shift');await page.keyboard.press('Backspace');// Result text will end up saying 'Hello!'Example 2
An example of pressing
A
await page.keyboard.down('Shift');await page.keyboard.press('KeyA');await page.keyboard.up('Shift');Modifiers
@public
method down
abstract down: ( key: KeyInput, options?: Readonly<KeyDownOptions>) => Promise<void>;
Dispatches a
keydown
event.Parameter key
Name of key to press, such as
ArrowLeft
. See KeyInput for a list of all key names.Parameter options
An object of options. Accepts text which, if specified, generates an input event with this text. Accepts commands which, if specified, is the commands of keyboard shortcuts, see Chromium Source Code for valid command names.
Remarks
If
key
is a single character and no modifier keys besidesShift
are being held down, akeypress
/input
event will also generated. Thetext
option can be specified to force an input event to be generated. Ifkey
is a modifier key,Shift
,Meta
,Control
, orAlt
, subsequent key presses will be sent with that modifier active. To release the modifier key, use Keyboard.up.After the key is pressed once, subsequent calls to Keyboard.down will have repeat set to true. To release the key, use Keyboard.up.
Modifier keys DO influence Keyboard.down. Holding down
Shift
will type the text in upper case.
method press
abstract press: ( key: KeyInput, options?: Readonly<KeyPressOptions>) => Promise<void>;
Shortcut for Keyboard.down and Keyboard.up.
Parameter key
Name of key to press, such as
ArrowLeft
. See KeyInput for a list of all key names.Parameter options
An object of options. Accepts text which, if specified, generates an input event with this text. Accepts delay which, if specified, is the time to wait between
keydown
andkeyup
in milliseconds. Defaults to 0. Accepts commands which, if specified, is the commands of keyboard shortcuts, see Chromium Source Code for valid command names.Remarks
If
key
is a single character and no modifier keys besidesShift
are being held down, akeypress
/input
event will also generated. Thetext
option can be specified to force an input event to be generated.Modifier keys DO effect Keyboard.press. Holding down
Shift
will type the text in upper case.
method sendCharacter
abstract sendCharacter: (char: string) => Promise<void>;
Dispatches a
keypress
andinput
event. This does not send akeydown
orkeyup
event.Parameter char
Character to send into the page.
Remarks
Modifier keys DO NOT effect Keyboard.sendCharacter. Holding down
Shift
will not type the text in upper case.Example 1
page.keyboard.sendCharacter('å—¨');
method type
abstract type: ( text: string, options?: Readonly<KeyboardTypeOptions>) => Promise<void>;
Sends a
keydown
,keypress
/input
, andkeyup
event for each character in the text.Parameter text
A text to type into a focused element.
Parameter options
An object of options. Accepts delay which, if specified, is the time to wait between
keydown
andkeyup
in milliseconds. Defaults to 0.Remarks
To press a special key, like
Control
orArrowDown
, use Keyboard.press.Modifier keys DO NOT effect
keyboard.type
. Holding downShift
will not type the text in upper case.Example 1
await page.keyboard.type('Hello'); // Types instantlyawait page.keyboard.type('World', {delay: 100}); // Types slower, like a user
method up
abstract up: (key: KeyInput) => Promise<void>;
Dispatches a
keyup
event.Parameter key
Name of key to release, such as
ArrowLeft
. See KeyInput for a list of all key names.
class Locator
abstract class Locator<T> extends EventEmitter<LocatorEvents> {}
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.
See https://pptr.dev/guides/page-interactions#locators for details.
Modifiers
@public
property timeout
readonly timeout: number;
method click
click: <ElementType extends Element>( this: Locator<ElementType>, options?: Readonly<LocatorClickOptions>) => Promise<void>;
Clicks the located element.
method clone
clone: () => Locator<T>;
Clones the locator.
method fill
fill: <ElementType extends Element>( this: Locator<ElementType>, value: string, options?: Readonly<ActionOptions>) => Promise<void>;
Fills out the input identified by the locator using the provided value. The type of the input is determined at runtime and the appropriate fill-out method is chosen based on the type.
contenteditable
, select, textarea and input elements are supported.
method filter
filter: <S extends T>(predicate: Predicate<T, S>) => Locator<S>;
Creates an expectation that is evaluated against located values.
If the expectations do not match, then the locator will retry.
Modifiers
@public
method hover
hover: <ElementType extends Element>( this: Locator<ElementType>, options?: Readonly<ActionOptions>) => Promise<void>;
Hovers over the located element.
method map
map: <To>(mapper: Mapper<T, To>) => Locator<To>;
Maps the locator using the provided mapper.
Modifiers
@public
method race
static race: <Locators extends readonly unknown[] | []>( locators: Locators) => Locator<AwaitedLocator<Locators[number]>>;
Creates a race between multiple locators trying to locate elements in parallel but ensures that only a single element receives the action.
Modifiers
@public
method scroll
scroll: <ElementType extends Element>( this: Locator<ElementType>, options?: Readonly<LocatorScrollOptions>) => Promise<void>;
Scrolls the located element.
method setEnsureElementIsInTheViewport
setEnsureElementIsInTheViewport: <ElementType extends Element>( this: Locator<ElementType>, value: boolean) => Locator<ElementType>;
Creates a new locator instance by cloning the current locator and specifying whether the locator should scroll the element into viewport if it is not in the viewport already.
method setTimeout
setTimeout: (timeout: number) => Locator<T>;
Creates a new locator instance by cloning the current locator and setting the total timeout for the locator actions.
Pass
0
to disable timeout.
method setVisibility
setVisibility: <NodeType extends Node>( this: Locator<NodeType>, visibility: VisibilityOption) => Locator<NodeType>;
Creates a new locator instance by cloning the current locator with the visibility property changed to the specified value.
method setWaitForEnabled
setWaitForEnabled: <NodeType extends Node>( this: Locator<NodeType>, value: boolean) => Locator<NodeType>;
Creates a new locator instance by cloning the current locator and specifying whether to wait for input elements to become enabled before the action. Applicable to
click
andfill
actions.
method setWaitForStableBoundingBox
setWaitForStableBoundingBox: <ElementType extends Element>( this: Locator<ElementType>, value: boolean) => Locator<ElementType>;
Creates a new locator instance by cloning the current locator and specifying whether the locator has to wait for the element's bounding box to be same between two consecutive animation frames.
method wait
wait: (options?: Readonly<ActionOptions>) => Promise<T>;
Waits for the locator to get the serialized value from the page.
Note this requires the value to be JSON-serializable.
Modifiers
@public
method waitHandle
waitHandle: (options?: Readonly<ActionOptions>) => Promise<HandleFor<T>>;
Waits for the locator to get a handle from the page.
Modifiers
@public
class Mouse
abstract class 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.Example 1
// Using ‘page.mouse’ to trace a 100x100 square.await page.mouse.move(0, 0);await page.mouse.down();await page.mouse.move(0, 100);await page.mouse.move(100, 100);await page.mouse.move(100, 0);await page.mouse.move(0, 0);await page.mouse.up();**Note**: The mouse events trigger synthetic
MouseEvent
s. This means that it does not fully replicate the functionality of what a normal user would be able to do with their mouse.For example, dragging and selecting text is not possible using
page.mouse
. Instead, you can use the `DocumentOrShadowRoot.getSelection()` functionality implemented in the platform.Example 2
For example, if you want to select all content between nodes:
await page.evaluate((from, to) => {const selection = from.getRootNode().getSelection();const range = document.createRange();range.setStartBefore(from);range.setEndAfter(to);selection.removeAllRanges();selection.addRange(range);},fromJSHandle,toJSHandle,);If you then would want to copy-paste your selection, you can use the clipboard api:
// The clipboard api does not allow you to copy, unless the tab is focused.await page.bringToFront();await page.evaluate(() => {// Copy the selected content to the clipboarddocument.execCommand('copy');// Obtain the content of the clipboard as a stringreturn navigator.clipboard.readText();});**Note**: If you want access to the clipboard API, you have to give it permission to do so:
await browser.defaultBrowserContext().overridePermissions('<your origin>', ['clipboard-read','clipboard-write',]);Modifiers
@public
method click
abstract click: ( x: number, y: number, options?: Readonly<MouseClickOptions>) => Promise<void>;
Shortcut for
mouse.move
,mouse.down
andmouse.up
.Parameter x
Horizontal position of the mouse.
Parameter y
Vertical position of the mouse.
Parameter options
Options to configure behavior.
method down
abstract down: (options?: Readonly<MouseOptions>) => Promise<void>;
Presses the mouse.
Parameter options
Options to configure behavior.
method drag
abstract drag: (start: Point, target: Point) => Promise<Protocol.Input.DragData>;
Dispatches a
drag
event.Parameter start
starting point for drag
Parameter target
point to drag to
method dragAndDrop
abstract dragAndDrop: ( start: Point, target: Point, options?: { delay?: number }) => Promise<void>;
Performs a drag, dragenter, dragover, and drop in sequence.
Parameter start
point to drag from
Parameter target
point to drop on
Parameter options
An object of options. Accepts delay which, if specified, is the time to wait between
dragover
anddrop
in milliseconds. Defaults to 0.
method dragEnter
abstract dragEnter: ( target: Point, data: Protocol.Input.DragData) => Promise<void>;
Dispatches a
dragenter
event.Parameter target
point for emitting
dragenter
eventParameter data
drag data containing items and operations mask
method dragOver
abstract dragOver: ( target: Point, data: Protocol.Input.DragData) => Promise<void>;
Dispatches a
dragover
event.Parameter target
point for emitting
dragover
eventParameter data
drag data containing items and operations mask
method drop
abstract drop: (target: Point, data: Protocol.Input.DragData) => Promise<void>;
Performs a dragenter, dragover, and drop in sequence.
Parameter target
point to drop on
Parameter data
drag data containing items and operations mask
method move
abstract move: ( x: number, y: number, options?: Readonly<MouseMoveOptions>) => Promise<void>;
Moves the mouse to the given coordinate.
Parameter x
Horizontal position of the mouse.
Parameter y
Vertical position of the mouse.
Parameter options
Options to configure behavior.
method reset
abstract reset: () => Promise<void>;
Resets the mouse to the default state: No buttons pressed; position at (0,0).
method up
abstract up: (options?: Readonly<MouseOptions>) => Promise<void>;
Releases the mouse.
Parameter options
Options to configure behavior.
method wheel
abstract wheel: (options?: Readonly<MouseWheelOptions>) => Promise<void>;
Dispatches a
mousewheel
event.Parameter options
Optional:
MouseWheelOptions
.Example 1
An example of zooming into an element:
await page.goto('https://mdn.mozillademos.org/en-US/docs/Web/API/Element/wheel_event$samples/Scaling_an_element_via_the_wheel?revision=1587366',);const elem = await page.$('div');const boundingBox = await elem.boundingBox();await page.mouse.move(boundingBox.x + boundingBox.width / 2,boundingBox.y + boundingBox.height / 2,);await page.mouse.wheel({deltaY: -100});
class Page
abstract class Page extends EventEmitter<PageEvents> {}
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.
:::
Example 1
This example creates a page, navigates it to a URL, and then saves a screenshot:
import puppeteer from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();await page.goto('https://example.com');await page.screenshot({path: 'screenshot.png'});await browser.close();})();The Page class extends from Puppeteer's EventEmitter class and will emit various events which are documented in the PageEvent enum.
Example 2
This example logs a message for a single page
load
event:page.once('load', () => console.log('Page loaded!'));To unsubscribe from events use the EventEmitter.off method:
function logRequest(interceptedRequest) {console.log('A request was made:', interceptedRequest.url());}page.on('request', logRequest);// Sometime later...page.off('request', logRequest);Modifiers
@public
property accessibility
readonly accessibility: Accessibility;
See documentation for Accessibility.
property coverage
readonly coverage: Coverage;
See documentation for Coverage.
property keyboard
readonly keyboard: Keyboard;
See documentation for Keyboard.
property mouse
readonly mouse: Mouse;
See documentation for Mouse.
property touchscreen
readonly touchscreen: Touchscreen;
See documentation for Touchscreen.
property tracing
readonly tracing: Tracing;
See documentation for Tracing.
method $
$: <Selector extends string>( selector: Selector) => Promise<ElementHandle<NodeFor<Selector>> | null>;
Finds the first element that matches the selector. If no element matches the selector, the return value resolves to
null
.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Remarks
Shortcut for Page.mainFrame().$(selector).
method $$
$$: <Selector extends string>( selector: Selector, options?: QueryOptions) => Promise<Array<ElementHandle<NodeFor<Selector>>>>;
Finds elements on the page that match the selector. If no elements match the selector, the return value resolves to
[]
.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Remarks
Shortcut for Page.mainFrame().$$(selector).
method $$eval
$$eval: < Selector extends string, Params extends unknown[], Func extends EvaluateFuncWith< ParseSelector<ComplexSelector>[], Params > = EvaluateFuncWith<ParseSelector<ComplexSelector>[], Params>>( selector: Selector, pageFunction: Func | string, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
This method returns all elements matching the selector and passes the resulting array as the first argument to the
pageFunction
.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Parameter pageFunction
the function to be evaluated in the page context. Will be passed an array of matching elements as its first argument.
Parameter args
any additional arguments to pass through to
pageFunction
.Returns
The result of calling
pageFunction
. If it returns an element it is wrapped in an ElementHandle, else the raw value itself is returned.Remarks
If
pageFunction
returns a promise$$eval
will wait for the promise to resolve and then return its value.Example 1
// get the amount of divs on the pageconst divCount = await page.$$eval('div', divs => divs.length);// get the text content of all the `.options` elements:const options = await page.$$eval('div > span.options', options => {return options.map(option => option.textContent);});If you are using TypeScript, you may have to provide an explicit type to the first argument of the
pageFunction
. By default it is typed asElement[]
, but you may need to provide a more specific sub-type:Example 2
await page.$$eval('input', elements => {return elements.map(e => e.value);});The compiler should be able to infer the return type from the
pageFunction
you provide. If it is unable to, you can use the generic type to tell the compiler what return type you expect from$$eval
:Example 3
const allInputValues = await page.$$eval('input', elements =>elements.map(e => e.textContent),);
method $eval
$eval: < Selector extends string, Params extends unknown[], Func extends EvaluateFuncWith< ParseSelector<ComplexSelector>, Params > = EvaluateFuncWith<ParseSelector<ComplexSelector>, Params>>( selector: Selector, pageFunction: Func | string, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
This method finds the first element within the page that matches the selector and passes the result as the first argument to the
pageFunction
.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Parameter pageFunction
the function to be evaluated in the page context. Will be passed the result of the element matching the selector as its first argument.
Parameter args
any additional arguments to pass through to
pageFunction
.Returns
The result of calling
pageFunction
. If it returns an element it is wrapped in an ElementHandle, else the raw value itself is returned.Remarks
If no element is found matching
selector
, the method will throw an error.If
pageFunction
returns a promise$eval
will wait for the promise to resolve and then return its value.Example 1
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', el => el.outerHTML);If you are using TypeScript, you may have to provide an explicit type to the first argument of the
pageFunction
. By default it is typed asElement
, but you may need to provide a more specific sub-type:Example 2
// if you don't provide HTMLInputElement here, TS will error// as `value` is not on `Element`const searchValue = await page.$eval('#search',(el: HTMLInputElement) => el.value,);The compiler should be able to infer the return type from the
pageFunction
you provide. If it is unable to, you can use the generic type to tell the compiler what return type you expect from$eval
:Example 3
// The compiler can infer the return type in this case, but if it can't// or if you want to be more explicit, provide it as the generic type.const searchValue = await page.$eval<string>('#search',(el: HTMLInputElement) => el.value,);
method addScriptTag
addScriptTag: ( options: FrameAddScriptTagOptions) => Promise<ElementHandle<HTMLScriptElement>>;
Adds a
<script>
tag into the page with the desired URL or content.Parameter options
Options for the script.
Returns
An element handle to the injected
<script>
element.Remarks
Shortcut for page.mainFrame().addScriptTag(options).
method addStyleTag
addStyleTag: { (options: Omit<FrameAddStyleTagOptions, 'url'>): Promise< ElementHandle<HTMLStyleElement> >; (options: FrameAddStyleTagOptions): Promise<ElementHandle<HTMLLinkElement>>;};
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).
Returns
An element handle to the injected
<link>
or<style>
element.
method authenticate
abstract authenticate: (credentials: Credentials | null) => Promise<void>;
Provide credentials for
HTTP authentication
.:::note
Request interception will be turned on behind the scenes to implement authentication. This might affect performance.
:::
Remarks
To disable authentication, pass
null
.
method bringToFront
abstract bringToFront: () => Promise<void>;
Brings page to front (activates tab).
method browser
abstract browser: () => Browser;
Get the browser the page belongs to.
method browserContext
abstract browserContext: () => BrowserContext;
Get the browser context that the page belongs to.
method click
click: (selector: string, options?: Readonly<ClickOptions>) => Promise<void>;
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 matchingselector
, the method throws an error.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix. If there are multiple elements satisfying the
selector
, the first will be clickedParameter options
Object
Returns
Promise which resolves when the element matching
selector
is successfully clicked. The Promise will be rejected if there is no element matchingselector
.Remarks
Bear in mind that if
click()
triggers a navigation event and there's a separatepage.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:const [response] = await Promise.all([page.waitForNavigation(waitOptions),page.click(selector, clickOptions),]);Shortcut for page.mainFrame().click(selector[, options]).
method close
abstract close: (options?: { runBeforeUnload?: boolean }) => Promise<void>;
method content
content: () => Promise<string>;
The full HTML contents of the page, including the DOCTYPE.
method cookies
abstract cookies: (...urls: string[]) => Promise<Cookie[]>;
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.
method createCDPSession
abstract createCDPSession: () => Promise<CDPSession>;
Creates a Chrome Devtools Protocol session attached to the page.
method createPDFStream
abstract createPDFStream: ( options?: PDFOptions) => Promise<ReadableStream<Uint8Array>>;
Generates a PDF of the page with the
print
CSS media type.Parameter options
options for generating the PDF.
Remarks
To generate a PDF with the
screen
media type, call `page.emulateMediaType('screen')` before callingpage.pdf()
.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.
method deleteCookie
abstract deleteCookie: (...cookies: DeleteCookiesRequest[]) => Promise<void>;
method emulate
emulate: (device: Device) => Promise<void>;
Emulates a given device's metrics and user agent.
To aid emulation, Puppeteer provides a list of known devices that can be via KnownDevices.
Remarks
This method is a shortcut for calling two methods: Page.setUserAgent and Page.setViewport.
This method will resize the page. A lot of websites don't expect phones to change size, so you should emulate before navigating to the page.
Example 1
import {KnownDevices} from 'puppeteer';const iPhone = KnownDevices['iPhone 15 Pro'];(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();await page.emulate(iPhone);await page.goto('https://www.google.com');// other actions...await browser.close();})();
method emulateCPUThrottling
abstract emulateCPUThrottling: (factor: number | null) => Promise<void>;
Enables CPU throttling to emulate slow CPUs.
Parameter factor
slowdown factor (1 is no throttle, 2 is 2x slowdown, etc).
method emulateIdleState
abstract emulateIdleState: (overrides?: { isUserActive: boolean; isScreenUnlocked: boolean;}) => Promise<void>;
Emulates the idle state. If no arguments set, clears idle state emulation.
Parameter overrides
Mock idle state. If not set, clears idle overrides
Example 1
// set idle emulationawait page.emulateIdleState({isUserActive: true, isScreenUnlocked: false});// do some checks here...// clear idle emulationawait page.emulateIdleState();
method emulateMediaFeatures
abstract emulateMediaFeatures: (features?: MediaFeature[]) => Promise<void>;
Parameter features
<?Array<Object>>
Given an array of media feature objects, emulates CSS media features on the page. Each media feature object must have the following properties:Example 1
await page.emulateMediaFeatures([{name: 'prefers-color-scheme', value: 'dark'},]);await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches,);// → trueawait page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches,);// → falseawait page.emulateMediaFeatures([{name: 'prefers-reduced-motion', value: 'reduce'},]);await page.evaluate(() => matchMedia('(prefers-reduced-motion: reduce)').matches,);// → trueawait page.evaluate(() => matchMedia('(prefers-reduced-motion: no-preference)').matches,);// → falseawait page.emulateMediaFeatures([{name: 'prefers-color-scheme', value: 'dark'},{name: 'prefers-reduced-motion', value: 'reduce'},]);await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches,);// → trueawait page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches,);// → falseawait page.evaluate(() => matchMedia('(prefers-reduced-motion: reduce)').matches,);// → trueawait page.evaluate(() => matchMedia('(prefers-reduced-motion: no-preference)').matches,);// → falseawait page.emulateMediaFeatures([{name: 'color-gamut', value: 'p3'}]);await page.evaluate(() => matchMedia('(color-gamut: srgb)').matches);// → trueawait page.evaluate(() => matchMedia('(color-gamut: p3)').matches);// → trueawait page.evaluate(() => matchMedia('(color-gamut: rec2020)').matches);// → false
method emulateMediaType
abstract emulateMediaType: (type?: string) => Promise<void>;
Parameter type
Changes the CSS media type of the page. The only allowed values are
screen
,print
andnull
. Passingnull
disables CSS media emulation.Example 1
await page.evaluate(() => matchMedia('screen').matches);// → trueawait page.evaluate(() => matchMedia('print').matches);// → falseawait page.emulateMediaType('print');await page.evaluate(() => matchMedia('screen').matches);// → falseawait page.evaluate(() => matchMedia('print').matches);// → trueawait page.emulateMediaType(null);await page.evaluate(() => matchMedia('screen').matches);// → trueawait page.evaluate(() => matchMedia('print').matches);// → false
method emulateNetworkConditions
abstract emulateNetworkConditions: ( networkConditions: NetworkConditions | null) => Promise<void>;
This does not affect WebSockets and WebRTC PeerConnections (see https://crbug.com/563644). To set the page offline, you can use Page.setOfflineMode.
A list of predefined network conditions can be used by importing PredefinedNetworkConditions.
Parameter networkConditions
Passing
null
disables network condition emulation.Example 1
import {PredefinedNetworkConditions} from 'puppeteer';const slow3G = PredefinedNetworkConditions['Slow 3G'];(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();await page.emulateNetworkConditions(slow3G);await page.goto('https://www.google.com');// other actions...await browser.close();})();
method emulateTimezone
abstract emulateTimezone: (timezoneId?: string) => Promise<void>;
Parameter timezoneId
Changes the timezone of the page. See ICU’s metaZones.txt for a list of supported timezone IDs. Passing
null
disables timezone emulation.
method emulateVisionDeficiency
abstract emulateVisionDeficiency: ( type?: Protocol.Emulation.SetEmulatedVisionDeficiencyRequest) => Promise<void>;
Simulates the given vision deficiency on the page.
Parameter type
the type of deficiency to simulate, or
'none'
to reset.Example 1
import puppeteer from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();await page.goto('https://v8.dev/blog/10-years');await page.emulateVisionDeficiency('achromatopsia');await page.screenshot({path: 'achromatopsia.png'});await page.emulateVisionDeficiency('deuteranopia');await page.screenshot({path: 'deuteranopia.png'});await page.emulateVisionDeficiency('blurredVision');await page.screenshot({path: 'blurred-vision.png'});await browser.close();})();
method evaluate
evaluate: < Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>( pageFunction: Func | string, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
Evaluates a function in the page's context and returns the result.
If the function passed to
page.evaluate
returns a Promise, the function will wait for the promise to resolve and return its value.Parameter pageFunction
a function that is run within the page
Parameter args
arguments to be passed to the pageFunction
Returns
the return value of
pageFunction
.Example 1
const result = await frame.evaluate(() => {return Promise.resolve(8 * 7);});console.log(result); // prints "56"You can pass a string instead of a function (although functions are recommended as they are easier to debug and use with TypeScript):
Example 2
const aHandle = await page.evaluate('1 + 2');To get the best TypeScript experience, you should pass in as the generic the type of
pageFunction
:const aHandle = await page.evaluate(() => 2);Example 3
ElementHandle instances (including JSHandles) can be passed as arguments to the
pageFunction
:const bodyHandle = await page.$('body');const html = await page.evaluate(body => body.innerHTML, bodyHandle);await bodyHandle.dispose();
method evaluateHandle
evaluateHandle: < Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>( pageFunction: Func | string, ...args: Params) => Promise<HandleFor<Awaited<ReturnType<Func>>>>;
Parameter pageFunction
a function that is run within the page
Parameter args
arguments to be passed to the pageFunction
Remarks
The only difference between page.evaluate and
page.evaluateHandle
is thatevaluateHandle
will return the value wrapped in an in-page object.If the function passed to
page.evaluateHandle
returns a Promise, the function will wait for the promise to resolve and return its value.You can pass a string instead of a function (although functions are recommended as they are easier to debug and use with TypeScript):
Example 1
const aHandle = await page.evaluateHandle('document');Example 2
JSHandle instances can be passed as arguments to the
pageFunction
:const aHandle = await page.evaluateHandle(() => document.body);const resultHandle = await page.evaluateHandle(body => body.innerHTML,aHandle,);console.log(await resultHandle.jsonValue());await resultHandle.dispose();Most of the time this function returns a JSHandle, but if
pageFunction
returns a reference to an element, you instead get an ElementHandle back:Example 3
const button = await page.evaluateHandle(() =>document.querySelector('button'),);// can call `click` because `button` is an `ElementHandle`await button.click();The TypeScript definitions assume that
evaluateHandle
returns aJSHandle
, but if you know it's going to return anElementHandle
, pass it as the generic argument:const button = await page.evaluateHandle<ElementHandle>(...);
method evaluateOnNewDocument
abstract evaluateOnNewDocument: < Params extends unknown[], Func extends (...args: Params) => unknown = (...args: Params) => unknown>( pageFunction: Func | string, ...args: Params) => Promise<NewDocumentScriptEvaluation>;
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
.Parameter pageFunction
Function to be evaluated in browser context
Parameter args
Arguments to pass to
pageFunction
Example 1
An example of overriding the navigator.languages property before the page loads:
// preload.js// overwrite the `languages` property to use a custom getterObject.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);
method exposeFunction
abstract exposeFunction: ( name: string, pptrFunction: Function | { default: Function }) => Promise<void>;
The method adds a function called
name
on the page'swindow
object. When called, the function executespuppeteerFunction
in node.js and returns aPromise
which resolves to the return value ofpuppeteerFunction
.If the puppeteerFunction returns a
Promise
, it will be awaited.:::note
Functions installed via
page.exposeFunction
survive navigations.:::
Parameter name
Name of the function on the window object
Parameter pptrFunction
Callback function which will be called in Puppeteer's context.
Example 1
An example of adding an
md5
function into the page:import puppeteer from 'puppeteer';import crypto from 'crypto';(async () => {const browser = await puppeteer.launch();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 hashesconst myString = 'PUPPETEER';const myHash = await window.md5(myString);console.log(`md5 of ${myString} is ${myHash}`);});await browser.close();})();Example 2
An example of adding a
window.readfile
function into the page:import puppeteer from 'puppeteer';import fs from 'fs';(async () => {const browser = await puppeteer.launch();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 fileconst content = await window.readfile('/etc/hosts');console.log(content);});await browser.close();})();
method focus
focus: (selector: string) => Promise<void>;
This method fetches an element with
selector
and focuses it. If there's no element matchingselector
, the method throws an error.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix. 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.
Remarks
Shortcut for page.mainFrame().focus(selector).
method frames
abstract frames: () => Frame[];
An array of all frames attached to the page.
method getDefaultTimeout
abstract getDefaultTimeout: () => number;
Maximum time in milliseconds.
method goBack
abstract goBack: (options?: WaitForOptions) => Promise<HTTPResponse | null>;
This method navigate to the previous page in history.
Parameter options
Navigation parameters
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
.
method goForward
abstract goForward: (options?: WaitForOptions) => Promise<HTTPResponse | null>;
This method navigate to the next page in history.
Parameter options
Navigation Parameter
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
.
method goto
goto: (url: string, options?: GoToOptions) => Promise<HTTPResponse | null>;
See documentation for Frame.goto.
method hover
hover: (selector: string) => Promise<void>;
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 matchingselector
, the method throws an error.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix. 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 matchingselector
.Remarks
Shortcut for page.mainFrame().hover(selector).
method isClosed
abstract isClosed: () => boolean;
Indicates that the page has been closed.
Returns
method isDragInterceptionEnabled
abstract isDragInterceptionEnabled: () => boolean;
true
if drag events are being intercepted,false
otherwise.Deprecated
We no longer support intercepting drag payloads. Use the new drag APIs found on ElementHandle to drag (or just use the Page.mouse).
method isJavaScriptEnabled
abstract isJavaScriptEnabled: () => boolean;
true
if the page has JavaScript enabled,false
otherwise.
method isServiceWorkerBypassed
abstract isServiceWorkerBypassed: () => boolean;
true
if the service worker are being bypassed,false
otherwise.
method locator
locator: { <Selector extends string>(selector: Selector): Locator<NodeFor<Selector>>; <Ret>(func: () => Awaitable<Ret>): Locator<Ret>;};
Creates a locator for the provided selector. See Locator for details and supported actions.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Creates a locator for the provided function. See Locator for details and supported actions.
Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
method mainFrame
abstract mainFrame: () => Frame;
The page's main frame.
method metrics
abstract metrics: () => Promise<Metrics>;
Object containing metrics as key/value pairs.
Returns
-
Timestamp
: The timestamp when the metrics sample was taken.-
Documents
: Number of documents in the page.-
Frames
: Number of frames in the page.-
JSEventListeners
: Number of events in the page.-
Nodes
: Number of DOM nodes in the page.-
LayoutCount
: Total number of full or partial page layout.-
RecalcStyleCount
: Total number of page style recalculations.-
LayoutDuration
: Combined durations of all page layouts.-
RecalcStyleDuration
: Combined duration of all page style recalculations.-
ScriptDuration
: Combined duration of JavaScript execution.-
TaskDuration
: Combined duration of all tasks performed by the browser.-
JSHeapUsedSize
: Used JavaScript heap size.-
JSHeapTotalSize
: Total JavaScript heap size.Remarks
All timestamps are in monotonic time: monotonically increasing time in seconds since an arbitrary point in the past.
method pdf
abstract pdf: (options?: PDFOptions) => Promise<Uint8Array>;
See documentation for Page.createPDFStream.
method queryObjects
abstract queryObjects: <Prototype>( prototypeHandle: JSHandle<Prototype>) => Promise<JSHandle<Prototype[]>>;
This method iterates the JavaScript heap and finds all objects with the given prototype.
Parameter prototypeHandle
a handle to the object prototype.
Returns
Promise which resolves to a handle to an array of objects with this prototype.
Example 1
// Create a Map objectawait page.evaluate(() => (window.map = new Map()));// Get a handle to the Map object prototypeconst mapPrototype = await page.evaluateHandle(() => Map.prototype);// Query all map instances into an arrayconst mapInstances = await page.queryObjects(mapPrototype);// Count amount of map objects in heapconst count = await page.evaluate(maps => maps.length, mapInstances);await mapInstances.dispose();await mapPrototype.dispose();
method reload
abstract reload: (options?: WaitForOptions) => Promise<HTTPResponse | null>;
Reloads the page.
Parameter options
Options to configure waiting behavior.
Returns
A promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
method removeExposedFunction
abstract removeExposedFunction: (name: string) => Promise<void>;
The method removes a previously added function via $Page.exposeFunction called
name
from the page'swindow
object.
method removeScriptToEvaluateOnNewDocument
abstract removeScriptToEvaluateOnNewDocument: ( identifier: string) => Promise<void>;
Removes script that injected into page by Page.evaluateOnNewDocument.
Parameter identifier
script identifier
method screencast
screencast: (options?: Readonly<ScreencastOptions>) => Promise<ScreenRecorder>;
Captures a screencast of this page.
Parameter options
Configures screencast behavior.
Remarks
All recordings will be WebM format using the VP9 video codec. The FPS is 30.
You must have ffmpeg installed on your system.
Example 1
Recording a page:
import puppeteer from 'puppeteer';// Launch a browserconst browser = await puppeteer.launch();// Create a new pageconst page = await browser.newPage();// Go to your site.await page.goto("https://www.example.com");// Start recording.const recorder = await page.screencast({path: 'recording.webm'});// Do something.// Stop recording.await recorder.stop();browser.close();Modifiers
@experimental
method screenshot
screenshot: { ( options: Readonly<ScreenshotOptions> & { encoding: 'base64' } ): Promise<string>; (options?: Readonly<ScreenshotOptions>): Promise<Uint8Array>;};
Captures a screenshot of this page.
Parameter options
Configures screenshot behavior.
Remarks
While a screenshot is being taken in a BrowserContext, the following methods will automatically wait for the screenshot to finish to prevent interference with the screenshot process: BrowserContext.newPage, Browser.newPage, Page.close.
Calling Page.bringToFront will not wait for existing screenshot operations.
method select
select: (selector: string, ...values: string[]) => Promise<string[]>;
Triggers a
change
andinput
event once all the provided options have been selected. If there's no<select>
element matchingselector
, the method throws an error.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Parameter values
Values of options to select. If the
<select>
has themultiple
attribute, all values are considered, otherwise only the first one is taken into account.Returns
Remarks
Shortcut for page.mainFrame().select()
Example 1
page.select('select#colors', 'blue'); // single selectionpage.select('select#colors', 'red', 'green', 'blue'); // multiple selections
method setBypassCSP
abstract setBypassCSP: (enabled: boolean) => Promise<void>;
Toggles bypassing page's Content-Security-Policy.
Parameter enabled
sets bypassing of page's Content-Security-Policy.
Remarks
NOTE: CSP bypassing happens at the moment of CSP initialization rather than evaluation. Usually, this means that
page.setBypassCSP
should be called before navigating to the domain.
method setBypassServiceWorker
abstract setBypassServiceWorker: (bypass: boolean) => Promise<void>;
Toggles ignoring of service worker for each request.
Parameter bypass
Whether to bypass service worker and load from network.
method setCacheEnabled
abstract setCacheEnabled: (enabled?: boolean) => Promise<void>;
Toggles ignoring cache for each request based on the enabled state. By default, caching is enabled.
Parameter enabled
sets the
enabled
state of cache
method setContent
setContent: (html: string, options?: WaitForOptions) => Promise<void>;
Set the content of the page.
Parameter html
HTML markup to assign to the page.
Parameter options
Parameters that has some properties.
method setCookie
abstract setCookie: (...cookies: CookieParam[]) => Promise<void>;
Example 1
await page.setCookie(cookieObject1, cookieObject2);
method setDefaultNavigationTimeout
abstract setDefaultNavigationTimeout: (timeout: number) => void;
This setting will change the default maximum navigation time for the following methods and related shortcuts:
Parameter timeout
Maximum navigation time in milliseconds.
method setDefaultTimeout
abstract setDefaultTimeout: (timeout: number) => void;
Parameter timeout
Maximum time in milliseconds.
method setDragInterception
abstract setDragInterception: (enabled: boolean) => Promise<void>;
Parameter enabled
Whether to enable drag interception.
Deprecated
We no longer support intercepting drag payloads. Use the new drag APIs found on ElementHandle to drag (or just use the Page.mouse).
method setExtraHTTPHeaders
abstract setExtraHTTPHeaders: (headers: Record<string, string>) => Promise<void>;
The extra HTTP headers will be sent with every request the page initiates.
:::tip
All HTTP header names are lowercased. (HTTP headers are case-insensitive, so this shouldn’t impact your server code.)
:::
:::note
page.setExtraHTTPHeaders does not guarantee the order of headers in the outgoing requests.
:::
Parameter headers
An object containing additional HTTP headers to be sent with every request. All header values must be strings.
method setGeolocation
abstract setGeolocation: (options: GeolocationOptions) => Promise<void>;
Sets the page's geolocation.
Remarks
Consider using BrowserContext.overridePermissions to grant permissions for the page to read its geolocation.
Example 1
await page.setGeolocation({latitude: 59.95, longitude: 30.31667});
method setJavaScriptEnabled
abstract setJavaScriptEnabled: (enabled: boolean) => Promise<void>;
Parameter enabled
Whether or not to enable JavaScript on the page.
Remarks
NOTE: changing this value won't affect scripts that have already been run. It will take full effect on the next navigation.
method setOfflineMode
abstract setOfflineMode: (enabled: boolean) => Promise<void>;
Sets the network connection to offline.
It does not change the parameters used in Page.emulateNetworkConditions
Parameter enabled
When
true
, enables offline mode for the page.
method setRequestInterception
abstract setRequestInterception: (value: boolean) => Promise<void>;
Activating request interception enables HTTPRequest.abort, HTTPRequest.continue and HTTPRequest.respond methods. This provides the capability to modify network requests that are made by a page.
Once request interception is enabled, every request will stall unless it's continued, responded or aborted; or completed using the browser cache.
See the Request interception guide for more details.
Parameter value
Whether to enable request interception.
Example 1
An example of a naïve request interceptor that aborts all image requests:
import puppeteer from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();await page.setRequestInterception(true);page.on('request', interceptedRequest => {if (interceptedRequest.url().endsWith('.png') ||interceptedRequest.url().endsWith('.jpg'))interceptedRequest.abort();else interceptedRequest.continue();});await page.goto('https://example.com');await browser.close();})();
method setUserAgent
abstract setUserAgent: ( userAgent: string, userAgentMetadata?: Protocol.Emulation.UserAgentMetadata) => Promise<void>;
Parameter userAgent
Specific user agent to use in this page
Parameter userAgentData
Specific user agent client hint data to use in this page
Returns
Promise which resolves when the user agent is set.
method setViewport
abstract setViewport: (viewport: Viewport | null) => Promise<void>;
page.setViewport
will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport before navigating to the page.In the case of multiple pages in a single browser, each page can have its own viewport size. Setting the viewport to
null
resets the viewport to its default value.Parameter viewport
Remarks
NOTE: in certain cases, setting viewport will reload the page in order to set the isMobile or hasTouch properties.
Example 1
const page = await browser.newPage();await page.setViewport({width: 640,height: 480,deviceScaleFactor: 1,});await page.goto('https://example.com');
method tap
tap: (selector: string) => Promise<void>;
This method fetches an element with
selector
, scrolls it into view if needed, and then uses Page.touchscreen to tap in the center of the element. If there's no element matchingselector
, the method throws an error.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix. If there are multiple elements satisfying the selector, the first will be tapped.
Remarks
Shortcut for page.mainFrame().tap(selector).
method target
abstract target: () => Target;
A target this page was created from.
Deprecated
Use Page.createCDPSession directly.
method title
title: () => Promise<string>;
The page's title
Remarks
Shortcut for page.mainFrame().title().
method type
type: ( selector: string, text: string, options?: Readonly<KeyboardTypeOptions>) => Promise<void>;
Sends a
keydown
,keypress/input
, andkeyup
event for each character in the text.To press a special key, like
Control
orArrowDown
, use Keyboard.press.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Parameter text
A text to type into a focused element.
Parameter options
have property
delay
which is the Time to wait between key presses in milliseconds. Defaults to0
.Returns
Example 1
await page.type('#mytextarea', 'Hello');// Types instantlyawait page.type('#mytextarea', 'World', {delay: 100});// Types slower, like a user
method url
url: () => string;
The page's URL.
Remarks
Shortcut for page.mainFrame().url().
method viewport
abstract viewport: () => Viewport | null;
Returns the current page viewport settings without checking the actual page viewport.
This is either the viewport set with the previous Page.setViewport call or the default viewport set via BrowserConnectOptions.defaultViewport.
method waitForDevicePrompt
abstract waitForDevicePrompt: ( options?: WaitTimeoutOptions) => Promise<DeviceRequestPrompt>;
This method is typically coupled with an action that triggers a device request from an api such as WebBluetooth.
:::caution
This must be called before the device request is made. It will not return a currently active device prompt.
:::
Example 1
const [devicePrompt] = Promise.all([page.waitForDevicePrompt(),page.click('#connect-bluetooth'),]);await devicePrompt.select(await devicePrompt.waitForDevice(({name}) => name.includes('My Device')),);
method waitForFileChooser
abstract waitForFileChooser: ( options?: WaitTimeoutOptions) => Promise<FileChooser>;
This method is typically coupled with an action that triggers file choosing.
:::caution
This must be called before the file chooser is launched. It will not return a currently active file chooser.
:::
:::caution
Interception of file dialogs triggered via DOM APIs such as window.showOpenFilePicker is currently not supported.
:::
Remarks
In the "headful" browser, this method results in the native file picker dialog
not showing up
for the user.Example 1
The following example clicks a button that issues a file chooser and then responds with
/tmp/myfile.pdf
as if a user has selected this file.const [fileChooser] = await Promise.all([page.waitForFileChooser(),page.click('#upload-file-button'),// some button that triggers file selection]);await fileChooser.accept(['/tmp/myfile.pdf']);
method waitForFrame
waitForFrame: ( urlOrPredicate: string | ((frame: Frame) => Awaitable<boolean>), options?: WaitTimeoutOptions) => Promise<Frame>;
Waits for a frame matching the given conditions to appear.
Example 1
const frame = await page.waitForFrame(async frame => {return frame.name() === 'Test';});
method waitForFunction
waitForFunction: < Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>( pageFunction: Func | string, options?: FrameWaitForFunctionOptions, ...args: Params) => Promise<HandleFor<Awaited<ReturnType<Func>>>>;
Waits for the provided function,
pageFunction
, to return a truthy value when evaluated in the page's context.Parameter pageFunction
Function to be evaluated in browser context until it returns a truthy value.
Parameter options
Options for configuring waiting behavior.
Example 1
Page.waitForFunction can be used to observe a viewport size change:
import puppeteer from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();const watchDog = page.waitForFunction('window.innerWidth < 100');await page.setViewport({width: 50, height: 50});await watchDog;await browser.close();})();Example 2
Arguments can be passed from Node.js to
pageFunction
:const selector = '.foo';await page.waitForFunction(selector => !!document.querySelector(selector),{},selector,);Example 3
The provided
pageFunction
can be asynchronous:const username = 'github-username';await page.waitForFunction(async username => {const githubResponse = await fetch(`https://api.github.com/users/${username}`,);const githubUser = await githubResponse.json();// show the avatarconst img = document.createElement('img');img.src = githubUser.avatar_url;// wait 3 secondsawait new Promise((resolve, reject) => setTimeout(resolve, 3000));img.remove();},{},username,);
method waitForNavigation
waitForNavigation: (options?: WaitForOptions) => Promise<HTTPResponse | null>;
Waits for the page to navigate to a new URL or to reload. It is useful when you run code that will indirectly cause the page to navigate.
Parameter options
Navigation parameters which might have the following properties:
Returns
A
Promise
which resolves to the main resource response.- In case of multiple redirects, the navigation will resolve with the response of the last redirect. - In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with
null
.Remarks
Usage of the History API to change the URL is considered a navigation.
Example 1
const [response] = await Promise.all([page.waitForNavigation(), // The promise resolves after navigation has finishedpage.click('a.my-link'), // Clicking the link will indirectly cause a navigation]);
method waitForNetworkIdle
waitForNetworkIdle: (options?: WaitForNetworkIdleOptions) => Promise<void>;
Waits for the network to be idle.
Parameter options
Options to configure waiting behavior.
Returns
A promise which resolves once the network is idle.
method waitForRequest
waitForRequest: ( urlOrPredicate: string | AwaitablePredicate<HTTPRequest>, options?: WaitTimeoutOptions) => Promise<HTTPRequest>;
Parameter urlOrPredicate
A URL or predicate to wait for
Parameter options
Optional waiting parameters
Returns
Promise which resolves to the matched request
Remarks
Optional Waiting Parameters have:
-
timeout
: Maximum wait time in milliseconds, defaults to30
seconds, pass0
to disable the timeout. The default value can be changed by using the Page.setDefaultTimeout method.Example 1
const firstRequest = await page.waitForRequest('https://example.com/resource',);const finalRequest = await page.waitForRequest(request => request.url() === 'https://example.com',);return finalRequest.response()?.ok();
method waitForResponse
waitForResponse: ( urlOrPredicate: string | AwaitablePredicate<HTTPResponse>, options?: WaitTimeoutOptions) => Promise<HTTPResponse>;
Parameter urlOrPredicate
A URL or predicate to wait for.
Parameter options
Optional waiting parameters
Returns
Promise which resolves to the matched response.
Remarks
Optional Parameter have:
-
timeout
: Maximum wait time in milliseconds, defaults to30
seconds, pass0
to disable the timeout. The default value can be changed by using the Page.setDefaultTimeout method.Example 1
const firstResponse = await page.waitForResponse('https://example.com/resource',);const finalResponse = await page.waitForResponse(response =>response.url() === 'https://example.com' && response.status() === 200,);const finalResponse = await page.waitForResponse(async response => {return (await response.text()).includes('<html>');});return finalResponse.ok();
method waitForSelector
waitForSelector: <Selector extends string>( selector: Selector, options?: WaitForSelectorOptions) => Promise<ElementHandle<NodeFor<Selector>> | null>;
Wait for the
selector
to appear in page. If at the moment of calling the method theselector
already exists, the method will return immediately. If theselector
doesn't appear after thetimeout
milliseconds of waiting, the function will throw.Parameter selector
selector to query the page for. CSS selectors can be passed as-is and a Puppeteer-specific selector syntax allows quering by text, a11y role and name, and xpath and combining these queries across shadow roots. Alternatively, you can specify the selector type using a prefix.
Parameter options
Optional waiting parameters
Returns
Promise which resolves when element specified by selector string is added to DOM. Resolves to
null
if waiting for hidden:true
and selector is not found in DOM.Remarks
The optional Parameter in Arguments
options
are:-
visible
: A boolean wait for element to be present in DOM and to be visible, i.e. to not havedisplay: none
orvisibility: hidden
CSS properties. Defaults tofalse
.-
hidden
: Wait for element to not be found in the DOM or to be hidden, i.e. havedisplay: none
orvisibility: hidden
CSS properties. Defaults tofalse
.-
timeout
: maximum time to wait for in milliseconds. Defaults to30000
(30 seconds). Pass0
to disable timeout. The default value can be changed by using the Page.setDefaultTimeout method.Example 1
This method works across navigations:
import puppeteer from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();let currentURL;page.waitForSelector('img').then(() => console.log('First URL with image: ' + currentURL));for (currentURL of ['https://example.com','https://google.com','https://bbc.com',]) {await page.goto(currentURL);}await browser.close();})();
method workers
abstract workers: () => WebWorker[];
All of the dedicated WebWorkers associated with the page.
Remarks
This does not contain ServiceWorkers
class ProtocolError
class ProtocolError extends PuppeteerError {}
ProtocolError is emitted whenever there is an error from the protocol.
Modifiers
@public
property code
code: number;
Modifiers
@readonly
@public
property originalMessage
originalMessage: string;
Modifiers
@readonly
@public
class Puppeteer
class 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 extendsPuppeteer
, so has all the methods documented below as well as all that are defined on PuppeteerNode.Modifiers
@public
method clearCustomQueryHandlers
static clearCustomQueryHandlers: () => void;
Unregisters all custom query handlers.
method connect
connect: (options: ConnectOptions) => Promise<Browser>;
This method attaches Puppeteer to an existing browser instance.
Parameter options
Set of configurable options to set on the browser.
Returns
Promise which resolves to browser instance.
Remarks
method customQueryHandlerNames
static customQueryHandlerNames: () => string[];
Gets the names of all custom query handlers.
method registerCustomQueryHandler
static registerCustomQueryHandler: ( name: string, queryHandler: CustomQueryHandler) => void;
Registers a custom query handler.
Parameter name
The name that the custom query handler will be registered under.
Parameter queryHandler
The custom query handler to register.
Remarks
After registration, the handler can be used everywhere where a selector is expected by prepending the selection string with
<name>/
. The name is only allowed to consist of lower- and upper case latin letters.Example 1
import {Puppeteer}, puppeteer from 'puppeteer';Puppeteer.registerCustomQueryHandler('text', { … });const aHandle = await page.$('text/…');Modifiers
@public
method unregisterCustomQueryHandler
static unregisterCustomQueryHandler: (name: string) => void;
Unregisters a custom query handler for a given name.
class PuppeteerError
class PuppeteerError extends Error {}
The base class for all Puppeteer-specific errors
Modifiers
@public
class PuppeteerNode
class PuppeteerNode extends Puppeteer {}
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 ESimport
).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.
Example 1
The following is a typical example of using Puppeteer to drive automation:
import puppeteer from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();await page.goto('https://www.google.com');// other actions...await browser.close();})();Once you have created a
page
you have access to a large API to interact with the page, navigate, or find certain elements in that page. The `page` documentation lists all the available methods.Modifiers
@public
property defaultBrowser
readonly defaultBrowser: SupportedBrowser;
The name of the browser that will be launched by default. For
puppeteer
, this is influenced by your configuration. Otherwise, it'schrome
.
property lastLaunchedBrowser
readonly lastLaunchedBrowser: SupportedBrowser;
The name of the browser that was last launched.
property product
readonly product: string;
Returns
The name of the browser that is under automation.
Deprecated
Do not use as this field as it does not take into account multiple browsers of different types. Use defaultBrowser or lastLaunchedBrowser.
method connect
connect: (options: ConnectOptions) => Promise<Browser>;
This method attaches Puppeteer to an existing browser instance.
Parameter options
Set of configurable options to set on the browser.
Returns
Promise which resolves to browser instance.
method defaultArgs
defaultArgs: (options?: BrowserLaunchArgumentOptions) => string[];
Parameter options
Set of configurable options to set on the browser.
Returns
The default flags that Chromium will be launched with.
method executablePath
executablePath: (channel?: ChromeReleaseChannel) => string;
The default executable path.
method launch
launch: (options?: PuppeteerLaunchOptions) => Promise<Browser>;
Launches a browser instance with given arguments and options when specified.
When using with
puppeteer-core
, options.executablePath or options.channel must be provided.Parameter options
Options to configure launching behavior.
Remarks
Puppeteer can also be used to control the Chrome browser, but it works best with the version of Chrome for Testing downloaded by default. There is no guarantee it will work with any other version. If Google Chrome (rather than Chrome for Testing) is preferred, a Chrome Canary or Dev Channel build is suggested. See this article for a description of the differences between Chromium and Chrome. This article describes some differences for Linux users. See this doc for the description of Chrome for Testing.
Example 1
You can use options.ignoreDefaultArgs to filter out
--mute-audio
from default arguments:const browser = await puppeteer.launch({ignoreDefaultArgs: ['--mute-audio'],});
method trimCache
trimCache: () => Promise<void>;
Removes all non-current Firefox and Chrome binaries in the cache directory identified by the provided Puppeteer configuration. The current browser version is determined by resolving PUPPETEER_REVISIONS from Puppeteer unless
configuration.browserRevision
is provided.Remarks
Note that the method does not check if any other Puppeteer versions installed on the host that use the same cache directory require the non-current binaries.
Modifiers
@public
class ScreenRecorder
class ScreenRecorder extends PassThrough {}
Modifiers
@public
method stop
stop: () => Promise<void>;
Stops the recorder.
Modifiers
@public
class SecurityDetails
class SecurityDetails {}
The SecurityDetails class represents the security details of a response that was received over a secure connection.
Modifiers
@public
method issuer
issuer: () => string;
The name of the issuer of the certificate.
method protocol
protocol: () => string;
The security protocol being used, e.g. "TLS 1.2".
method subjectAlternativeNames
subjectAlternativeNames: () => string[];
The list of subject alternative names (SANs) of the certificate.
method subjectName
subjectName: () => string;
The name of the subject to which the certificate was issued.
method validFrom
validFrom: () => number;
Unix timestamp marking the start of the certificate's validity.
method validTo
validTo: () => number;
Unix timestamp marking the end of the certificate's validity.
class Target
abstract 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.
Modifiers
@public
method asPage
abstract asPage: () => Promise<Page>;
Forcefully creates a page for a target of any type. It is useful if you want to handle a CDP target of type
other
as a page. If you deal with a regular page target, use Target.page.
method browser
abstract browser: () => Browser;
Get the browser the target belongs to.
method browserContext
abstract browserContext: () => BrowserContext;
Get the browser context the target belongs to.
method createCDPSession
abstract createCDPSession: () => Promise<CDPSession>;
Creates a Chrome Devtools Protocol session attached to the target.
method opener
abstract opener: () => Target | undefined;
Get the target that opened this target. Top-level targets return
null
.
method page
page: () => Promise<Page | null>;
If the target is not of type
"page"
,"webview"
or"background_page"
, returnsnull
.
method type
abstract type: () => TargetType;
Identifies what kind of target this is.
Remarks
See docs for more info about background pages.
method url
abstract url: () => string;
method worker
worker: () => Promise<WebWorker | null>;
If the target is not of type
"service_worker"
or"shared_worker"
, returnsnull
.
class TimeoutError
class TimeoutError extends PuppeteerError {}
TimeoutError is emitted whenever certain operations are terminated due to timeout.
Remarks
Example operations are page.waitForSelector or puppeteer.launch.
Modifiers
@public
class TouchError
class TouchError extends PuppeteerError {}
TouchError is thrown when an attempt is made to move or end a touch that does not exist.
Modifiers
@public
class Touchscreen
abstract class Touchscreen {}
The Touchscreen class exposes touchscreen events.
Modifiers
@public
method tap
tap: (x: number, y: number) => Promise<void>;
Dispatches a
touchstart
andtouchend
event.Parameter x
Horizontal position of the tap.
Parameter y
Vertical position of the tap.
method touchEnd
touchEnd: () => Promise<void>;
Dispatches a
touchend
event on the first touch that is active.
method touchMove
touchMove: (x: number, y: number) => Promise<void>;
Dispatches a
touchMove
event on the first touch that is active.Parameter x
Horizontal position of the move.
Parameter y
Vertical position of the move.
Remarks
Not every
touchMove
call results in atouchmove
event being emitted, depending on the browser's optimizations. For example, Chrome throttles touch move events.
method touchStart
abstract touchStart: (x: number, y: number) => Promise<TouchHandle>;
Dispatches a
touchstart
event.Parameter x
Horizontal position of the tap.
Parameter y
Vertical position of the tap.
Returns
A handle for the touch that was started.
class Tracing
class Tracing {}
The Tracing class exposes the tracing audit interface.
Remarks
You can use
tracing.start
andtracing.stop
to create a trace file which can be opened in Chrome DevTools or timeline viewer.Example 1
await page.tracing.start({path: 'trace.json'});await page.goto('https://www.google.com');await page.tracing.stop();Modifiers
@public
method start
start: (options?: TracingOptions) => Promise<void>;
Starts a trace for the current page.
Parameter options
Optional
TracingOptions
.Remarks
Only one trace can be active at a time per browser.
method stop
stop: () => Promise<Uint8Array | undefined>;
Stops a trace started with the
start
method.Returns
Promise which resolves to buffer with trace data.
class UnsupportedOperation
class UnsupportedOperation extends PuppeteerError {}
Puppeteer will throw this error if a method is not supported by the currently used protocol
Modifiers
@public
class WebWorker
abstract class WebWorker extends EventEmitter<Record<EventType, unknown>> {}
This class represents a WebWorker.
Remarks
The events
workercreated
andworkerdestroyed
are emitted on the page object to signal the worker lifecycle.Example 1
page.on('workercreated', worker =>console.log('Worker created: ' + worker.url()),);page.on('workerdestroyed', worker =>console.log('Worker destroyed: ' + worker.url()),);console.log('Current workers:');for (const worker of page.workers()) {console.log(' ' + worker.url());}Modifiers
@public
property client
readonly client: CDPSession;
The CDP session client the WebWorker belongs to.
method close
close: () => Promise<void>;
method evaluate
evaluate: < Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>( func: Func | string, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
Evaluates a given function in the worker.
Parameter func
Function to be evaluated.
Parameter args
Arguments to pass into
func
.Returns
The result of
func
.Remarks
If the given function returns a promise, evaluate will wait for the promise to resolve.
As a rule of thumb, if the return value of the given function is more complicated than a JSON object (e.g. most classes), then evaluate will _likely_ return some truncated value (or
{}
). This is because we are not returning the actual return value, but a deserialized version as a result of transferring the return value through a protocol to Puppeteer.In general, you should use evaluateHandle if evaluate cannot serialize the return value properly or you need a mutable handle to the return object.
method evaluateHandle
evaluateHandle: < Params extends unknown[], Func extends EvaluateFunc<Params> = EvaluateFunc<Params>>( func: Func | string, ...args: Params) => Promise<HandleFor<Awaited<ReturnType<Func>>>>;
Evaluates a given function in the worker.
Parameter func
Function to be evaluated.
Parameter args
Arguments to pass into
func
.Returns
A handle to the return value of
func
.Remarks
If the given function returns a promise, evaluate will wait for the promise to resolve.
In general, you should use evaluateHandle if evaluate cannot serialize the return value properly or you need a mutable handle to the return object.
method url
url: () => string;
The URL of this web worker.
interface ActionOptions
interface ActionOptions {}
Modifiers
@public
property signal
signal?: AbortSignal;
A signal to abort the locator action.
interface AutofillData
interface AutofillData {}
Modifiers
@public
property creditCard
creditCard: { number: string; name: string; expiryMonth: string; expiryYear: string; cvc: string;};
interface BoundingBox
interface BoundingBox extends Point {}
Modifiers
@public
interface BoxModel
interface BoxModel {}
Modifiers
@public
interface BrowserConnectOptions
interface BrowserConnectOptions {}
Generic browser options that can be passed when launching any browser or when connecting to an existing browser instance.
Modifiers
@public
property acceptInsecureCerts
acceptInsecureCerts?: boolean;
Whether to ignore HTTPS errors during navigation.
property defaultViewport
defaultViewport?: Viewport | null;
Sets the viewport for each page.
property protocol
protocol?: ProtocolType;
Modifiers
@public
property protocolTimeout
protocolTimeout?: number;
Timeout setting for individual protocol (CDP) calls.
property slowMo
slowMo?: number;
Slows down Puppeteer operations by the specified amount of milliseconds to aid debugging.
property targetFilter
targetFilter?: TargetFilterCallback;
Callback to decide if Puppeteer should connect to a given target or not.
interface BrowserContextEvents
interface BrowserContextEvents extends Record<EventType, unknown> {}
Modifiers
@public
property [BrowserContextEvent.TargetChanged]
[BrowserContextEvent.TargetChanged]: Target;
property [BrowserContextEvent.TargetCreated]
[BrowserContextEvent.TargetCreated]: Target;
property [BrowserContextEvent.TargetDestroyed]
[BrowserContextEvent.TargetDestroyed]: Target;
interface BrowserContextOptions
interface BrowserContextOptions {}
Modifiers
@public
property proxyBypassList
proxyBypassList?: string[];
Bypass the proxy for the given list of hosts.
property proxyServer
proxyServer?: string;
Proxy server with optional port to use for all requests. Username and password can be set in
Page.authenticate
.
interface BrowserEvents
interface BrowserEvents extends Record<EventType, unknown> {}
Modifiers
@public
property [BrowserEvent.Disconnected]
[BrowserEvent.Disconnected]: undefined;
property [BrowserEvent.TargetChanged]
[BrowserEvent.TargetChanged]: Target;
property [BrowserEvent.TargetCreated]
[BrowserEvent.TargetCreated]: Target;
property [BrowserEvent.TargetDestroyed]
[BrowserEvent.TargetDestroyed]: Target;
interface BrowserLaunchArgumentOptions
interface BrowserLaunchArgumentOptions {}
Launcher options that only apply to Chrome.
Modifiers
@public
property args
args?: string[];
Additional command line arguments to pass to the browser instance.
property debuggingPort
debuggingPort?: number;
Specify the debugging port number to use
property devtools
devtools?: boolean;
Whether to auto-open a DevTools panel for each tab. If this is set to
true
, thenheadless
will be forced tofalse
.
property headless
headless?: boolean | 'shell';
Whether to run the browser in headless mode.
Remarks
-
true
launches the browser in the new headless mode.-
'shell'
launches shell known as the old headless mode.
property userDataDir
userDataDir?: string;
Path to a user data directory. see the Chromium docs for more info.
interface CDPSessionEvents
interface CDPSessionEvents extends CDPEvents, Record<EventType, unknown> {}
Modifiers
@public
property [CDPSessionEvent.SessionAttached]
[CDPSessionEvent.SessionAttached]: CDPSession;
property [CDPSessionEvent.SessionDetached]
[CDPSessionEvent.SessionDetached]: CDPSession;
interface ChromeHeadlessShellSettings
interface ChromeHeadlessShellSettings {}
Modifiers
@public
property downloadBaseUrl
downloadBaseUrl?: string;
Specifies the URL prefix that is used to download the browser.
Can be overridden by
PUPPETEER_CHROME_HEADLESS_SHELL_DOWNLOAD_BASE_URL
.Remarks
This must include the protocol and may even need a path prefix. This must **not** include a trailing slash similar to the default.
property skipDownload
skipDownload?: boolean;
Tells Puppeteer to not download the browser during installation.
Can be overridden by
PUPPETEER_CHROME_HEADLESS_SHELL_SKIP_DOWNLOAD
orPUPPETEER_SKIP_CHROME_HEADLESS_SHELL_DOWNLOAD
.
property version
version?: string;
Specifies a certain version of the browser you'd like Puppeteer to use.
Can be overridden by
PUPPETEER_CHROME_HEADLESS_SHELL_VERSION
.See puppeteer.launch on how executable path is inferred.
Example 1
119.0.6045.105
interface ChromeSettings
interface ChromeSettings {}
Modifiers
@public
property downloadBaseUrl
downloadBaseUrl?: string;
Specifies the URL prefix that is used to download the browser.
Can be overridden by
PUPPETEER_CHROME_DOWNLOAD_BASE_URL
.Remarks
This must include the protocol and may even need a path prefix. This must **not** include a trailing slash similar to the default.
property skipDownload
skipDownload?: boolean;
Tells Puppeteer to not download the browser during installation.
Can be overridden by
PUPPETEER_CHROME_SKIP_DOWNLOAD
.
property version
version?: string;
Specifies a certain version of the browser you'd like Puppeteer to use.
Can be overridden by
PUPPETEER_CHROME_VERSION
orPUPPETEER_SKIP_CHROME_DOWNLOAD
.See puppeteer.launch on how executable path is inferred.
Example 1
119.0.6045.105
interface ClickOptions
interface ClickOptions extends MouseClickOptions {}
Modifiers
@public
property offset
offset?: Offset;
Offset for the clickable point relative to the top-left corner of the border box.
interface CommandOptions
interface CommandOptions {}
Modifiers
@public
property timeout
timeout: number;
interface CommonEventEmitter
interface CommonEventEmitter<Events extends Record<EventType, unknown>> {}
Modifiers
@public
method emit
emit: <Key extends keyof Events>(type: Key, event: Events[Key]) => boolean;
method listenerCount
listenerCount: (event: keyof Events) => number;
method off
off: <Key extends keyof Events>( type: Key, handler?: Handler<Events[Key]>) => this;
method on
on: <Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>) => this;
method once
once: <Key extends keyof Events>( type: Key, handler: Handler<Events[Key]>) => this;
method removeAllListeners
removeAllListeners: (event?: keyof Events) => this;
interface Configuration
interface Configuration {}
Defines options to configure Puppeteer's behavior during installation and runtime.
See individual properties for more information.
Modifiers
@public
property ['chrome-headless-shell']
['chrome-headless-shell']?: ChromeHeadlessShellSettings;
property cacheDirectory
cacheDirectory?: string;
Defines the directory to be used by Puppeteer for caching.
Can be overridden by
PUPPETEER_CACHE_DIR
.
property chrome
chrome?: ChromeSettings;
property defaultBrowser
defaultBrowser?: SupportedBrowser;
Specifies which browser you'd like Puppeteer to use.
Can be overridden by
PUPPETEER_BROWSER
.
property executablePath
executablePath?: string;
Specifies an executable path to be used in puppeteer.launch.
Can be overridden by
PUPPETEER_EXECUTABLE_PATH
.
property experiments
experiments?: ExperimentsConfiguration;
Defines experimental options for Puppeteer.
property firefox
firefox?: FirefoxSettings;
property logLevel
logLevel?: 'silent' | 'error' | 'warn';
Tells Puppeteer to log at the given level.
property skipDownload
skipDownload?: boolean;
Tells Puppeteer to not download during installation.
Can be overridden by
PUPPETEER_SKIP_DOWNLOAD
.
property temporaryDirectory
temporaryDirectory?: string;
Defines the directory to be used by Puppeteer for creating temporary files.
Can be overridden by
PUPPETEER_TMP_DIR
.
interface ConnectionTransport
interface ConnectionTransport {}
Modifiers
@public
interface ConnectOptions
interface ConnectOptions extends BrowserConnectOptions {}
Modifiers
@public
property browserURL
browserURL?: string;
property browserWSEndpoint
browserWSEndpoint?: string;
property capabilities
capabilities?: SupportedWebDriverCapabilities;
WebDriver BiDi capabilities passed to BiDi
session.new
.Remarks
Only works for
protocol="webDriverBiDi"
and Puppeteer.connect.
property headers
headers?: Record<string, string>;
Headers to use for the web socket connection.
Remarks
Only works in the Node.js environment.
property transport
transport?: ConnectionTransport;
interface ConsoleMessageLocation
interface ConsoleMessageLocation {}
Modifiers
@public
property columnNumber
columnNumber?: number;
0-based column number in the resource if known or
undefined
otherwise.
property lineNumber
lineNumber?: number;
0-based line number in the resource if known or
undefined
otherwise.
property url
url?: string;
URL of the resource if known or
undefined
otherwise.
interface ContinueRequestOverrides
interface ContinueRequestOverrides {}
Modifiers
@public
interface Cookie
interface Cookie {}
Represents a cookie object.
Modifiers
@public
property domain
domain: string;
Cookie domain.
property expires
expires: number;
Cookie expiration date as the number of seconds since the UNIX epoch. Set to
-1
for session cookies
property httpOnly
httpOnly: boolean;
True if cookie is http-only.
property name
name: string;
Cookie name.
property partitionKey
partitionKey?: string;
Cookie partition key. In Chrome, it is the top-level site the partitioned cookie is available in. In Firefox, it matches the source origin (https://w3c.github.io/webdriver-bidi/#type-storage-PartitionKey).
property partitionKeyOpaque
partitionKeyOpaque?: boolean;
True if cookie partition key is opaque. Supported only in Chrome.
property path
path: string;
Cookie path.
property priority
priority?: CookiePriority;
Cookie Priority. Supported only in Chrome.
property sameParty
sameParty?: boolean;
True if cookie is SameParty. Supported only in Chrome.
property sameSite
sameSite?: CookieSameSite;
Cookie SameSite type.
property secure
secure: boolean;
True if cookie is secure.
property session
session: boolean;
True in case of session cookie.
property size
size: number;
Cookie size.
property sourceScheme
sourceScheme?: CookieSourceScheme;
Cookie source scheme type. Supported only in Chrome.
property value
value: string;
Cookie value.
interface CookieParam
interface CookieParam {}
Cookie parameter object
Modifiers
@public
property domain
domain?: string;
Cookie domain.
property expires
expires?: number;
Cookie expiration date, session cookie if not set
property httpOnly
httpOnly?: boolean;
True if cookie is http-only.
property name
name: string;
Cookie name.
property partitionKey
partitionKey?: string;
Cookie partition key. In Chrome, it matches the top-level site the partitioned cookie is available in. In Firefox, it matches the source origin (https://w3c.github.io/webdriver-bidi/#type-storage-PartitionKey).
property path
path?: string;
Cookie path.
property priority
priority?: CookiePriority;
Cookie Priority. Supported only in Chrome.
property sameParty
sameParty?: boolean;
True if cookie is SameParty. Supported only in Chrome.
property sameSite
sameSite?: CookieSameSite;
Cookie SameSite type.
property secure
secure?: boolean;
True if cookie is secure.
property sourceScheme
sourceScheme?: CookieSourceScheme;
Cookie source scheme type. Supported only in Chrome.
property url
url?: string;
The request-URI to associate with the setting of the cookie. This value can affect the default domain, path, and source scheme values of the created cookie.
property value
value: string;
Cookie value.
interface CoverageEntry
interface CoverageEntry {}
The CoverageEntry class represents one entry of the coverage report.
Modifiers
@public
interface Credentials
interface Credentials {}
Modifiers
@public
interface CSSCoverageOptions
interface CSSCoverageOptions {}
Set of configurable options for CSS coverage.
Modifiers
@public
property resetOnNavigation
resetOnNavigation?: boolean;
Whether to reset coverage on every navigation.
interface CustomQueryHandler
interface CustomQueryHandler {}
Modifiers
@public
interface DebugInfo
interface DebugInfo {}
Modifiers
@public
@experimental
property pendingProtocolErrors
pendingProtocolErrors: Error[];
interface DeleteCookiesRequest
interface DeleteCookiesRequest {}
Modifiers
@public
property domain
domain?: string;
If specified, deletes only cookies with the exact domain.
property name
name: string;
Name of the cookies to remove.
property partitionKey
partitionKey?: string;
If specified, deletes cookies in the given partition key. In Chrome, partitionKey matches the top-level site the partitioned cookie is available in. In Firefox, it matches the source origin (https://w3c.github.io/webdriver-bidi/#type-storage-PartitionKey).
property path
path?: string;
If specified, deletes only cookies with the exact path.
property url
url?: string;
If specified, deletes all the cookies with the given name where domain and path match provided URL. Otherwise, deletes only cookies related to the current page's domain.
interface Device
interface Device {}
Modifiers
@public
interface ElementScreenshotOptions
interface ElementScreenshotOptions extends ScreenshotOptions {}
Modifiers
@public
property scrollIntoView
scrollIntoView?: boolean;
interface FirefoxSettings
interface FirefoxSettings {}
Modifiers
@public
property downloadBaseUrl
downloadBaseUrl?: string;
Specifies the URL prefix that is used to download the browser.
Can be overridden by
PUPPETEER_FIREFOX_DOWNLOAD_BASE_URL
.Remarks
This must include the protocol and may even need a path prefix. This must **not** include a trailing slash similar to the default.
property skipDownload
skipDownload?: boolean;
Tells Puppeteer to not download the browser during installation.
Can be overridden by
PUPPETEER_FIREFOX_SKIP_DOWNLOAD
.
property version
version?: string;
Specifies a certain version of the browser you'd like Puppeteer to use.
Can be overridden by
PUPPETEER_FIREFOX_VERSION
.See puppeteer.launch on how executable path is inferred.
Example 1
stable_129.0
interface FrameAddScriptTagOptions
interface FrameAddScriptTagOptions {}
Modifiers
@public
property content
content?: string;
JavaScript to be injected into the frame.
property id
id?: string;
Sets the
id
of the script.
property path
path?: string;
Path to a JavaScript file to be injected into the frame.
Remarks
If
path
is a relative path, it is resolved relative to the current working directory (process.cwd()
in Node.js).
property type
type?: string;
Sets the
type
of the script. Usemodule
in order to load an ES2015 module.
property url
url?: string;
URL of the script to be added.
interface FrameAddStyleTagOptions
interface FrameAddStyleTagOptions {}
Modifiers
@public
property content
content?: string;
Raw CSS content to be injected into the frame.
property path
path?: string;
The path to a CSS file to be injected into the frame.
Remarks
If
path
is a relative path, it is resolved relative to the current working directory (process.cwd()
in Node.js).
property url
url?: string;
the URL of the CSS file to be added.
interface FrameEvents
interface FrameEvents extends Record<EventType, unknown> {}
Modifiers
@public
interface FrameWaitForFunctionOptions
interface FrameWaitForFunctionOptions {}
Modifiers
@public
property polling
polling?: 'raf' | 'mutation' | number;
An interval at which the
pageFunction
is executed, defaults toraf
. Ifpolling
is a number, then it is treated as an interval in milliseconds at which the function would be executed. Ifpolling
is a string, then it can be one of the following values:-
raf
- to constantly executepageFunction
inrequestAnimationFrame
callback. This is the tightest polling mode which is suitable to observe styling changes.-
mutation
- to executepageFunction
on every DOM mutation.
property signal
signal?: AbortSignal;
A signal object that allows you to cancel a waitForFunction call.
property timeout
timeout?: number;
Maximum time to wait in milliseconds. Defaults to
30000
(30 seconds). Pass0
to disable the timeout. Puppeteer's default timeout can be changed using Page.setDefaultTimeout.
interface GeolocationOptions
interface GeolocationOptions {}
Modifiers
@public
interface GoToOptions
interface GoToOptions extends WaitForOptions {}
Modifiers
@public
property referer
referer?: string;
If provided, it will take preference over the referer header value set by page.setExtraHTTPHeaders().
property referrerPolicy
referrerPolicy?: string;
If provided, it will take preference over the referer-policy header value set by page.setExtraHTTPHeaders().
interface InterceptResolutionState
interface InterceptResolutionState {}
Modifiers
@public
interface InternalNetworkConditions
interface InternalNetworkConditions extends NetworkConditions {}
Modifiers
@public
property offline
offline: boolean;
interface JSCoverageEntry
interface JSCoverageEntry extends CoverageEntry {}
The CoverageEntry class for JavaScript
Modifiers
@public
property rawScriptCoverage
rawScriptCoverage?: Protocol.Profiler.ScriptCoverage;
Raw V8 script coverage entry.
interface JSCoverageOptions
interface JSCoverageOptions {}
Set of configurable options for JS coverage.
Modifiers
@public
property includeRawScriptCoverage
includeRawScriptCoverage?: boolean;
Whether the result includes raw V8 script coverage entries.
property reportAnonymousScripts
reportAnonymousScripts?: boolean;
Whether anonymous scripts generated by the page should be reported.
property resetOnNavigation
resetOnNavigation?: boolean;
Whether to reset coverage on every navigation.
property useBlockCoverage
useBlockCoverage?: boolean;
Whether to collect coverage information at the block level. If true, coverage will be collected at the block level (this is the default). If false, coverage will be collected at the function level.
interface KeyboardTypeOptions
interface KeyboardTypeOptions {}
Modifiers
@public
property delay
delay?: number;
interface KeyDownOptions
interface KeyDownOptions {}
Modifiers
@public
interface LaunchOptions
interface LaunchOptions {}
Generic launch options that can be passed when launching any browser.
Modifiers
@public
property browser
browser?: SupportedBrowser;
Which browser to launch.
property channel
channel?: ChromeReleaseChannel;
Chrome Release Channel
property dumpio
dumpio?: boolean;
If true, pipes the browser process stdout and stderr to
process.stdout
andprocess.stderr
.
property env
env?: Record<string, string | undefined>;
Specify environment variables that will be visible to the browser.
property executablePath
executablePath?: string;
Path to a browser executable to use instead of the bundled browser. Note that Puppeteer is only guaranteed to work with the bundled browser, so use this setting at your own risk.
Remarks
When using this is recommended to set the
browser
property as well as Puppeteer will default tochrome
by default.
property extraPrefsFirefox
extraPrefsFirefox?: Record<string, unknown>;
Additional preferences that can be passed when launching with Firefox.
property handleSIGHUP
handleSIGHUP?: boolean;
Close the browser process on
SIGHUP
.
property handleSIGINT
handleSIGINT?: boolean;
Close the browser process on
Ctrl+C
.
property handleSIGTERM
handleSIGTERM?: boolean;
Close the browser process on
SIGTERM
.
property ignoreDefaultArgs
ignoreDefaultArgs?: boolean | string[];
If
true
, do not usepuppeteer.defaultArgs()
when creating a browser. If an array is provided, these args will be filtered out. Use this with care - you probably want the default arguments Puppeteer uses.
property pipe
pipe?: boolean;
Connect to a browser over a pipe instead of a WebSocket. Only supported with Chrome.
property timeout
timeout?: number;
Maximum time in milliseconds to wait for the browser to start. Pass
0
to disable the timeout.
property waitForInitialPage
waitForInitialPage?: boolean;
Whether to wait for the initial page to be ready. Useful when a user explicitly disables that (e.g.
--no-startup-window
for Chrome).
interface LocatorEvents
interface LocatorEvents extends Record<EventType, unknown> {}
Modifiers
@public
property [LocatorEvent.Action]
[LocatorEvent.Action]: undefined;
interface LocatorScrollOptions
interface LocatorScrollOptions extends ActionOptions {}
Modifiers
@public
property scrollLeft
scrollLeft?: number;
property scrollTop
scrollTop?: number;
interface MediaFeature
interface MediaFeature {}
A media feature to emulate.
Modifiers
@public
interface Metrics
interface Metrics {}
Modifiers
@public
property Documents
Documents?: number;
property Frames
Frames?: number;
property JSEventListeners
JSEventListeners?: number;
property JSHeapTotalSize
JSHeapTotalSize?: number;
property JSHeapUsedSize
JSHeapUsedSize?: number;
property LayoutCount
LayoutCount?: number;
property LayoutDuration
LayoutDuration?: number;
property Nodes
Nodes?: number;
property RecalcStyleCount
RecalcStyleCount?: number;
property RecalcStyleDuration
RecalcStyleDuration?: number;
property ScriptDuration
ScriptDuration?: number;
property TaskDuration
TaskDuration?: number;
property Timestamp
Timestamp?: number;
interface MouseClickOptions
interface MouseClickOptions extends MouseOptions {}
Modifiers
@public
interface MouseMoveOptions
interface MouseMoveOptions {}
Modifiers
@public
property steps
steps?: number;
Determines the number of movements to make from the current mouse position to the new one.
interface MouseOptions
interface MouseOptions {}
Modifiers
@public
property button
button?: MouseButton;
Determines which button will be pressed.
property clickCount
clickCount?: number;
Determines the click count for the mouse event. This does not perform multiple clicks.
Deprecated
interface MouseWheelOptions
interface MouseWheelOptions {}
Modifiers
@public
interface Moveable
interface Moveable {}
Modifiers
@public
method move
move: () => this;
Moves the resource when 'using'.
interface NetworkConditions
interface NetworkConditions {}
Modifiers
@public
interface NewDocumentScriptEvaluation
interface NewDocumentScriptEvaluation {}
Modifiers
@public
property identifier
identifier: string;
interface Offset
interface Offset {}
Modifiers
@public
interface PageEvents
interface PageEvents extends Record<EventType, unknown> {}
Denotes the objects received by callback functions for page events.
See PageEvent for more detail on the events and when they are emitted.
Modifiers
@public
property [PageEvent.Close]
[PageEvent.Close]: undefined;
property [PageEvent.Console]
[PageEvent.Console]: ConsoleMessage;
property [PageEvent.Dialog]
[PageEvent.Dialog]: Dialog;
property [PageEvent.DOMContentLoaded]
[PageEvent.DOMContentLoaded]: undefined;
property [PageEvent.Error]
[PageEvent.Error]: Error;
property [PageEvent.FrameAttached]
[PageEvent.FrameAttached]: Frame;
property [PageEvent.FrameDetached]
[PageEvent.FrameDetached]: Frame;
property [PageEvent.FrameNavigated]
[PageEvent.FrameNavigated]: Frame;
property [PageEvent.Load]
[PageEvent.Load]: undefined;
property [PageEvent.Metrics]
[PageEvent.Metrics]: { title: string; metrics: Metrics;};
property [PageEvent.PageError]
[PageEvent.PageError]: Error;
property [PageEvent.Popup]
[PageEvent.Popup]: Page | null;
property [PageEvent.Request]
[PageEvent.Request]: HTTPRequest;
property [PageEvent.RequestFailed]
[PageEvent.RequestFailed]: HTTPRequest;
property [PageEvent.RequestFinished]
[PageEvent.RequestFinished]: HTTPRequest;
property [PageEvent.RequestServedFromCache]
[PageEvent.RequestServedFromCache]: HTTPRequest;
property [PageEvent.Response]
[PageEvent.Response]: HTTPResponse;
property [PageEvent.WorkerCreated]
[PageEvent.WorkerCreated]: WebWorker;
property [PageEvent.WorkerDestroyed]
[PageEvent.WorkerDestroyed]: WebWorker;
interface PDFMargin
interface PDFMargin {}
Modifiers
@public
interface PDFOptions
interface PDFOptions {}
Valid options to configure PDF generation via Page.pdf.
Modifiers
@public
property displayHeaderFooter
displayHeaderFooter?: boolean;
Whether to show the header and footer.
property footerTemplate
footerTemplate?: string;
HTML template for the print footer. Has the same constraints and support for special classes as PDFOptions.headerTemplate.
property format
format?: PaperFormat;
Remarks
If set, this takes priority over the
width
andheight
options.
property headerTemplate
headerTemplate?: string;
HTML template for the print header. Should be valid HTML with the following classes used to inject values into them:
-
date
formatted print date-
title
document title-
url
document location-
pageNumber
current page number-
totalPages
total pages in the document
property height
height?: string | number;
Sets the height of paper. You can pass in a number or a string with a unit.
property landscape
landscape?: boolean;
Whether to print in landscape orientation.
property margin
margin?: PDFMargin;
Set the PDF margins.
property omitBackground
omitBackground?: boolean;
Hides default white background and allows generating pdfs with transparency.
property outline
outline?: boolean;
Generate document outline.
Modifiers
@experimental
property pageRanges
pageRanges?: string;
Paper ranges to print, e.g.
1-5, 8, 11-13
.
property path
path?: string;
The path to save the file to.
Remarks
If the path is relative, it's resolved relative to the current working directory.
property preferCSSPageSize
preferCSSPageSize?: boolean;
Give any CSS
@page
size declared in the page priority over what is declared in thewidth
orheight
orformat
option.
property printBackground
printBackground?: boolean;
Set to
true
to print background graphics.
property scale
scale?: number;
Scales the rendering of the web page. Amount must be between
0.1
and2
.
property tagged
tagged?: boolean;
Generate tagged (accessible) PDF.
Modifiers
@experimental
property timeout
timeout?: number;
Timeout in milliseconds. Pass
0
to disable timeout.The default value can be changed by using Page.setDefaultTimeout
property waitForFonts
waitForFonts?: boolean;
If true, waits for
document.fonts.ready
to resolve. This might require activating the page using Page.bringToFront if the page is in the background.
property width
width?: string | number;
Sets the width of paper. You can pass in a number or a string with a unit.
interface PuppeteerLaunchOptions
interface PuppeteerLaunchOptions extends LaunchOptions, BrowserLaunchArgumentOptions, BrowserConnectOptions {}
Modifiers
@public
property browser
browser?: SupportedBrowser;
property extraPrefsFirefox
extraPrefsFirefox?: Record<string, unknown>;
interface QueryOptions
interface QueryOptions {}
Modifiers
@public
interface RemoteAddress
interface RemoteAddress {}
Modifiers
@public
interface ResponseForRequest
interface ResponseForRequest {}
Required response data to fulfill a request with.
Modifiers
@public
property body
body: string | Uint8Array;
property contentType
contentType: string;
property headers
headers: Record<string, string | string[] | unknown>;
Optional response headers.
The record values will be converted to string following: Arrays' values will be mapped to String (Used when you need multiple headers with the same name). Non-arrays will be converted to String.
property status
status: number;
interface ScreencastOptions
interface ScreencastOptions {}
Modifiers
@public
@experimental
property crop
crop?: BoundingBox;
Specifies the region of the viewport to crop.
property ffmpegPath
ffmpegPath?: string;
Path to the ffmpeg.
Required if
ffmpeg
is not in your PATH.
property path
path?: `${string}.webm`;
File path to save the screencast to.
property scale
scale?: number;
Scales the output video.
For example,
0.5
will shrink the width and height of the output video by half.2
will double the width and height of the output video.
property speed
speed?: number;
Specifies the speed to record at.
For example,
0.5
will slowdown the output video by 50%.2
will double the speed of the output video.
interface ScreenshotClip
interface ScreenshotClip extends BoundingBox {}
Modifiers
@public
property scale
scale?: number;
interface ScreenshotOptions
interface ScreenshotOptions {}
Modifiers
@public
property captureBeyondViewport
captureBeyondViewport?: boolean;
Capture the screenshot beyond the viewport.
property clip
clip?: ScreenshotClip;
Specifies the region of the page/element to clip.
property encoding
encoding?: 'base64' | 'binary';
Encoding of the image.
property fromSurface
fromSurface?: boolean;
Capture the screenshot from the surface, rather than the view.
property fullPage
fullPage?: boolean;
When
true
, takes a screenshot of the full page.
property omitBackground
omitBackground?: boolean;
Hides default white background and allows capturing screenshots with transparency.
property optimizeForSpeed
optimizeForSpeed?: boolean;
property path
path?: string;
The file path to save the image to. The screenshot type will be inferred from file extension. If path is a relative path, then it is resolved relative to current working directory. If no path is provided, the image won't be saved to the disk.
property quality
quality?: number;
Quality of the image, between 0-100. Not applicable to
png
images.
property type
type?: 'png' | 'jpeg' | 'webp';
interface SerializedAXNode
interface SerializedAXNode {}
Represents a Node and the properties of it that are relevant to Accessibility.
Modifiers
@public
property autocomplete
autocomplete?: string;
property checked
checked?: boolean | 'mixed';
Whether the checkbox is checked, or in a mixed state.
property children
children?: SerializedAXNode[];
Children of this node, if there are any.
property description
description?: string;
An additional human readable description of the node.
property disabled
disabled?: boolean;
property expanded
expanded?: boolean;
property focused
focused?: boolean;
property haspopup
haspopup?: string;
property invalid
invalid?: string;
Whether and in what way this node's value is invalid.
property keyshortcuts
keyshortcuts?: string;
Any keyboard shortcuts associated with this node.
property level
level?: number;
The level of a heading.
property modal
modal?: boolean;
property multiline
multiline?: boolean;
property multiselectable
multiselectable?: boolean;
Whether more than one child can be selected.
property name
name?: string;
A human readable name for the node.
property orientation
orientation?: string;
property pressed
pressed?: boolean | 'mixed';
Whether the node is checked or in a mixed state.
property readonly
readonly?: boolean;
property required
required?: boolean;
property role
role: string;
The role of the node.
property roledescription
roledescription?: string;
A human readable alternative to the role.
property selected
selected?: boolean;
property value
value?: string | number;
The current value of the node.
property valuemax
valuemax?: number;
property valuemin
valuemin?: number;
property valuetext
valuetext?: string;
A description of the current value.
method elementHandle
elementHandle: () => Promise<ElementHandle | null>;
Get an ElementHandle for this AXNode if available.
If the underlying DOM element has been disposed, the method might return an error.
interface SnapshotOptions
interface SnapshotOptions {}
Modifiers
@public
property interestingOnly
interestingOnly?: boolean;
Prune uninteresting nodes from the tree.
property root
root?: ElementHandle<Node>;
Root node to get the accessibility tree for
interface SupportedWebDriverCapabilities
interface SupportedWebDriverCapabilities {}
WebDriver BiDi capabilities that are not set by Puppeteer itself.
Modifiers
@public
property alwaysMatch
alwaysMatch?: SupportedWebDriverCapability;
property firstMatch
firstMatch?: SupportedWebDriverCapability[];
interface TouchHandle
interface TouchHandle {}
The TouchHandle interface exposes methods to manipulate touches that have been started
Modifiers
@public
interface TracingOptions
interface TracingOptions {}
Modifiers
@public
property categories
categories?: string[];
property path
path?: string;
property screenshots
screenshots?: boolean;
interface Viewport
interface Viewport {}
Modifiers
@public
property deviceScaleFactor
deviceScaleFactor?: number;
Specify device scale factor. See devicePixelRatio for more info.
Remarks
Setting this value to
0
will reset this value to the system default.
property hasTouch
hasTouch?: boolean;
Specify if the viewport supports touch events.
property height
height: number;
The page height in CSS pixels.
Remarks
Setting this value to
0
will reset this value to the system default.
property isLandscape
isLandscape?: boolean;
Specifies if the viewport is in landscape mode.
property isMobile
isMobile?: boolean;
Whether the
meta viewport
tag is taken into account.
property width
width: number;
The page width in CSS pixels.
Remarks
Setting this value to
0
will reset this value to the system default.
interface WaitForNetworkIdleOptions
interface WaitForNetworkIdleOptions extends WaitTimeoutOptions {}
Modifiers
@public
property concurrency
concurrency?: number;
Maximum number concurrent of network connections to be considered inactive.
property idleTime
idleTime?: number;
Time (in milliseconds) the network should be idle.
interface WaitForOptions
interface WaitForOptions {}
Modifiers
@public
property signal
signal?: AbortSignal;
A signal object that allows you to cancel the call.
property timeout
timeout?: number;
Maximum wait time in milliseconds. Pass 0 to disable the timeout.
The default value can be changed by using the Page.setDefaultTimeout or Page.setDefaultNavigationTimeout methods.
property waitUntil
waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[];
When to consider waiting succeeds. Given an array of event strings, waiting is considered to be successful after all events have been fired.
interface WaitForSelectorOptions
interface WaitForSelectorOptions {}
Modifiers
@public
property hidden
hidden?: boolean;
Wait for the selected element to not be found in the DOM or to be hidden. See ElementHandle.isHidden for the definition of element invisibility.
property signal
signal?: AbortSignal;
A signal object that allows you to cancel a waitForSelector call.
property timeout
timeout?: number;
Maximum time to wait in milliseconds. Pass
0
to disable timeout.The default value can be changed by using Page.setDefaultTimeout
property visible
visible?: boolean;
Wait for the selected element to be present in DOM and to be visible. See ElementHandle.isVisible for the definition of element visibility.
interface WaitForTargetOptions
interface WaitForTargetOptions {}
Modifiers
@public
interface WaitTimeoutOptions
interface WaitTimeoutOptions {}
Modifiers
@public
property signal
signal?: AbortSignal;
A signal object that allows you to cancel a waitFor call.
property timeout
timeout?: number;
Maximum wait time in milliseconds. Pass 0 to disable the timeout.
The default value can be changed by using the Page.setDefaultTimeout method.
enum BrowserContextEvent
const enum BrowserContextEvent { TargetChanged = 'targetchanged', TargetCreated = 'targetcreated', TargetDestroyed = 'targetdestroyed',}
Modifiers
@public
member TargetChanged
TargetChanged = 'targetchanged'
Emitted when the url of a target inside the browser context changes. Contains a Target instance.
member TargetCreated
TargetCreated = 'targetcreated'
Emitted when a target is created within the browser context, for example when a new page is opened by window.open or by browserContext.newPage
Contains a Target instance.
member TargetDestroyed
TargetDestroyed = 'targetdestroyed'
Emitted when a target is destroyed within the browser context, for example when a page is closed. Contains a Target instance.
enum BrowserEvent
const enum BrowserEvent { Disconnected = 'disconnected', TargetChanged = 'targetchanged', TargetCreated = 'targetcreated', TargetDestroyed = 'targetdestroyed',}
All the events a browser instance may emit.
Modifiers
@public
member Disconnected
Disconnected = 'disconnected'
Emitted when Puppeteer gets disconnected from the browser instance. This might happen because either:
- The browser closes/crashes or - Browser.disconnect was called.
member TargetChanged
TargetChanged = 'targetchanged'
Emitted when the URL of a target changes. Contains a Target instance.
Remarks
Note that this includes target changes in all browser contexts.
member TargetCreated
TargetCreated = 'targetcreated'
Emitted when a target is created, for example when a new page is opened by window.open or by browser.newPage
Contains a Target instance.
Remarks
Note that this includes target creations in all browser contexts.
member TargetDestroyed
TargetDestroyed = 'targetdestroyed'
Emitted when a target is destroyed, for example when a page is closed. Contains a Target instance.
Remarks
Note that this includes target destructions in all browser contexts.
enum InterceptResolutionAction
enum InterceptResolutionAction { Abort = 'abort', Respond = 'respond', Continue = 'continue', Disabled = 'disabled', None = 'none', AlreadyHandled = 'already-handled',}
Modifiers
@public
enum LocatorEvent
enum LocatorEvent { Action = 'action',}
All the events that a locator instance may emit.
Modifiers
@public
member Action
Action = 'action'
Emitted every time before the locator performs an action on the located element(s).
enum PageEvent
const enum PageEvent { Close = 'close', Console = 'console', Dialog = 'dialog', DOMContentLoaded = 'domcontentloaded', Error = 'error', FrameAttached = 'frameattached', FrameDetached = 'framedetached', FrameNavigated = 'framenavigated', Load = 'load', Metrics = 'metrics', PageError = 'pageerror', Popup = 'popup', Request = 'request', RequestServedFromCache = 'requestservedfromcache', RequestFailed = 'requestfailed', RequestFinished = 'requestfinished', Response = 'response', WorkerCreated = 'workercreated', WorkerDestroyed = 'workerdestroyed',}
All the events that a page instance may emit.
Modifiers
@public
member Close
Close = 'close'
Emitted when the page closes.
member Console
Console = 'console'
Emitted when JavaScript within the page calls one of console API methods, e.g.
console.log
orconsole.dir
. Also emitted if the page throws an error or a warning.Remarks
A
console
event provides a ConsoleMessage representing the console message that was logged.Example 1
An example of handling
console
event: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'}));
member Dialog
Dialog = 'dialog'
Emitted when a JavaScript dialog appears, such as
alert
,prompt
,confirm
orbeforeunload
. Puppeteer can respond to the dialog via Dialog.accept or Dialog.dismiss.
member DOMContentLoaded
DOMContentLoaded = 'domcontentloaded'
Emitted when the JavaScript DOMContentLoaded event is dispatched.
member Error
Error = 'error'
Emitted when the page crashes. Will contain an
Error
.
member FrameAttached
FrameAttached = 'frameattached'
Emitted when a frame is attached. Will contain a Frame.
member FrameDetached
FrameDetached = 'framedetached'
Emitted when a frame is detached. Will contain a Frame.
member FrameNavigated
FrameNavigated = 'framenavigated'
Emitted when a frame is navigated to a new URL. Will contain a Frame.
member Load
Load = 'load'
Emitted when the JavaScript load event is dispatched.
member Metrics
Metrics = 'metrics'
Emitted when the JavaScript code makes a call to
console.timeStamp
. For the list of metrics see page.metrics.Remarks
Contains an object with two properties:
-
title
: the title passed toconsole.timeStamp
-metrics
: object containing metrics as key/value pairs. The values will benumber
s.
member PageError
PageError = 'pageerror'
Emitted when an uncaught exception happens within the page. Contains an
Error
.
member Popup
Popup = 'popup'
Emitted when the page opens a new tab or window.
Contains a Page corresponding to the popup window.
Example 1
const [popup] = await Promise.all([new Promise(resolve => page.once('popup', resolve)),page.click('a[target=_blank]'),]);const [popup] = await Promise.all([new Promise(resolve => page.once('popup', resolve)),page.evaluate(() => window.open('https://example.com')),]);
member Request
Request = 'request'
Emitted when a page issues a request and contains a HTTPRequest.
Remarks
The object is readonly. See Page.setRequestInterception for intercepting and mutating requests.
member RequestFailed
RequestFailed = 'requestfailed'
Emitted when a request fails, for example by timing out.
Contains a HTTPRequest.
Remarks
HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with
requestfinished
event and not withrequestfailed
.
member RequestFinished
RequestFinished = 'requestfinished'
Emitted when a request finishes successfully. Contains a HTTPRequest.
member RequestServedFromCache
RequestServedFromCache = 'requestservedfromcache'
Emitted when a request ended up loading from cache. Contains a HTTPRequest.
Remarks
For certain requests, might contain undefined. https://crbug.com/750469
member Response
Response = 'response'
Emitted when a response is received. Contains a HTTPResponse.
member WorkerCreated
WorkerCreated = 'workercreated'
Emitted when a dedicated WebWorker is spawned by the page.
member WorkerDestroyed
WorkerDestroyed = 'workerdestroyed'
Emitted when a dedicated WebWorker is destroyed by the page.
enum TargetType
enum TargetType { PAGE = 'page', BACKGROUND_PAGE = 'background_page', SERVICE_WORKER = 'service_worker', SHARED_WORKER = 'shared_worker', BROWSER = 'browser', WEBVIEW = 'webview', OTHER = 'other',}
Modifiers
@public
member BACKGROUND_PAGE
BACKGROUND_PAGE = 'background_page'
member BROWSER
BROWSER = 'browser'
member OTHER
OTHER = 'other'
member PAGE
PAGE = 'page'
member SERVICE_WORKER
SERVICE_WORKER = 'service_worker'
member SHARED_WORKER
SHARED_WORKER = 'shared_worker'
member WEBVIEW
WEBVIEW = 'webview'
type ActionResult
type ActionResult = 'continue' | 'abort' | 'respond';
Modifiers
@public
type Awaitable
type Awaitable<T> = T | PromiseLike<T>;
Modifiers
@public
type AwaitableIterable
type AwaitableIterable<T> = Iterable<T> | AsyncIterable<T>;
Modifiers
@public
type AwaitablePredicate
type AwaitablePredicate<T> = (value: T) => Awaitable<boolean>;
Modifiers
@public
type AwaitedLocator
type AwaitedLocator<T> = T extends Locator<infer S> ? S : never;
Modifiers
@public
type CDPEvents
type CDPEvents = { [Property in keyof ProtocolMapping.Events]: ProtocolMapping.Events[Property][0];};
Modifiers
@public
type ChromeReleaseChannel
type ChromeReleaseChannel = | 'chrome' | 'chrome-beta' | 'chrome-canary' | 'chrome-dev';
Modifiers
@public
type ConsoleMessageType
type ConsoleMessageType = | 'log' | 'debug' | 'info' | 'error' | 'warn' | 'dir' | 'dirxml' | 'table' | 'trace' | 'clear' | 'startGroup' | 'startGroupCollapsed' | 'endGroup' | 'assert' | 'profile' | 'profileEnd' | 'count' | 'timeEnd' | 'verbose';
The supported types for console messages.
Modifiers
@public
type CookiePriority
type CookiePriority = 'Low' | 'Medium' | 'High';
Represents the cookie's 'Priority' status: https://tools.ietf.org/html/draft-west-cookie-priority-00
Modifiers
@public
type CookieSameSite
type CookieSameSite = 'Strict' | 'Lax' | 'None';
Represents the cookie's 'SameSite' status: https://tools.ietf.org/html/draft-west-first-party-cookies
Modifiers
@public
type CookieSourceScheme
type CookieSourceScheme = 'Unset' | 'NonSecure' | 'Secure';
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.
Modifiers
@public
type ElementFor
type ElementFor< TagName extends keyof HTMLElementTagNameMap | keyof SVGElementTagNameMap> = TagName extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[TagName] : TagName extends keyof SVGElementTagNameMap ? SVGElementTagNameMap[TagName] : never;
Modifiers
@public
type ErrorCode
type ErrorCode = | 'aborted' | 'accessdenied' | 'addressunreachable' | 'blockedbyclient' | 'blockedbyresponse' | 'connectionaborted' | 'connectionclosed' | 'connectionfailed' | 'connectionrefused' | 'connectionreset' | 'internetdisconnected' | 'namenotresolved' | 'timedout' | 'failed';
Modifiers
@public
type EvaluateFunc
type EvaluateFunc<T extends unknown[]> = ( ...params: InnerParams<T>) => Awaitable<unknown>;
Modifiers
@public
type EvaluateFuncWith
type EvaluateFuncWith<V, T extends unknown[]> = ( ...params: [V, ...InnerParams<T>]) => Awaitable<unknown>;
Modifiers
@public
type EventsWithWildcard
type EventsWithWildcard<Events extends Record<EventType, unknown>> = Events & { '*': Events[keyof Events];};
Modifiers
@public
type EventType
type EventType = string | symbol;
Modifiers
@public
type ExperimentsConfiguration
type ExperimentsConfiguration = Record<string, never>;
Defines experiment options for Puppeteer.
See individual properties for more information.
Modifiers
@public
type FlattenHandle
type FlattenHandle<T> = T extends HandleOr<infer U> ? U : never;
Modifiers
@public
type HandleFor
type HandleFor<T> = T extends Node ? ElementHandle<T> : JSHandle<T>;
Modifiers
@public
type HandleOr
type HandleOr<T> = HandleFor<T> | JSHandle<T> | T;
Modifiers
@public
type Handler
type Handler<T = unknown> = (event: T) => void;
Modifiers
@public
type InnerParams
type InnerParams<T extends unknown[]> = { [K in keyof T]: FlattenHandle<T[K]>;};
Modifiers
@public
type KeyInput
type KeyInput = | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | 'Power' | 'Eject' | 'Abort' | 'Help' | 'Backspace' | 'Tab' | 'Numpad5' | 'NumpadEnter' | 'Enter' | '\r' | '\n' | 'ShiftLeft' | 'ShiftRight' | 'ControlLeft' | 'ControlRight' | 'AltLeft' | 'AltRight' | 'Pause' | 'CapsLock' | 'Escape' | 'Convert' | 'NonConvert' | 'Space' | 'Numpad9' | 'PageUp' | 'Numpad3' | 'PageDown' | 'End' | 'Numpad1' | 'Home' | 'Numpad7' | 'ArrowLeft' | 'Numpad4' | 'Numpad8' | 'ArrowUp' | 'ArrowRight' | 'Numpad6' | 'Numpad2' | 'ArrowDown' | 'Select' | 'Open' | 'PrintScreen' | 'Insert' | 'Numpad0' | 'Delete' | 'NumpadDecimal' | 'Digit0' | 'Digit1' | 'Digit2' | 'Digit3' | 'Digit4' | 'Digit5' | 'Digit6' | 'Digit7' | 'Digit8' | 'Digit9' | 'KeyA' | 'KeyB' | 'KeyC' | 'KeyD' | 'KeyE' | 'KeyF' | 'KeyG' | 'KeyH' | 'KeyI' | 'KeyJ' | 'KeyK' | 'KeyL' | 'KeyM' | 'KeyN' | 'KeyO' | 'KeyP' | 'KeyQ' | 'KeyR' | 'KeyS' | 'KeyT' | 'KeyU' | 'KeyV' | 'KeyW' | 'KeyX' | 'KeyY' | 'KeyZ' | 'MetaLeft' | 'MetaRight' | 'ContextMenu' | 'NumpadMultiply' | 'NumpadAdd' | 'NumpadSubtract' | 'NumpadDivide' | 'F1' | 'F2' | 'F3' | 'F4' | 'F5' | 'F6' | 'F7' | 'F8' | 'F9' | 'F10' | 'F11' | 'F12' | 'F13' | 'F14' | 'F15' | 'F16' | 'F17' | 'F18' | 'F19' | 'F20' | 'F21' | 'F22' | 'F23' | 'F24' | 'NumLock' | 'ScrollLock' | 'AudioVolumeMute' | 'AudioVolumeDown' | 'AudioVolumeUp' | 'MediaTrackNext' | 'MediaTrackPrevious' | 'MediaStop' | 'MediaPlayPause' | 'Semicolon' | 'Equal' | 'NumpadEqual' | 'Comma' | 'Minus' | 'Period' | 'Slash' | 'Backquote' | 'BracketLeft' | 'Backslash' | 'BracketRight' | 'Quote' | 'AltGraph' | 'Props' | 'Cancel' | 'Clear' | 'Shift' | 'Control' | 'Alt' | 'Accept' | 'ModeChange' | ' ' | 'Print' | 'Execute' | '\u0000' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z' | 'Meta' | '*' | '+' | '-' | '/' | ';' | '=' | ',' | '.' | '`' | '[' | '\\' | ']' | "'" | 'Attn' | 'CrSel' | 'ExSel' | 'EraseEof' | 'Play' | 'ZoomOut' | ')' | '!' | '@' | '#' | '$' | '%' | '^' | '&' | '(' | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z' | ':' | '<' | '_' | '>' | '?' | '~' | '{' | '|' | '}' | '"' | 'SoftLeft' | 'SoftRight' | 'Camera' | 'Call' | 'EndCall' | 'VolumeDown' | 'VolumeUp';
All the valid keys that can be passed to functions that take user input, such as keyboard.press
Modifiers
@public
type KeyPressOptions
type KeyPressOptions = KeyDownOptions & KeyboardTypeOptions;
Modifiers
@public
type LocatorClickOptions
type LocatorClickOptions = ClickOptions & ActionOptions;
Modifiers
@public
type LowerCasePaperFormat
type LowerCasePaperFormat = | 'letter' | 'legal' | 'tabloid' | 'ledger' | 'a0' | 'a1' | 'a2' | 'a3' | 'a4' | 'a5' | 'a6';
Modifiers
@public
type Mapper
type Mapper<From, To> = (value: From) => Awaitable<To>;
Modifiers
@public
type MouseButton
type MouseButton = (typeof MouseButton)[keyof typeof MouseButton];
Modifiers
@public
type NodeFor
type NodeFor<ComplexSelector extends string> = ParseSelector<ComplexSelector>;
Modifiers
@public
type PaperFormat
type PaperFormat = | Uppercase<LowerCasePaperFormat> | Capitalize<LowerCasePaperFormat> | LowerCasePaperFormat;
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.1102in x 46.811in-
A1
: 23.3858in x 33.1102in-
A2
: 16.5354in x 23.3858in-
A3
: 11.6929in x 16.5354in-
A4
: 8.2677in x 11.6929in-
A5
: 5.8268in x 8.2677in-
A6
: 4.1339in x 5.8268inModifiers
@public
type Permission
type Permission = | 'geolocation' | 'midi' | 'notifications' | 'camera' | 'microphone' | 'background-sync' | 'ambient-light-sensor' | 'accelerometer' | 'gyroscope' | 'magnetometer' | 'accessibility-events' | 'clipboard-read' | 'clipboard-write' | 'clipboard-sanitized-write' | 'payment-handler' | 'persistent-storage' | 'idle-detection' | 'midi-sysex';
Modifiers
@public
type Predicate
type Predicate<From, To extends From = From> = | ((value: From) => value is To) | ((value: From) => Awaitable<boolean>);
Modifiers
@public
type ProtocolLifeCycleEvent
type ProtocolLifeCycleEvent = | 'load' | 'DOMContentLoaded' | 'networkIdle' | 'networkAlmostIdle';
Modifiers
@public
type ProtocolType
type ProtocolType = 'cdp' | 'webDriverBiDi';
Modifiers
@public
type PuppeteerLifeCycleEvent
type PuppeteerLifeCycleEvent = /** * Waits for the 'load' event. */ | 'load' /** * Waits for the 'DOMContentLoaded' event. */ | 'domcontentloaded' /** * Waits till there are no more than 0 network connections for at least `500` * ms. */ | 'networkidle0' /** * Waits till there are no more than 2 network connections for at least `500` * ms. */ | 'networkidle2';
Modifiers
@public
type PuppeteerNodeLaunchOptions
type PuppeteerNodeLaunchOptions = BrowserLaunchArgumentOptions & LaunchOptions & BrowserConnectOptions;
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.Modifiers
@public
type Quad
type Quad = [Point, Point, Point, Point];
Modifiers
@public
type ResourceType
type ResourceType = Lowercase<Protocol.Network.ResourceType>;
Resource types for HTTPRequests as perceived by the rendering engine.
Modifiers
@public
type SupportedBrowser
type SupportedBrowser = 'chrome' | 'firefox';
Browsers supported by Puppeteer.
Modifiers
@public
type SupportedWebDriverCapability
type SupportedWebDriverCapability = Exclude< Session.CapabilityRequest, 'unhandledPromptBehavior' | 'acceptInsecureCerts'>;
Modifiers
@public
type TargetFilterCallback
type TargetFilterCallback = (target: Target) => boolean;
Modifiers
@public
type VisibilityOption
type VisibilityOption = 'hidden' | 'visible' | null;
namespace Puppeteer_2.CDPSessionEvent
namespace Puppeteer_2.CDPSessionEvent {}
Events that the CDPSession class emits.
Modifiers
@public
variable SessionAttached
const SessionAttached: string;
variable SessionDetached
const SessionDetached: string;
Package Files (1)
Dependencies (6)
Dev Dependencies (7)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/puppeteer-core
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/puppeteer-core)
- HTML<a href="https://www.jsdocs.io/package/puppeteer-core"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 28305 ms. - Missing or incorrect documentation? Open an issue for this package.