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 Cdp Connection

From Leeroopedia
Property Value
sources packages/puppeteer-core/src/cdp/Connection.ts
domains CDP, WebSocket, Protocol Communication
last_updated 2026-02-12 00:00 GMT

Overview

Description

The Connection class is the low-level transport layer for all Chrome DevTools Protocol communication in Puppeteer. It manages the WebSocket connection to the browser, handles message serialization/deserialization, routes messages to the appropriate CDP sessions, and provides the foundation for all CDP commands.

Key responsibilities include:

  • Message transport -- Sending CDP commands as JSON over WebSocket via a ConnectionTransport abstraction, with optional delay for debugging.
  • Session management -- Creating, tracking, and routing messages to CdpCDPSession instances. Sessions are created automatically when Target.attachedToTarget events are received and removed on Target.detachedFromTarget.
  • Callback management -- Using a CallbackRegistry to track pending requests by ID, resolve them with responses, and reject them on errors or timeouts.
  • Connection lifecycle -- Handling connection close events, disposing all sessions, clearing callbacks, and emitting disconnect events.
  • Auto-attach tracking -- Differentiating between auto-attached targets and manually attached targets for proper target management.
  • Error handling -- Converting CDP protocol errors into appropriate Puppeteer error types (ConnectionClosedError, TargetCloseError).

The class also provides debug logging via the puppeteer:protocol:SEND and puppeteer:protocol:RECV debug namespaces.

Usage

The Connection class is instantiated internally by Puppeteer during puppeteer.launch() or puppeteer.connect(). All CDP commands flow through this class, either directly for browser-level commands or through CdpCDPSession instances for target-level commands.

Code Reference

Source Location: packages/puppeteer-core/src/cdp/Connection.ts (308 lines)

Signature:

export class Connection extends EventEmitter<CDPSessionEvents> {
  constructor(
    url: string,
    transport: ConnectionTransport,
    delay?: number,
    timeout?: number,
    rawErrors?: boolean,
    idGenerator?: () => number,
  );

  static fromSession(session: CDPSession): Connection | undefined;
  url(): string;
  send<T extends keyof ProtocolMapping.Commands>(
    method: T,
    params?: ProtocolMapping.Commands[T]['paramsType'][0],
    options?: CommandOptions,
  ): Promise<ProtocolMapping.Commands[T]['returnType']>;
  session(sessionId: string): CDPSession | null;
  async createSession(targetInfo: Protocol.Target.TargetInfo): Promise<CDPSession>;
  dispose(): void;
}

Import:

import { Connection } from 'puppeteer-core/lib/cdp/Connection.js';

I/O Contract

Inputs:

Parameter Type Required Description
url string Yes The WebSocket URL of the browser DevTools endpoint
transport ConnectionTransport Yes The underlying transport (e.g., WebSocket)
delay number No Delay in ms before processing each incoming message (default: 0)
timeout number No Default timeout in ms for CDP commands (default: 180000)
rawErrors boolean No Whether to pass raw CDP errors without reformatting (default: false)
idGenerator () => number No Custom ID generator for CDP message IDs

Outputs:

Output Type Description
send() return Promise<T> The typed CDP command response
session() null An existing CDP session by session ID, or null
createSession() Promise<CDPSession> A newly created CDP session attached to a target
url() string The WebSocket endpoint URL
getPendingProtocolErrors() Error[] All pending protocol errors across all sessions

Usage Examples

// Connection is typically created internally, but can be used directly
import { Connection } from 'puppeteer-core';

// Send a browser-level CDP command
const versionInfo = await connection.send('Browser.getVersion');
console.log(versionInfo.product);

// Create a session for a specific target
const session = await connection.createSession(targetInfo);

// Look up an existing session
const existingSession = connection.session(sessionId);

// Get the WebSocket URL
const wsUrl = connection.url();

// Check for pending protocol errors
const errors = connection.getPendingProtocolErrors();

// Close the connection
connection.dispose();

// Obtain a Connection from a CDPSession
const conn = Connection.fromSession(mySession);

Related Pages

Page Connections

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