> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch24-browser-control/24.2-cdp-layer-implementation.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 24.2 CDP Layer Implementation

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~170k tokens, Output \~5k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

In the previous section, we learned about the overall architecture of browser control. This section dives deep into the CDP (Chrome DevTools Protocol) layer—how OpenClaw communicates with Chrome via WebSocket and executes low-level browser operations.

***

## 24.2.1 CDP Connection Management

### WebSocket URL Normalization

Chrome's CDP interface exposes the WebSocket URL through the `/json/version` endpoint. However, this URL may need normalization:

```typescript
// src/browser/cdp.ts — normalizeCdpWsUrl
export function normalizeCdpWsUrl(wsUrl: string, cdpUrl: string): string {
  const ws = new URL(wsUrl);
  const cdp = new URL(cdpUrl);
  
  // If ws is loopback but cdp is not → replace hostname
  // (remote Chrome may return 127.0.0.1 as ws address)
  if (isLoopbackHost(ws.hostname) && !isLoopbackHost(cdp.hostname)) {
    ws.hostname = cdp.hostname;
    ws.port = cdp.port;
    ws.protocol = cdp.protocol === "https:" ? "wss:" : "ws:";
  }
  
  // Protocol upgrade: if cdp is https, ws should be wss
  if (cdp.protocol === "https:" && ws.protocol === "ws:") {
    ws.protocol = "wss:";
  }
  
  // Pass authentication info
  if (!ws.username && !ws.password && (cdp.username || cdp.password)) {
    ws.username = cdp.username;
    ws.password = cdp.password;
  }
  
  // Pass query parameters
  for (const [key, value] of cdp.searchParams.entries()) {
    if (!ws.searchParams.has(key)) {
      ws.searchParams.append(key, value);
    }
  }
  return ws.toString();
}
```

This function handles common issues with remote CDP connections: Chrome typically returns `webSocketDebuggerUrl` as `ws://127.0.0.1:9222/...` (because Chrome only knows it's local), but if OpenClaw accesses remote Chrome through a reverse proxy or SSH tunnel, the URL needs to be replaced with the actual remote address.

### CDP Socket Wrapper

`withCdpSocket()` is the core primitive for CDP communication:

```typescript
// src/browser/cdp.helpers.ts — withCdpSocket (simplified)
export async function withCdpSocket<T>(
  wsUrl: string,
  fn: (send: CdpSendFn) => Promise<T>,
): Promise<T> {
  const ws = new WebSocket(wsUrl, { handshakeTimeout: 5000 });
  
  // Wait for connection to establish
  await new Promise((resolve, reject) => {
    ws.once("open", resolve);
    ws.once("error", reject);
  });
  
  // Create CDP command sender
  const { send, closeWithError } = createCdpSender(ws);
  
  try {
    return await fn(send);
  } finally {
    ws.close();
  }
}
```

`createCdpSender()` implements the CDP JSON-RPC protocol:

```typescript
// src/browser/cdp.helpers.ts — createCdpSender
function createCdpSender(ws: WebSocket) {
  let nextId = 1;
  const pending = new Map<number, Pending>();

  const send: CdpSendFn = (method, params?) => {
    const id = nextId++;
    ws.send(JSON.stringify({ id, method, params }));
    return new Promise((resolve, reject) => {
      pending.set(id, { resolve, reject });
    });
  };

  ws.on("message", (data) => {
    const parsed = JSON.parse(data) as CdpResponse;
    const p = pending.get(parsed.id);
    if (!p) return;
    pending.delete(parsed.id);
    if (parsed.error?.message) {
      p.reject(new Error(parsed.error.message));
    } else {
      p.resolve(parsed.result);
    }
  });
  
  return { send, closeWithError };
}
```

> **Sidebar**: CDP uses JSON-RPC over WebSocket protocol. Each request has an incrementing `id`, and the server replies with the same `id`, allowing the client to pair requests and responses via `id`. This is a classic **request-response multiplexing** pattern—a single WebSocket connection can carry multiple concurrent request/response pairs. The `pending` Map stores Promise callbacks for each incomplete request.

***

## 24.2.2 CDP Helper Functions

### Screenshots

```typescript
// src/browser/cdp.ts — captureScreenshot
export async function captureScreenshot(opts: {
  wsUrl: string;
  fullPage?: boolean;
  format?: "png" | "jpeg";
  quality?: number;
}): Promise<Buffer> {
  return await withCdpSocket(opts.wsUrl, async (send) => {
    await send("Page.enable");

    let clip;
    if (opts.fullPage) {
      // Get full page dimensions
      const metrics = await send("Page.getLayoutMetrics");
      const size = metrics?.cssContentSize ?? metrics?.contentSize;
      if (size.width > 0 && size.height > 0) {
        clip = { x: 0, y: 0, width: size.width, height: size.height, scale: 1 };
      }
    }

    const result = await send("Page.captureScreenshot", {
      format: opts.format ?? "png",
      quality: opts.format === "jpeg" ? opts.quality ?? 85 : undefined,
      fromSurface: true,
      captureBeyondViewport: true,
      ...(clip ? { clip } : {}),
    });

    return Buffer.from(result.data, "base64");
  });
}
```

The key to full-page screenshots: first use `Page.getLayoutMetrics` to get the page's complete content dimensions (which may be much larger than the viewport), then pass that dimension as the `clip` parameter to the screenshot command. `captureBeyondViewport: true` ensures content beyond the current viewport is captured.

### JavaScript Execution

```typescript
// src/browser/cdp.ts — evaluateJavaScript
export async function evaluateJavaScript(opts: {
  wsUrl: string;
  expression: string;
  awaitPromise?: boolean;
  returnByValue?: boolean;
}): Promise<{ result: CdpRemoteObject; exceptionDetails?: CdpExceptionDetails }> {
  return await withCdpSocket(opts.wsUrl, async (send) => {
    await send("Runtime.enable").catch(() => {});
    const evaluated = await send("Runtime.evaluate", {
      expression: opts.expression,
      awaitPromise: Boolean(opts.awaitPromise),
      returnByValue: opts.returnByValue ?? true,
      userGesture: true,           // Simulate user interaction context
      includeCommandLineAPI: true, // Enable $, $$, copy() debugging helpers
    });
    return { result: evaluated.result, exceptionDetails: evaluated.exceptionDetails };
  });
}
```

`userGesture: true` is important—certain browser APIs (like `navigator.clipboard.writeText()`, `Notification.requestPermission()`) require being called in a "user gesture" context. This parameter makes CDP simulate a user interaction environment.

### Tab Creation

```typescript
// src/browser/cdp.ts — createTargetViaCdp
export async function createTargetViaCdp(opts: {
  cdpUrl: string;
  url: string;
}): Promise<{ targetId: string }> {
  // Get browser-level WebSocket URL (not tab-level)
  const version = await fetchJson(appendCdpPath(opts.cdpUrl, "/json/version"));
  const wsUrl = normalizeCdpWsUrl(version.webSocketDebuggerUrl, opts.cdpUrl);
  
  return await withCdpSocket(wsUrl, async (send) => {
    const created = await send("Target.createTarget", { url: opts.url });
    return { targetId: created.targetId };
  });
}
```

Note that this uses the **browser-level** WebSocket (obtained via `/json/version`), not a tab-level WebSocket. `Target.createTarget` is a browser-level CDP command.

***

## 24.2.3 Target ID Management and Tab Operations

### What is Target ID

In CDP, each browser tab (as well as Service Workers, iframes, etc.) is a **Target**, identified by a unique `targetId`. OpenClaw uses `targetId` to locate and manipulate specific tabs.

### Fuzzy Matching

```typescript
// src/browser/target-id.ts — resolveTargetIdFromTabs
export function resolveTargetIdFromTabs(
  input: string,
  tabs: Array<{ targetId: string }>,
): TargetIdResolution {
  const needle = input.trim();
  
  // 1. Exact match
  const exact = tabs.find(t => t.targetId === needle);
  if (exact) return { ok: true, targetId: exact.targetId };
  
  // 2. Prefix match (case-insensitive)
  const matches = tabs
    .map(t => t.targetId)
    .filter(id => id.toLowerCase().startsWith(needle.toLowerCase()));
  
  if (matches.length === 1) return { ok: true, targetId: matches[0] };
  if (matches.length === 0) return { ok: false, reason: "not_found" };
  return { ok: false, reason: "ambiguous", matches };
}
```

The return type is a discriminated union:

```typescript
type TargetIdResolution =
  | { ok: true; targetId: string }
  | { ok: false; reason: "not_found" | "ambiguous"; matches?: string[] };
```

> **Sidebar**: Target ID is a UUID-format string generated internally by Chrome (e.g., `8D3E4F7A-2B1C-4D5E-9F0A-1B2C3D4E5F6A`). In conversations between Agents and users, passing the complete UUID is inconvenient. Prefix matching allows Agents to uniquely locate a tab using just the first few characters—similar to Git's short commit hash. An `ambiguous` result means the prefix matches multiple tabs, requiring a longer prefix.

### Tab List

Tab information is obtained via CDP's `/json/list` endpoint:

```typescript
// listTabs in server context (simplified)
const listTabs = async (): Promise<BrowserTab[]> => {
  if (!profile.cdpIsLoopback) {
    // Remote browser: list pages via Playwright
    const pages = await listPagesViaPlaywright({ cdpUrl: profile.cdpUrl });
    return pages.map(p => ({
      targetId: p.targetId,
      title: p.title,
      url: p.url,
      type: "page",
    }));
  }
  // Local browser: call CDP HTTP interface directly
  const tabs = await fetchJson(appendCdpPath(profile.cdpUrl, "/json/list"));
  return tabs.filter(t => t.type === "page").map(t => ({
    targetId: t.id,
    title: t.title,
    url: t.url,
    wsUrl: normalizeWsUrl(t.webSocketDebuggerUrl, profile.cdpUrl),
  }));
};
```

Differences in local vs. remote handling:

* **Local**: Direct HTTP call to `/json/list`, more efficient
* **Remote**: List pages via Playwright's persistent connection, avoiding establishing new ephemeral connections each time

***

## 24.2.4 Authentication and Security

Authentication in CDP communication is handled uniformly via `getHeadersWithAuth()`:

```typescript
// src/browser/cdp.helpers.ts — Auth header injection
export function getHeadersWithAuth(url: string, headers = {}) {
  // 1. Check Chrome Extension Relay authentication
  const relayHeaders = getChromeExtensionRelayAuthHeaders(url);
  const merged = { ...relayHeaders, ...headers };
  
  // 2. Check Basic Auth in URL
  const parsed = new URL(url);
  if (parsed.username || parsed.password) {
    const auth = Buffer.from(`${parsed.username}:${parsed.password}`)
      .toString("base64");
    return { ...merged, Authorization: `Basic ${auth}` };
  }
  
  return merged;
}
```

This supports three authentication methods:

1. **Chrome Extension Relay Token**—passed via custom header `x-openclaw-relay-token`
2. **URL Basic Auth**—format `http://user:pass@host:port/`
3. **No authentication**—local loopback connections typically don't need it

***

## Summary of This Section

1. **CDP communication is based on JSON-RPC over WebSocket**—each request/response is paired via incrementing `id`, supporting concurrent multiplexing
2. **WebSocket URL normalization** handles address replacement, protocol upgrade, and authentication passing for remote connections
3. **`withCdpSocket()` is a one-time connection pattern**—open WebSocket, execute operations, close, suitable for short-term operations like screenshots and JS execution
4. **Screenshots support full-page mode**—use `Page.getLayoutMetrics` to get complete content dimensions, `captureBeyondViewport` to capture content beyond viewport
5. **JS execution uses `userGesture: true`**—simulates user interaction context, unlocking restricted browser APIs
6. **Target ID supports prefix fuzzy matching**—Agents don't need to memorize complete UUIDs, similar to Git short hashes
7. **Three authentication methods**: Extension Relay Token, URL Basic Auth, no authentication
