puppeteer
- Version 19.6.0
- Published
- 329 kB
- 5 dependencies
- Apache-2.0 license
Install
npm i puppeteer
yarn add puppeteer
pnpm add puppeteer
Overview
A high-level API to control headless Chrome over the DevTools Protocol
Index
Variables
Functions
Classes
Frame
- $()
- $$()
- $$eval()
- $eval()
- $x()
- addScriptTag()
- addStyleTag()
- childFrames()
- click()
- content()
- evaluate()
- evaluateHandle()
- focus()
- goto()
- hover()
- isDetached()
- isOOPFrame()
- name()
- page()
- parentFrame()
- select()
- setContent()
- tap()
- title()
- type()
- url()
- waitForFunction()
- waitForNavigation()
- waitForSelector()
- waitForTimeout()
- waitForXPath()
HTTPRequest
- abort()
- abortErrorReason()
- client
- continue()
- continueRequestOverrides()
- enqueueInterceptAction()
- failure()
- finalizeInterceptions()
- frame()
- headers()
- initiator()
- interceptResolutionState()
- isInterceptResolutionHandled()
- isNavigationRequest()
- method()
- postData()
- redirectChain()
- resourceType()
- respond()
- response()
- responseForRequest()
- url()
Page
- $()
- $$()
- $$eval()
- $eval()
- $x()
- accessibility
- addScriptTag()
- addStyleTag()
- authenticate()
- bringToFront()
- browser()
- browserContext()
- click()
- close()
- content()
- cookies()
- coverage
- createPDFStream()
- deleteCookie()
- emulate()
- emulateCPUThrottling()
- emulateIdleState()
- emulateMediaFeatures()
- emulateMediaType()
- emulateNetworkConditions()
- emulateTimezone()
- emulateVisionDeficiency()
- evaluate()
- evaluateHandle()
- evaluateOnNewDocument()
- exposeFunction()
- focus()
- frames()
- getDefaultTimeout()
- goBack()
- goForward()
- goto()
- hover()
- isClosed()
- isDragInterceptionEnabled()
- isJavaScriptEnabled()
- keyboard
- mainFrame()
- metrics()
- mouse
- off()
- on()
- once()
- pdf()
- queryObjects()
- reload()
- screenshot()
- select()
- setBypassCSP()
- setCacheEnabled()
- setContent()
- setCookie()
- setDefaultNavigationTimeout()
- setDefaultTimeout()
- setDragInterception()
- setExtraHTTPHeaders()
- setGeolocation()
- setJavaScriptEnabled()
- setOfflineMode()
- setRequestInterception()
- setUserAgent()
- setViewport()
- tap()
- target()
- title()
- touchscreen
- tracing
- type()
- url()
- viewport()
- waitForFileChooser()
- waitForFrame()
- waitForFunction()
- waitForNavigation()
- waitForNetworkIdle()
- waitForRequest()
- waitForResponse()
- waitForSelector()
- waitForTimeout()
- waitForXPath()
- workers()
Interfaces
Enums
Type Aliases
- ActionResult
- Awaitable
- ChromeReleaseChannel
- ConsoleMessageType
- ElementFor
- ErrorCode
- EvaluateFunc
- EventType
- FlattenHandle
- HandleFor
- HandleOr
- Handler
- InnerParams
- InterceptResolutionStrategy
- KeyInput
- LowerCasePaperFormat
- MouseButton
- NodeFor
- PaperFormat
- Permission
- Platform
- Product
- ProtocolLifeCycleEvent
- PuppeteerLifeCycleEvent
- PuppeteerNodeLaunchOptions
- ResourceType
- TargetFilterCallback
Variables
variable DEFAULT_INTERCEPT_RESOLUTION_PRIORITY
const DEFAULT_INTERCEPT_RESOLUTION_PRIORITY: number;
The default cooperative request interception resolution priority
Modifiers
@public
variable devices
const devices: 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' | '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 >>;
Modifiers
@public
Deprecated
Import KnownDevices
variable errors
const errors: PuppeteerErrors;
Example 1
An example of handling a timeout error:
try {await page.waitForSelector('.foo');} catch (e) {if (e instanceof TimeoutError) {// Do something if this is a timeout.}}Modifiers
@public
Deprecated
Import error classes directly.
Puppeteer methods might throw errors if they are unable to fulfill a request. For example,
page.waitForSelector(selector[, options])
might fail if the selector doesn't match any nodes during the given timeframe.For certain types of errors Puppeteer uses specific error classes. These classes are available via
puppeteer.errors
.
variable EVALUATION_SCRIPT_URL
const EVALUATION_SCRIPT_URL: string;
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' | '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 6'];(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 networkConditions
const networkConditions: Readonly<{ 'Slow 3G': NetworkConditions; 'Fast 3G': NetworkConditions;}>;
Modifiers
@public
Deprecated
Import PredefinedNetworkConditions.
variable PredefinedNetworkConditions
const PredefinedNetworkConditions: Readonly<{ 'Slow 3G': NetworkConditions; 'Fast 3G': NetworkConditions;}>;
A list of network conditions to be used with Page.emulateNetworkConditions.
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();})();Modifiers
@public
variable puppeteer
const puppeteer: PuppeteerNode;
Modifiers
@public
Functions
function clearCustomQueryHandlers
clearCustomQueryHandlers: () => void;
Modifiers
@public
Deprecated
Import Puppeteer and use the static method Puppeteer.clearCustomQueryHandlers
function connect
connect: (options: ConnectOptions) => Promise<Browser>;
function createBrowserFetcher
createBrowserFetcher: ( options?: Partial<BrowserFetcherOptions> | undefined) => BrowserFetcher;
function customQueryHandlerNames
customQueryHandlerNames: () => string[];
Modifiers
@public
Deprecated
Import Puppeteer and use the static method Puppeteer.customQueryHandlerNames
function defaultArgs
defaultArgs: (options?: BrowserLaunchArgumentOptions | undefined) => string[];
function executablePath
executablePath: (channel?: ChromeReleaseChannel | undefined) => string;
function launch
launch: (options?: PuppeteerLaunchOptions | undefined) => Promise<Browser>;
function registerCustomQueryHandler
registerCustomQueryHandler: (name: string, handler: CustomQueryHandler) => void;
Modifiers
@public
Deprecated
Import Puppeteer and use the static method Puppeteer.registerCustomQueryHandler
function unregisterCustomQueryHandler
unregisterCustomQueryHandler: (name: string) => void;
Modifiers
@public
Deprecated
Import Puppeteer and use the static method Puppeteer.unregisterCustomQueryHandler
Classes
class Accessibility
class Accessibility {}
The Accessibility class provides methods for inspecting Chromium'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 Chromium accessibility tree contains nodes that go unused on most platforms and by most screen readers. Puppeteer will discard them as well for an easier to process tree, unless
interestingOnly
is set 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
class Browser extends EventEmitter {}
A Browser is created when Puppeteer connects to a Chromium instance, either through PuppeteerNode.launch or Puppeteer.connect.
Remarks
The Browser class extends from Puppeteer's EventEmitter class and will emit various events which are documented in the BrowserEmittedEvents enum.
Example 1
An example of using a Browser to create a Page:
import puppeteer from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();await page.goto('https://example.com');await browser.close();})();Example 2
An example of disconnecting from and reconnecting to a Browser:
import puppeteer from 'puppeteer';(async () => {const browser = await puppeteer.launch();// Store the endpoint to be able to reconnect to Chromiumconst browserWSEndpoint = browser.wsEndpoint();// Disconnect puppeteer from Chromiumbrowser.disconnect();// Use the endpoint to reestablish a connectionconst browser2 = await puppeteer.connect({browserWSEndpoint});// Close Chromiumawait browser2.close();})();Modifiers
@public
method browserContexts
browserContexts: () => BrowserContext[];
Returns an array of all open browser contexts. In a newly created browser, this will return a single instance of BrowserContext.
method close
close: () => Promise<void>;
Closes Chromium and all of its pages (if any were opened). The Browser object itself is considered to be disposed and cannot be used anymore.
method createIncognitoBrowserContext
createIncognitoBrowserContext: ( options?: BrowserContextOptions) => Promise<BrowserContext>;
Creates a new incognito browser context. This won't share cookies/cache with other browser contexts.
Example 1
(async () => {const browser = await puppeteer.launch();// Create a new incognito browser context.const context = await browser.createIncognitoBrowserContext();// Create a new page in a pristine context.const page = await context.newPage();// Do stuffawait page.goto('https://example.com');})();
method defaultBrowserContext
defaultBrowserContext: () => BrowserContext;
Returns the default browser context. The default browser context cannot be closed.
method disconnect
disconnect: () => void;
Disconnects Puppeteer from the browser, but leaves the Chromium process running. After calling
disconnect
, the Browser object is considered disposed and cannot be used anymore.
method isConnected
isConnected: () => boolean;
Indicates that the browser is connected.
method newPage
newPage: () => Promise<Page>;
Promise which resolves to a new Page object. The Page is created in a default browser context.
method pages
pages: () => Promise<Page[]>;
An array of all open pages inside the Browser.
Remarks
In case of multiple browser contexts, returns an array with all the pages in all browser contexts. Non-visible pages, such as
"background_page"
, will not be listed here. You can find them using Target.page.
method process
process: () => ChildProcess | null;
The spawned browser process. Returns
null
if the browser instance was created with Puppeteer.connect.
method target
target: () => Target;
The target associated with the browser.
method targets
targets: () => Target[];
All active targets inside the Browser. In case of multiple browser contexts, returns an array with all the targets in all browser contexts.
method userAgent
userAgent: () => Promise<string>;
The browser's original user agent. Pages can override the browser user agent with Page.setUserAgent.
method version
version: () => Promise<string>;
A string representing the browser name and version.
Remarks
For headless Chromium, this is similar to
HeadlessChrome/61.0.3153.0
. For non-headless, this is similar toChrome/61.0.3153.0
.The format of browser.version() might change with future releases of Chromium.
method waitForTarget
waitForTarget: ( predicate: (x: Target) => boolean | Promise<boolean>, options?: WaitForTargetOptions) => Promise<Target>;
Searches for a target in all browser contexts.
Parameter predicate
A function to be run for every target.
Returns
The first target found that matches the
predicate
function.Example 1
An example of 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
wsEndpoint: () => string;
The browser websocket endpoint which can be used as an argument to Puppeteer.connect.
Returns
The Browser websocket url.
Remarks
The format is
ws://${host}:${port}/devtools/browser/<id>
.You can find the
webSocketDebuggerUrl
fromhttp://${host}:${port}/json/version
. Learn more about the devtools protocol and the browser endpoint.
class BrowserContext
class BrowserContext extends EventEmitter {}
BrowserContexts provide a way to operate multiple independent browser sessions. When a browser is launched, it has a single BrowserContext used by default. The method Browser.newPage creates a page in the default browser context.
Remarks
The Browser class extends from Puppeteer's EventEmitter class and will emit various events which are documented in the BrowserContextEmittedEvents enum.
If a page opens another page, e.g. with a
window.open
call, the popup will belong to the parent page's browser context.Puppeteer allows creation of "incognito" browser contexts with Browser.createIncognitoBrowserContext method. "Incognito" browser contexts don't write any browsing data to disk.
Example 1
// Create a new incognito browser contextconst context = await browser.createIncognitoBrowserContext();// Create a new page inside context.const page = await context.newPage();// ... do stuff with page ...await page.goto('https://example.com');// Dispose context once it's no longer needed.await context.close();Modifiers
@public
property id
readonly id: string;
method browser
browser: () => Browser;
The browser this browser context belongs to.
method clearPermissionOverrides
clearPermissionOverrides: () => Promise<void>;
Clears all permission overrides for the browser context.
Example 1
const context = browser.defaultBrowserContext();context.overridePermissions('https://example.com', ['clipboard-read']);// do stuff ..context.clearPermissionOverrides();
method close
close: () => Promise<void>;
Closes the browser context. All the targets that belong to the browser context will be closed.
Remarks
Only incognito browser contexts can be closed.
method isIncognito
isIncognito: () => boolean;
Returns whether BrowserContext is incognito. The default browser context is the only non-incognito browser context.
Remarks
The default browser context cannot be closed.
method newPage
newPage: () => Promise<Page>;
Creates a new page in the browser context.
method overridePermissions
overridePermissions: ( origin: string, permissions: Permission[]) => Promise<void>;
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
const context = browser.defaultBrowserContext();await context.overridePermissions('https://html5demos.com', ['geolocation',]);
method pages
pages: () => Promise<Page[]>;
An array of all pages inside the browser context.
Returns
Promise which resolves to an array of all open pages. Non visible pages, such as
"background_page"
, will not be listed here. You can find them using the target page.
method targets
targets: () => Target[];
An array of all active targets inside the browser context.
method waitForTarget
waitForTarget: ( predicate: (x: Target) => boolean | Promise<boolean>, options?: { timeout?: number }) => Promise<Target>;
This searches for a target in this specific browser context.
Parameter predicate
A function to be run for every target
Parameter options
An object of options. Accepts a timeout, which is the maximum wait time in milliseconds. Pass
0
to disable the timeout. Defaults to 30 seconds.Returns
Promise which resolves to the first target found that matches the
predicate
function.Example 1
An example of 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 BrowserFetcher
class BrowserFetcher {}
BrowserFetcher can download and manage different versions of Chromium and Firefox.
Remarks
BrowserFetcher is not designed to work concurrently with other instances of BrowserFetcher that share the same downloads directory.
Example 1
An example of using BrowserFetcher to download a specific version of Chromium and running Puppeteer against it:
const browserFetcher = new BrowserFetcher({path: 'path/to/download/folder'});const revisionInfo = await browserFetcher.download('533271');const browser = await puppeteer.launch({executablePath: revisionInfo.executablePath,});Modifiers
@public
constructor
constructor(options: BrowserFetcherOptions);
Constructs a browser fetcher for the given options.
method canDownload
canDownload: (revision: string) => Promise<boolean>;
Initiates a HEAD request to check if the revision is available.
Parameter revision
The revision to check availability for.
Returns
A promise that resolves to
true
if the revision could be downloaded from the host.Remarks
This method is affected by the current
product
.
method download
download: ( revision: string, progressCallback?: (x: number, y: number) => void) => Promise<BrowserFetcherRevisionInfo | undefined>;
Initiates a GET request to download the revision from the host.
Parameter revision
The revision to download.
Parameter progressCallback
A function that will be called with two arguments: How many bytes have been downloaded and the total number of bytes of the download.
Returns
A promise with revision information when the revision is downloaded and extracted.
Remarks
This method is affected by the current
product
.
method host
host: () => string;
Returns
The download host being used.
method localRevisions
localRevisions: () => string[];
Returns
A list of all revision strings (for the current
product
) available locally on disk.Remarks
This method is affected by the current
product
.
method platform
platform: () => Platform;
Returns
Returns the current
Platform
, which is one ofmac
,linux
,win32
orwin64
.
method product
product: () => Product;
Returns
Returns the current
Product
, which is one ofchrome
orfirefox
.
method remove
remove: (revision: string) => Promise<void>;
Parameter revision
A revision to remove for the current
product
.Returns
A promise that resolves when the revision has been removes or throws if the revision has not been downloaded.
Remarks
This method is affected by the current
product
.
method revisionInfo
revisionInfo: (revision: string) => BrowserFetcherRevisionInfo;
Parameter revision
The revision to get info for.
Returns
The revision info for the given revision.
class CDPSession
class CDPSession extends EventEmitter {}
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.target().createCDPSession();await client.send('Animation.enable');client.on('Animation.animationCreated', () =>console.log('Animation created!'));const response = await client.send('Animation.getPlaybackRate');console.log('playback rate is ' + response.playbackRate);await client.send('Animation.setPlaybackRate', {playbackRate: response.playbackRate / 2,});Modifiers
@public
method connection
connection: () => Connection | undefined;
method detach
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
id: () => string;
Returns the session's id.
method send
send: <T extends string | number | symbol>( method: T, ...paramArgs: ProtocolMapping.Commands) => Promise<ProtocolMapping.Commands[T]['returnType']>;
class Connection
class Connection extends EventEmitter {}
Modifiers
@public
constructor
constructor(url: string, transport: ConnectionTransport, delay?: 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, ...paramArgs: ProtocolMapping.Commands) => 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
constructor
constructor( type: ConsoleMessageType, text: string, args: JSHandle<unknown>[], stackTraceLocations: ConsoleMessageLocation[]);
Modifiers
@public
method args
args: () => JSHandle[];
Returns
An array of arguments passed to the console.
method location
location: () => ConsoleMessageLocation;
Returns
The location of the console message.
method stackTrace
stackTrace: () => ConsoleMessageLocation[];
Returns
The array of locations on the stack of the console message.
method text
text: () => string;
Returns
The text of the console message.
method type
type: () => ConsoleMessageType;
Returns
The type of the console message.
class Coverage
class Coverage {}
The Coverage class provides methods to gathers information about parts of JavaScript and CSS that were used by the page.
Remarks
To output coverage in a form consumable by 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
constructor
constructor(client: CDPSession);
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[]>;
Returns
Promise that resolves to the array of coverage reports for all stylesheets.
Remarks
CSS Coverage doesn't include dynamically injected style tags without sourceURLs.
method stopJSCoverage
stopJSCoverage: () => Promise<JSCoverageEntry[]>;
Returns
Promise that resolves to the array of coverage reports for all scripts.
Remarks
JavaScript Coverage doesn't include anonymous scripts by default. However, scripts with sourceURLs are reported.
class CSSCoverage
class CSSCoverage {}
Modifiers
@public
constructor
constructor(client: CDPSession);
method start
start: (options?: { resetOnNavigation?: boolean }) => Promise<void>;
method stop
stop: () => Promise<CoverageEntry[]>;
class CustomError
class CustomError extends Error {}
Modifiers
@public
Deprecated
Do not use.
class Dialog
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>;
Parameter promptText
optional text that will be entered in the dialog prompt. Has no effect if the dialog's type is not
prompt
.Returns
A promise that resolves when the dialog has been accepted.
method defaultValue
defaultValue: () => string;
Returns
The default value of the prompt, or an empty string if the dialog is not a
prompt
.
method dismiss
dismiss: () => Promise<void>;
Returns
A promise which will resolve once the dialog has been dismissed
method message
message: () => string;
Returns
The message displayed in the dialog.
method type
type: () => Protocol.Page.DialogType;
Returns
The type of the dialog.
class ElementHandle
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;
method $
$: <Selector extends string>( selector: Selector) => Promise<ElementHandle<NodeFor<Selector>> | null>;
Queries the current element for an element matching the given selector.
Parameter selector
The selector to query for.
Returns
A element handle to the first element matching the given selector. Otherwise,
null
.
method $$
$$: <Selector extends string>( selector: Selector) => Promise<Array<ElementHandle<NodeFor<Selector>>>>;
Queries the current element for all elements matching the given selector.
Parameter selector
The selector to query for.
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 EvaluateFunc< [JSHandle<NodeFor<Selector>[]>, ...Params] > = EvaluateFunc<[JSHandle<NodeFor<Selector>[]>, ...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
The selector to query for.
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 EvaluateFunc< [ElementHandle<NodeFor<Selector>>, ...Params] > = EvaluateFunc<[ElementHandle<NodeFor<Selector>>, ...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
The selector to query for.
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 $x
$x: (expression: string) => Promise<Array<ElementHandle<Node>>>;
Parameter expression
Expression to evaluate
Deprecated
Use ElementHandle.$$ with the
xpath
prefix.Example:
await elementHandle.$$('xpath/' + xpathExpression)
The method evaluates the XPath expression relative to the elementHandle. If
xpath
starts with//
instead of.//
, the dot will be appended automatically.If there are no such elements, the method will resolve to an empty array.
method asElement
asElement: () => ElementHandle<ElementType> | null;
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 visible.
method boxModel
boxModel: () => Promise<BoxModel | null>;
This method returns boxes of the element, or
null
if the element is not visible.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?: 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
contentFrame: () => Promise<Frame | null>;
Resolves to the content frame for element handles referencing iframe nodes, or null otherwise
method drag
drag: ( this: ElementHandle<Element>, target: Point) => Promise<Protocol.Input.DragData>;
This method creates and captures a dragevent from the element.
method dragAndDrop
dragAndDrop: ( this: ElementHandle<Element>, target: ElementHandle<Node>, options?: { delay: number }) => Promise<void>;
This method triggers a dragenter, dragover, and drop on the element.
method dragEnter
dragEnter: ( this: ElementHandle<Element>, data?: Protocol.Input.DragData) => Promise<void>;
This method creates a
dragenter
event on the element.
method dragOver
dragOver: ( this: ElementHandle<Element>, data?: Protocol.Input.DragData) => Promise<void>;
This method creates a
dragover
event on the element.
method drop
drop: ( this: ElementHandle<Element>, data?: Protocol.Input.DragData) => Promise<void>;
This method triggers a drop on the element.
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 isIntersectingViewport
isIntersectingViewport: ( this: ElementHandle<Element>, options?: { threshold?: number }) => Promise<boolean>;
Resolves to true if the element is visible in the current viewport.
method press
press: (key: KeyInput, options?: PressOptions) => 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: ( this: ElementHandle<Element>, options?: ScreenshotOptions) => Promise<string | Buffer>;
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 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 type
type: (text: string, options?: { delay: number }) => 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.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
uploadFile: ( this: ElementHandle<HTMLInputElement>, ...filePaths: string[]) => Promise<void>;
This method expects
elementHandle
to point to an input element.Parameter filePaths
Sets the value of the file input to these paths. If a path is relative, then it is resolved against the current working directory. Note 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();})();
method waitForXPath
waitForXPath: ( xpath: string, options?: { visible?: boolean; hidden?: boolean; timeout?: number }) => Promise<ElementHandle<Node> | null>;
Parameter xpath
A xpath of an element to wait for
Parameter options
Optional waiting parameters
Returns
Promise which resolves when element specified by xpath string is added to DOM. Resolves to
null
if waiting forhidden: true
and xpath is not found in DOM.Remarks
The optional Argument
options
have properties:-
visible
: A boolean to 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
: A boolean 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
: A number which is 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.Deprecated
Use ElementHandle.waitForSelector with the
xpath
prefix.Example:
await elementHandle.waitForSelector('xpath/' + xpathExpression)
The method evaluates the XPath expression relative to the elementHandle.
Wait for the
xpath
within the element. If at the moment of calling the method thexpath
already exists, the method will return immediately. If thexpath
doesn't appear after thetimeout
milliseconds of waiting, the function will throw.If
xpath
starts with//
instead of.//
, the dot will be appended automatically.This method works across navigation.
import puppeteer from 'puppeteer';(async () => {const browser = await puppeteer.launch();const page = await browser.newPage();let currentURL;page.waitForXPath('//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 implements CommonEventEmitter {}
method addListener
addListener: (event: EventType, handler: Handler<any>) => EventEmitter;
Add an event listener.
Deprecated
please use EventEmitter.on instead.
method emit
emit: (event: EventType, eventData?: unknown) => boolean;
Emit an event and call any associated listeners.
Parameter event
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: (event: EventType) => number;
Gets the number of listeners for a given event.
Parameter event
the event to get the listener count for
Returns
the number of listeners bound to the given event
method off
off: (event: EventType, handler: Handler<any>) => EventEmitter;
Remove an event listener from firing.
Parameter event
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: (event: EventType, handler: Handler<any>) => EventEmitter;
Bind an event listener to fire when an event occurs.
Parameter event
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: (event: EventType, handler: Handler<any>) => EventEmitter;
Like
on
but the listener will only be fired once and then it will be removed.Parameter event
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: (event?: EventType) => EventEmitter;
Removes all listeners. If given an event argument, it will remove only listeners for that event.
Parameter event
the event to remove listeners for.
Returns
this
to enable you to chain method calls.
method removeListener
removeListener: (event: EventType, handler: Handler<any>) => EventEmitter;
Remove an event listener.
Deprecated
please use EventEmitter.off instead.
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: (filePaths: string[]) => Promise<void>;
Accept the file chooser request with given paths.
Parameter filePaths
If some of the
filePaths
are relative paths, then they are resolved relative to the current working directory.
method cancel
cancel: () => void;
Closes the file chooser without selecting any files.
method isMultiple
isMultiple: () => boolean;
Whether file chooser allow for multiple file selection.
class Frame
class Frame {}
Represents a DOM frame.
To understand frames, you can think of frames as
<iframe>
elements. Just like iframes, frames can be nested, and when JavaScript is executed in a frame, the JavaScript does not effect frames inside the ambient frame the JavaScript executes in.Remarks
Frame lifecycles are controlled by three events that are all dispatched on the parent page:
- PageEmittedEvents.FrameAttached - PageEmittedEvents.FrameNavigated - PageEmittedEvents.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
method $
$: <Selector extends string>( selector: Selector) => Promise<ElementHandle<NodeFor<Selector>> | null>;
Queries the frame for an element matching the given selector.
Parameter selector
The selector to query for.
Returns
A element handle to the first element matching the given selector. Otherwise,
null
.
method $$
$$: <Selector extends string>( selector: Selector) => Promise<Array<ElementHandle<NodeFor<Selector>>>>;
Queries the frame for all elements matching the given selector.
Parameter selector
The selector to query for.
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 EvaluateFunc<[NodeFor<Selector>[], ...Params]> = EvaluateFunc< [NodeFor<Selector>[], ...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 frame.
If the given function returns a promise, then this method will wait till the promise resolves.
Parameter selector
The selector to query for.
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 EvaluateFunc< [ElementHandle<NodeFor<Selector>>, ...Params] > = EvaluateFunc<[ElementHandle<NodeFor<Selector>>, ...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 frame.
If the given function returns a promise, then this method will wait till the promise resolves.
Parameter selector
The selector to query for.
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 $x
$x: (expression: string) => Promise<Array<ElementHandle<Node>>>;
Parameter expression
the XPath expression to evaluate.
Deprecated
Use Frame.$$ with the
xpath
prefix.Example:
await frame.$$('xpath/' + xpathExpression)
This method evaluates the given XPath expression and returns the results. If
xpath
starts with//
instead of.//
, the dot will be appended automatically.
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
<link rel="stylesheet">
tag into the page with the desired URL or a<style type="text/css">
tag with the content.Returns
An element handle to the loaded
<link>
or<style>
element.
method childFrames
childFrames: () => Frame[];
Returns
An array of child frames.
method click
click: ( selector: string, options?: { delay?: number; button?: MouseButton; clickCount?: number }) => 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>;
Returns
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 the context of this frame.
See Also
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 Also
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 goto
goto: ( url: string, options?: { referer?: string; referrerPolicy?: string; timeout?: number; waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[]; }) => Promise<HTTPResponse | null>;
Navigates a frame to the given url.
Parameter url
the URL to navigate the frame to. This should include the scheme, e.g.
https://
.Parameter options
navigation options.
waitUntil
is useful to define when the navigation should be considered successful - see the docs for PuppeteerLifeCycleEvent for more details.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
This method will throw an error if:
- there's an SSL error (e.g. in case of self-signed certificates). - target URL is invalid. - the
timeout
is exceeded during navigation. - the remote server does not respond or is unreachable. - the main resource failed to load.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.
Remarks
Navigation to
about:blank
or navigation to the same URL with a different hash will succeed and returnnull
.:::warning
Headless mode doesn't support navigation to a PDF document. See the upstream issue.
:::
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;
Returns
true
if the frame has been detached. Otherwise,false
.
method isOOPFrame
isOOPFrame: () => boolean;
Returns
true
if the frame is an out-of-process (OOP) frame. Otherwise,false
.
method name
name: () => string;
Returns
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.
method page
page: () => Page;
Returns
The page associated with the frame.
method parentFrame
parentFrame: () => Frame | null;
Returns
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
setContent: ( html: string, options?: { timeout?: number; waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[]; }) => 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>;
Returns
the frame's title.
method type
type: ( selector: string, text: string, options?: { delay: number }) => 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
url: () => string;
Returns
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
waitForNavigation: (options?: { timeout?: number; waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[];}) => 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 when the navigation is consided finished.
Returns
a promise that resolves when the frame navigates to a new URL.
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();})();
method waitForTimeout
waitForTimeout: (milliseconds: number) => Promise<void>;
Parameter milliseconds
the number of milliseconds to wait.
Remarks
It's generally recommended to not wait for a number of seconds, but instead use Frame.waitForSelector, Frame.waitForXPath or Frame.waitForFunction to wait for exactly the conditions you want.
Example 1
Wait for 1 second:
await frame.waitForTimeout(1000);Deprecated
Replace with
new Promise(r => setTimeout(r, milliseconds));
.Causes your script to wait for the given number of milliseconds.
method waitForXPath
waitForXPath: ( xpath: string, options?: WaitForSelectorOptions) => Promise<ElementHandle<Node> | null>;
Parameter xpath
the XPath expression to wait for.
Parameter options
options to configure the visibility of the element and how long to wait before timing out.
Deprecated
Use Frame.waitForSelector with the
xpath
prefix.Example:
await frame.waitForSelector('xpath/' + xpathExpression)
The method evaluates the XPath expression relative to the Frame. If
xpath
starts with//
instead of.//
, the dot will be appended automatically.Wait for the
xpath
to appear in page. If at the moment of calling the method thexpath
already exists, the method will return immediately. If the xpath doesn't appear after thetimeout
milliseconds of waiting, the function will throw.For a code example, see the example for Frame.waitForSelector. That function behaves identically other than taking a CSS selector rather than an XPath.
class HTTPRequest
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_3;
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;
Returns
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;
Returns
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
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 finalizeInterceptions
finalizeInterceptions: () => Promise<void>;
Awaits pending interception handlers and then decides how to fulfill the request interception.
method frame
frame: () => Frame | null;
Returns
the frame that initiated the request, or null if navigating to error pages.
method headers
headers: () => Record<string, string>;
Returns
an object with HTTP headers associated with the request. All header names are lower-case.
method initiator
initiator: () => Protocol.Network.Initiator;
Returns
the initiator of the request.
method interceptResolutionState
interceptResolutionState: () => InterceptResolutionState;
Returns
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;
Returns
true
if the intercept resolution has already been handled,false
otherwise.
method isNavigationRequest
isNavigationRequest: () => boolean;
Returns
true if the request is the driver of the current frame's navigation.
method method
method: () => string;
Returns
the method used (
GET
,POST
, etc.)
method postData
postData: () => string | undefined;
Returns
the request's post body, if any.
method redirectChain
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
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
response: () => HTTPResponse | null;
Returns
A matching
HTTPResponse
object, or null if the response has not been received yet.
method responseForRequest
responseForRequest: () => Partial<ResponseForRequest> | null;
Returns
The
ResponseForRequest
that gets used if the interception is allowed to respond (ie,abort()
is not called).
method url
url: () => string;
Returns
the URL of the request
class HTTPResponse
class HTTPResponse {}
The HTTPResponse class represents responses which are received by the Page class.
Modifiers
@public
method buffer
buffer: () => Promise<Buffer>;
Returns
Promise which resolves to a buffer with response body.
method frame
frame: () => Frame | null;
Returns
A Frame that initiated this response, or
null
if navigating to error pages.
method fromCache
fromCache: () => boolean;
Returns
True if the response was served from either the browser's disk cache or memory cache.
method fromServiceWorker
fromServiceWorker: () => boolean;
Returns
True if the response was served by a service worker.
method headers
headers: () => Record<string, string>;
Returns
An object with HTTP headers associated with the response. All header names are lower-case.
method json
json: () => Promise<any>;
Returns
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;
Returns
True if the response was successful (status in the range 200-299).
method remoteAddress
remoteAddress: () => RemoteAddress;
Returns
The IP address and port number used to connect to the remote server.
method request
request: () => HTTPRequest;
Returns
A matching HTTPRequest object.
method securityDetails
securityDetails: () => SecurityDetails | null;
Returns
SecurityDetails if the response was received over the secure connection, or
null
otherwise.
method status
status: () => number;
Returns
The status code of the response (e.g., 200 for a success).
method statusText
statusText: () => string;
Returns
The status text of the response (e.g. usually an "OK" for a success).
method text
text: () => Promise<string>;
Returns
Promise which resolves to a text representation of response body.
method timing
timing: () => Protocol.Network.ResourceTiming | null;
Returns
Timing information related to the response.
method url
url: () => string;
Returns
The URL of the response.
class JSCoverage
class JSCoverage {}
Modifiers
@public
constructor
constructor(client: CDPSession);
method start
start: (options?: { resetOnNavigation?: boolean; reportAnonymousScripts?: boolean; includeRawScriptCoverage?: boolean; useBlockCoverage?: boolean;}) => Promise<void>;
method stop
stop: () => Promise<JSCoverageEntry[]>;
class JSHandle
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 [__JSHandleSymbol]
[__JSHandleSymbol]?: {};
Used for nominally typing JSHandle.
method asElement
asElement: () => ElementHandle<Node> | null;
Returns
Either
null
or the handle itself if the handle is an instance of ElementHandle.
method dispose
dispose: () => Promise<void>;
Releases the object referenced by the handle for garbage collection.
method evaluate
evaluate: < Params extends unknown[], Func extends EvaluateFunc<[this, ...Params]> = EvaluateFunc< [this, ...Params] >>( pageFunction: Func | string, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
Evaluates the given function with the current handle as its first argument.
See Also
ExecutionContext.evaluate for more details.
method evaluateHandle
evaluateHandle: < Params extends unknown[], Func extends EvaluateFunc<[this, ...Params]> = EvaluateFunc< [this, ...Params] >>( pageFunction: Func | string, ...args: Params) => Promise<HandleFor<Awaited<ReturnType<Func>>>>;
Evaluates the given function with the current handle as its first argument.
See Also
ExecutionContext.evaluateHandle for more details.
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
jsonValue: () => Promise<T>;
Returns
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
remoteObject: () => Protocol.Runtime.RemoteObject;
Provides access to the [Protocol.Runtime.RemoteObject](https://chromedevtools.github.io/devtools-protocol/tot/Runtime/#type-RemoteObject) backing this handle.
method toString
toString: () => string;
Returns a string representation of the JSHandle.
Remarks
Useful during debugging.
class Keyboard
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
down: ( key: KeyInput, options?: { text?: string; commands?: string[] }) => 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
press: ( key: KeyInput, options?: { delay?: number; text?: string; commands?: string[] }) => 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
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
type: (text: string, options?: { delay?: number }) => 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
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 Mouse
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
](#pagemouse).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
click: ( x: number, y: number, options?: MouseOptions & { delay?: number }) => 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
Optional
MouseOptions
.
method down
down: (options?: MouseOptions) => Promise<void>;
Dispatches a
mousedown
event.Parameter options
Optional
MouseOptions
.
method drag
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
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
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
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
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
move: (x: number, y: number, options?: { steps?: number }) => Promise<void>;
Dispatches a
mousemove
event.Parameter x
Horizontal position of the mouse.
Parameter y
Vertical position of the mouse.
Parameter options
Optional object. If specified, the
steps
property sends intermediatemousemove
events when set to1
(default).
method up
up: (options?: MouseOptions) => Promise<void>;
Dispatches a
mouseup
event.Parameter options
Optional
MouseOptions
.
method wheel
wheel: (options?: 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
class Page extends EventEmitter {}
Page provides methods to interact with a single tab or extension background page in Chromium.
:::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 PageEmittedEvents 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 Page.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;
property coverage
readonly coverage: Coverage;
property keyboard
readonly keyboard: Keyboard;
property mouse
readonly mouse: Mouse;
property touchscreen
readonly touchscreen: Touchscreen;
property tracing
readonly tracing: Tracing;
method $
$: <Selector extends string>( selector: Selector) => Promise<ElementHandle<NodeFor<Selector>> | null>;
Runs
document.querySelector
within the page. If no element matches the selector, the return value resolves tonull
.Parameter selector
A
selector
to query page for selector to query page for.
method $$
$$: <Selector extends string>( selector: Selector) => Promise<Array<ElementHandle<NodeFor<Selector>>>>;
The method runs
document.querySelectorAll
within the page. If no elements match the selector, the return value resolves to[]
.Parameter selector
A
selector
to query page forRemarks
Shortcut for Page.mainFrame().$$(selector).
method $$eval
$$eval: < Selector extends string, Params extends unknown[], Func extends EvaluateFunc<[NodeFor<Selector>[], ...Params]> = EvaluateFunc< [NodeFor<Selector>[], ...Params] >>( selector: Selector, pageFunction: Func | string, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
This method runs
Array.from(document.querySelectorAll(selector))
within the page and passes the result as the first argument to thepageFunction
.Parameter selector
the selector to query for
Parameter pageFunction
the function to be evaluated in the page context. Will be passed the result of
Array.from(document.querySelectorAll(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
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
// if you don't provide HTMLInputElement here, TS will error// as `value` is not on `Element`await page.$$eval('input', (elements: HTMLInputElement[]) => {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
// 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 allInputValues = await page.$$eval<string[]>('input',(elements: HTMLInputElement[]) => elements.map(e => e.textContent));
method $eval
$eval: < Selector extends string, Params extends unknown[], Func extends EvaluateFunc< [ElementHandle<NodeFor<Selector>>, ...Params] > = EvaluateFunc<[ElementHandle<NodeFor<Selector>>, ...Params]>>( selector: Selector, pageFunction: Func | string, ...args: Params) => Promise<Awaited<ReturnType<Func>>>;
This method runs
document.querySelector
within the page and passes the result as the first argument to thepageFunction
.Parameter selector
the selector to query for
Parameter pageFunction
the function to be evaluated in the page context. Will be passed the result of
document.querySelector(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 $x
$x: (expression: string) => Promise<Array<ElementHandle<Node>>>;
The method evaluates the XPath expression relative to the page document as its context node. If there are no such elements, the method resolves to an empty array.
Parameter expression
Expression to evaluate
Remarks
Shortcut for Page.mainFrame().$x(expression).
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: {