Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Puppeteer Puppeteer Bidi Page

From Leeroopedia
Property Value
Implementation BidiPage
Source File packages/puppeteer-core/src/bidi/Page.ts
Repository puppeteer/puppeteer
Lines 1208
License Apache-2.0
Copyright 2022 Google Inc.

Overview

Description

BidiPage is the WebDriver BiDi implementation of Puppeteer's Page abstract class. It is the central high-level object representing a single browser tab or page. The class is responsible for coordinating frame management, input devices, network interception, viewport/emulation settings, cookie management, screenshots, PDF generation, and page lifecycle operations.

Key responsibilities:

  • Frame management: Creates and manages the main BidiFrame and provides access to all frames via frames(). Traverses frame hierarchy recursively.
  • Input devices: Instantiates BidiKeyboard, BidiMouse, and BidiTouchscreen and exposes them as page.keyboard, page.mouse, and page.touchscreen.
  • Navigation: reload(), goBack(), goForward() with wait conditions.
  • Viewport and emulation: setViewport() with BiDi-native viewport/DPR/orientation support (falls back to CDP emulation manager when CDP is available). Also supports emulateMediaType(), emulateMediaFeatures(), emulateTimezone(), emulateIdleState(), emulateVisionDeficiency(), emulateCPUThrottling(), emulateNetworkConditions().
  • User agent: setUserAgent() with client hints override support.
  • Cookie management: Full cookie CRUD via cookies(), setCookie(), deleteCookie() using BiDi storage commands. Includes domain/path matching logic per RFC 6265 and support for Chrome-specific cookie extensions via the goog: prefix.
  • Network interception: setRequestInterception() and authenticate() using BiDi network intercept phases (beforeRequestSent, authRequired).
  • Screenshots: _screenshot() using browsingContext.captureScreenshot with support for clip regions, viewport/document origin, and quality settings.
  • PDF generation: pdf() and createPDFStream() using browsingContext.print.
  • Script evaluation: evaluateOnNewDocument() and removeScriptToEvaluateOnNewDocument() via preload scripts.
  • Workers: Tracks web workers via WorkerCreated/WorkerDestroyed events.
  • File chooser: waitForFileChooser() listening for input.fileDialogOpened.
  • Bluetooth: Exposes bluetooth emulation from the browsing context.

The module also exports several cookie conversion utility functions for translating between BiDi and CDP cookie formats: bidiToPuppeteerCookie(), convertCookiesSameSiteCdpToBiDi(), convertCookiesExpiryCdpToBiDi(), convertCookiesPartitionKeyFromPuppeteerToBiDi(), and cdpSpecificCookiePropertiesFromPuppeteerToBidi().

Usage

BidiPage instances are created internally by BidiBrowserContext when a new browsing context is created. Users obtain page instances via browser.newPage() or browserContext.newPage().

Code Reference

Source Location

packages/puppeteer-core/src/bidi/Page.ts (GitHub)

Signature

export class BidiPage extends Page {
  static from(
    browserContext: BidiBrowserContext,
    browsingContext: BrowsingContext,
  ): BidiPage;

  readonly keyboard: BidiKeyboard;
  readonly mouse: BidiMouse;
  readonly touchscreen: BidiTouchscreen;
  readonly tracing: Tracing;
  readonly coverage: Coverage;

  override browser(): BidiBrowser;
  override browserContext(): BidiBrowserContext;
  override mainFrame(): BidiFrame;
  override frames(): BidiFrame[];
  override isClosed(): boolean;
  override async close(options?: {runBeforeUnload?: boolean}): Promise<void>;
  override async reload(options?: ReloadOptions): Promise<BidiHTTPResponse | null>;
  override async setViewport(viewport: Viewport | null): Promise<void>;
  override viewport(): Viewport | null;
  override async pdf(options?: PDFOptions): Promise<Uint8Array>;
  override async createPDFStream(options?: PDFOptions): Promise<ReadableStream<Uint8Array>>;
  override async cookies(...urls: string[]): Promise<Cookie[]>;
  override async setCookie(...cookies: CookieParam[]): Promise<void>;
  override async deleteCookie(...cookies: DeleteCookiesRequest[]): Promise<void>;
  override async setRequestInterception(enable: boolean): Promise<void>;
  override async authenticate(credentials: Credentials | null): Promise<void>;
  override async setUserAgent(userAgentOrOptions: string | {...}): Promise<void>;
  override async setGeolocation(options: GeolocationOptions): Promise<void>;
  override async setJavaScriptEnabled(enabled: boolean): Promise<void>;
  override async evaluateOnNewDocument<Params, Func>(
    pageFunction: Func | string, ...args: Params
  ): Promise<NewDocumentScriptEvaluation>;
  override async exposeFunction<Args, Ret>(name: string, pptrFunction: Function): Promise<void>;
  override async bringToFront(): Promise<void>;
  override async goBack(options?: WaitForOptions): Promise<HTTPResponse | null>;
  override async goForward(options?: WaitForOptions): Promise<HTTPResponse | null>;
  override async setCacheEnabled(enabled?: boolean): Promise<void>;
  override async setOfflineMode(enabled: boolean): Promise<void>;
  override workers(): BidiWebWorker[];
  get isNetworkInterceptionEnabled(): boolean;
}

Import

import {BidiPage} from './Page.js';

I/O Contract

Inputs

Parameter Type Description
browserContext BidiBrowserContext The browser context that owns this page
browsingContext BrowsingContext The low-level BiDi browsing context for the page

Key Method Parameters

Method Parameter Type Description
setViewport viewport null Viewport dimensions, DPR, orientation, hasTouch
pdf options PDFOptions PDF generation options (margin, landscape, page size, scale, etc.)
setCookie cookies CookieParam[] Cookies to set with name, value, domain, path, etc.
setGeolocation options GeolocationOptions latitude, longitude, accuracy
setUserAgent userAgentOrOptions object User agent string or options with userAgent, userAgentMetadata, platform
authenticate credentials null Username/password for HTTP auth, or null to disable

Outputs

Method Return Type Description
mainFrame BidiFrame The page's main frame
frames BidiFrame[] All frames including main frame and nested iframes
reload null> Response after reload
pdf Promise<Uint8Array> PDF binary data
cookies Promise<Cookie[]> Cookies matching the specified URLs
viewport null Current viewport settings
isClosed boolean Whether the page has been closed
workers BidiWebWorker[] Active web workers

Usage Examples

// Create a page and navigate
const page = await browser.newPage();
await page.goto('https://example.com');

// Set viewport
await page.setViewport({width: 1280, height: 720, deviceScaleFactor: 2});

// Generate PDF
const pdfBuffer = await page.pdf({
  format: 'A4',
  printBackground: true,
  margin: {top: '1cm', bottom: '1cm'},
});

// Cookie management
await page.setCookie({
  name: 'session',
  value: 'abc123',
  domain: '.example.com',
  path: '/',
  httpOnly: true,
  secure: true,
});
const cookies = await page.cookies();

// Request interception with authentication
await page.authenticate({username: 'user', password: 'pass'});

// Emulation
await page.setGeolocation({latitude: 51.5074, longitude: -0.1278});
await page.emulateTimezone('Europe/London');
await page.setJavaScriptEnabled(false);

// Screenshot
const screenshot = await page.screenshot({
  type: 'png',
  clip: {x: 0, y: 0, width: 800, height: 600},
});

// Evaluate script on every new document
await page.evaluateOnNewDocument(() => {
  Object.defineProperty(navigator, 'webdriver', {get: () => false});
});

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment