Implementation:Puppeteer Puppeteer Cdp Page
| Property | Value |
|---|---|
| sources | packages/puppeteer-core/src/cdp/Page.ts |
| domains | Page Management, CDP, Browser Automation |
| last_updated | 2026-02-12 00:00 GMT |
Overview
Description
The CdpPage class is the comprehensive CDP-specific implementation of the abstract Page base class. It is the central hub for interacting with a browser tab, orchestrating all sub-systems (frames, network, input, emulation, coverage, tracing) into a unified API.
Key responsibilities include:
- Page lifecycle -- Static
_create()factory method that initializes the page, sets up event listeners, and applies the default viewport. Handles page close, crash, and target destruction events. - Frame management -- Delegates to
FrameManagerfor frame tree operations, navigation, and content manipulation. Forwards frame events (attached, detached, navigated) as page events. - Network management -- Delegates to
NetworkManager(via FrameManager) for request interception, offline mode, network condition emulation, authentication, HTTP headers, user agent, and cache control. Forwards network events (request, response, requestfailed, requestfinished). - Input handling -- Provides keyboard, mouse, and touchscreen properties backed by
CdpKeyboard,CdpMouse, andCdpTouchscreen. - Emulation -- Delegates to
EmulationManagerfor viewport, timezone, geolocation, vision deficiency, CPU throttling, media features/type, idle state, JavaScript toggle, and focus emulation. - Cookie management -- Full cookie CRUD via
Network.getCookies,Network.setCookies, andNetwork.deleteCookieswith partition key support. - Screenshots and PDF -- Taking screenshots via
Page.captureScreenshotwith support for clip regions, format selection, quality, and transparent backgrounds. Generating PDFs viaPage.printToPDFwith streaming support. - Console and dialog handling -- Forwarding console API calls as
ConsoleMessageevents and JavaScript dialogs asCdpDialogevents. - Exposed functions -- Exposing Node.js functions to the page via runtime bindings.
- Web Workers -- Tracking web workers attached to the page via
CdpWebWorker. - Performance metrics -- Collecting performance metrics via
Performance.getMetrics. - Heap snapshots -- Capturing heap snapshots to files via
HeapProfiler. - Coverage and tracing -- Providing access to
CoverageandTracingsub-systems. - Bluetooth emulation -- Providing Bluetooth device emulation.
- Prerendering support -- Handling page activation from prerender state by swapping the primary target/session and re-initializing all sub-systems.
- Window management -- Getting and setting window bounds, resizing content, and bringing pages to front.
- Navigation -- Supporting
reload(),goBack(),goForward()via CDP Page and navigation history APIs. - File chooser interception -- Intercepting file chooser dialogs via
Page.setInterceptFileChooserDialog.
Usage
CdpPage instances are created via browser.newPage() or by accessing an existing target's page. The full Page API is the primary interface for all page-level automation.
Code Reference
Source Location: packages/puppeteer-core/src/cdp/Page.ts (1368 lines)
Signature:
export class CdpPage extends Page {
static async _create(
client: CdpCDPSession,
target: CdpTarget,
defaultViewport: Viewport | null,
): Promise<CdpPage>;
// Navigation
override async reload(options?: ReloadOptions): Promise<HTTPResponse | null>;
override async goBack(options?: WaitForOptions): Promise<HTTPResponse | null>;
override async goForward(options?: WaitForOptions): Promise<HTTPResponse | null>;
// Frames
override mainFrame(): CdpFrame;
override frames(): Frame[];
// Input
override get keyboard(): CdpKeyboard;
override get mouse(): CdpMouse;
override get touchscreen(): CdpTouchscreen;
// Emulation
override async setViewport(viewport: Viewport | null): Promise<void>;
override async setGeolocation(options: GeolocationOptions): Promise<void>;
override async emulateTimezone(timezoneId?: string): Promise<void>;
override async emulateMediaType(type?: string): Promise<void>;
override async emulateMediaFeatures(features?: MediaFeature[]): Promise<void>;
override async emulateCPUThrottling(factor: number | null): Promise<void>;
override async emulateVisionDeficiency(type?: string): Promise<void>;
override async setJavaScriptEnabled(enabled: boolean): Promise<void>;
// Network
override async setRequestInterception(value: boolean): Promise<void>;
override async setOfflineMode(enabled: boolean): Promise<void>;
override async authenticate(credentials: Credentials | null): Promise<void>;
override async setExtraHTTPHeaders(headers: Record<string, string>): Promise<void>;
override async setUserAgent(userAgent: string): Promise<void>;
// Cookies
override async cookies(...urls: string[]): Promise<Cookie[]>;
override async setCookie(...cookies: CookieParam[]): Promise<void>;
override async deleteCookie(...cookies: DeleteCookiesRequest[]): Promise<void>;
// Content
override async exposeFunction(name: string, pptrFunction: Function): Promise<void>;
override async removeExposedFunction(name: string): Promise<void>;
override async evaluateOnNewDocument(pageFunction: Function | string, ...args: unknown[]): Promise<NewDocumentScriptEvaluation>;
// Screenshots / PDF
override async pdf(options?: PDFOptions): Promise<Uint8Array>;
override async close(options?: { runBeforeUnload?: boolean }): Promise<void>;
// Coverage / Tracing / Metrics
override get coverage(): Coverage;
override get tracing(): Tracing;
override async metrics(): Promise<Metrics>;
// Workers
override workers(): CdpWebWorker[];
// Page state
override target(): CdpTarget;
override browser(): Browser;
override isClosed(): boolean;
override viewport(): Viewport | null;
}
Import:
import { CdpPage } from 'puppeteer-core/lib/cdp/Page.js';
I/O Contract
Inputs:
| Parameter | Type | Required | Description |
|---|---|---|---|
| client | CdpCDPSession |
Yes | The CDP session for the page's primary target |
| target | CdpTarget |
Yes | The target this page belongs to |
| defaultViewport | null | Yes | The default viewport to apply on creation |
| options (various) | varies | No | Operation-specific options for navigation, screenshots, PDF, emulation, etc. |
Outputs:
| Output | Type | Description |
|---|---|---|
| _create() | Promise<CdpPage> |
A fully initialized page instance |
| mainFrame() | CdpFrame |
The main frame of the page |
| frames() | Frame[] |
All frames in the page |
| metrics() | Promise<Metrics> |
Performance metrics (Timestamp, Documents, Nodes, JSHeapUsedSize, etc.) |
| cookies() | Promise<Cookie[]> |
Cookies for the specified URLs |
| pdf() | Promise<Uint8Array> |
PDF bytes of the page |
| workers() | CdpWebWorker[] |
Active web workers on the page |
Usage Examples
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Navigate and wait
await page.goto('https://example.com', { waitUntil: 'networkidle0' });
// Set viewport for mobile emulation
await page.setViewport({ width: 375, height: 812, isMobile: true });
// Take a screenshot
await page.screenshot({ path: 'screenshot.png', fullPage: true });
// Generate PDF
const pdf = await page.pdf({ format: 'A4', printBackground: true });
// Manage cookies
await page.setCookie({ name: 'token', value: 'abc123', domain: 'example.com' });
const cookies = await page.cookies();
await page.deleteCookie({ name: 'token' });
// Expose a function
await page.exposeFunction('sha256', text => crypto.createHash('sha256').update(text).digest('hex'));
const hash = await page.evaluate(async () => window.sha256('hello'));
// Handle dialogs
page.on('dialog', async dialog => {
console.log(dialog.message());
await dialog.accept();
});
// Request interception
await page.setRequestInterception(true);
page.on('request', request => {
if (request.resourceType() === 'image') request.abort();
else request.continue();
});
// Performance metrics
const metrics = await page.metrics();
console.log('JS Heap Used:', metrics.JSHeapUsedSize);
// Close the page
await page.close();
await browser.close();