puppeteer
- Version 23.5.1
- Published
- 341 kB
- 6 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
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
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: ConnectOptions) => Promise<Browser>;
Modifiers
@public
function defaultArgs
defaultArgs: (options?: BrowserLaunchArgumentOptions | undefined) => string[];
Modifiers
@public
function executablePath
executablePath: (channel?: ChromeReleaseChannel | undefined) => string;
Modifiers
@public
function launch
launch: (options?: PuppeteerLaunchOptions | undefined) => Promise<Browser>;
Modifiers
@public
function trimCache
trimCache: () => Promise<void>;
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>) => Promise<void>;
method touchStart
touchStart: (this: ElementHandle<Element>) => Promise<void>;
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