> 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.3-playwright-layer-implementation.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 24.3 Playwright Layer Implementation

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

***

In the previous section, we analyzed the CDP low-level layer—directly controlling the browser via WebSocket. This section moves up to the Playwright layer, which is the main interface for Agents to interact with web pages: intelligent element locating, page snapshots, interactive operations, and state management.

***

## 24.3.1 Playwright Session Management

### Connection Reuse

Playwright connects to Chrome via CDP, but unlike `withCdpSocket()`'s one-time connections, Playwright requires **persistent connections** to maintain page state:

```typescript
// src/browser/pw-session.ts — Connection cache
let cached: ConnectedBrowser | null = null;
let connecting: Promise<ConnectedBrowser> | null = null;
```

Through `cached` and `connecting`, connection reuse is implemented—at any moment, only one Playwright-to-Chrome connection is maintained, and all operations share this connection.

### Page State Tracking

Each Page object is associated with a `PageState`, managed via `WeakMap`:

```typescript
// src/browser/pw-session.ts — Page state
type PageState = {
  console: BrowserConsoleMessage[];  // Console messages (max 500)
  errors: BrowserPageError[];        // Page errors (max 200)
  requests: BrowserNetworkRequest[]; // Network requests (max 500)
  requestIds: WeakMap<Request, string>;
  
  // Role Refs—identifiers for elements in page snapshots
  roleRefs?: Record<string, { role: string; name?: string; nth?: number }>;
  roleRefsMode?: "role" | "aria";
  roleRefsFrameSelector?: string;
};

const pageStates = new WeakMap<Page, PageState>();
```

> **Sidebar**: `WeakMap` is a special Map in JavaScript where keys are weak references—when the key object (here, Page) is garbage collected, the corresponding entry automatically disappears. This is perfect for managing page state: when Playwright destroys a Page object, the associated state data won't cause memory leaks.

### Role Refs Cache

Page snapshots generate **role references** (like `e1`, `e2`), which Agents use to manipulate elements. To maintain reference stability (even if Playwright returns different Page objects), there's also a target-level cache:

```typescript
const roleRefsByTarget = new Map<string, RoleRefsCacheEntry>();
const MAX_ROLE_REFS_CACHE = 50;
```

The cache key is `${cdpUrl}::${targetId}`, storing references for at most 50 targets, with FIFO eviction.

***

## 24.3.2 Role Snapshot

Role snapshot is the **core innovation** of OpenClaw's browser control—it converts a web page's accessibility tree into text representation readable by Agents, assigning each interactive element a short reference ID.

### Three Categories of ARIA Roles

```typescript
// src/browser/pw-role-snapshot.ts — Role classification
const INTERACTIVE_ROLES = new Set([
  "button", "link", "textbox", "checkbox", "radio",
  "combobox", "listbox", "menuitem", "option",
  "searchbox", "slider", "spinbutton", "switch", "tab", "treeitem",
]);

const CONTENT_ROLES = new Set([
  "heading", "cell", "gridcell", "columnheader", "rowheader",
  "listitem", "article", "region", "main", "navigation",
]);

const STRUCTURAL_ROLES = new Set([
  "generic", "group", "list", "table", "row", "rowgroup",
  "grid", "treegrid", "menu", "menubar", "toolbar", "tablist",
  "tree", "directory", "document", "application",
]);
```

> **Sidebar**: ARIA (Accessible Rich Internet Applications) is a W3C standard defining **semantic roles** for web elements. For example, a `<div>` can have `role="button"` to indicate it's a button, and `<input type="text">` automatically gets `role="textbox"`. Screen readers (like VoiceOver, NVDA) rely on these roles to describe page structure to visually impaired users. OpenClaw reuses this standard—Agents "see" pages through roles, just like screen readers do.

### Snapshot Format

A role snapshot output looks like this:

```
- navigation "Main Menu"
  - link "Home" [e1]
  - link "Products" [e2]
  - button "Cart (3)" [e3]
- main
  - heading "Welcome to Store" [level=1]
  - region "Featured"
    - link "Product A" [e4]
    - button "Add to Cart" [e5]
    - link "Product B" [e6]
    - button "Add to Cart" [e7]
  - textbox "Search..." [e8]
  - button "Search" [e9]
```

The `[e1]`, `[e2]` etc. in brackets are **role references**—Agents use `e3` in subsequent operations to click the "Cart" button.

### Reference Assignment and Deduplication

```typescript
// src/browser/pw-role-snapshot.ts — Reference tracker
function createRoleNameTracker(): RoleNameTracker {
  const counts = new Map<string, number>();
  const refsByKey = new Map<string, string[]>();
  return {
    getKey(role, name) { return `${role}:${name ?? ""}`; },
    getNextIndex(role, name) {
      const key = this.getKey(role, name);
      const current = counts.get(key) ?? 0;
      counts.set(key, current + 1);
      return current;
    },
    trackRef(role, name, ref) {
      const key = this.getKey(role, name);
      const refs = refsByKey.get(key) ?? [];
      refs.push(ref);
      refsByKey.set(key, refs);
    },
    getDuplicateKeys() { /* Find duplicate elements with same name and role */ },
  };
}
```

When a page has multiple buttons with the same name (like two "Add to Cart"), the tracker assigns them different `nth` indices to ensure unambiguous references.

### Snapshot Statistics

```typescript
export function getRoleSnapshotStats(snapshot: string, refs: RoleRefMap) {
  const interactive = Object.values(refs)
    .filter(r => INTERACTIVE_ROLES.has(r.role)).length;
  return {
    lines: snapshot.split("\n").length,
    chars: snapshot.length,
    refs: Object.keys(refs).length,
    interactive,  // Number of interactive elements
  };
}
```

***

## 24.3.3 Three Snapshot Modes

OpenClaw provides three page snapshot methods, each with different focuses:

### 1. AI Snapshot (Recommended)

```typescript
// src/browser/pw-tools-core.snapshot.ts — snapshotAiViaPlaywright
export async function snapshotAiViaPlaywright(opts) {
  const page = await getPageForTargetId(opts);
  const maybe = page as WithSnapshotForAI;
  
  // Use Playwright's built-in _snapshotForAI
  const result = await maybe._snapshotForAI({
    timeout: opts.timeoutMs ?? 5000,
    track: "response",
  });
  
  let snapshot = String(result?.full ?? "");
  // Truncate oversized snapshots
  if (limit && snapshot.length > limit) {
    snapshot = `${snapshot.slice(0, limit)}\n\n[...TRUNCATED - page too large]`;
  }
  
  // Build role references
  const built = buildRoleSnapshotFromAiSnapshot(snapshot);
  storeRoleRefsForTarget({ page, refs: built.refs, mode: "aria" });
  
  return { snapshot, refs: built.refs };
}
```

`_snapshotForAI` is an internal Playwright method (underscore prefix indicates non-public API) that returns an AI-optimized text representation of the page.

### 2. ARIA Snapshot

```typescript
// Get full accessibility tree via CDP Accessibility.getFullAXTree
export async function snapshotAriaViaPlaywright(opts) {
  const session = await page.context().newCDPSession(page);
  const res = await session.send("Accessibility.getFullAXTree");
  const nodes = formatAriaSnapshot(res.nodes, limit);
  return { nodes };
}
```

Directly retrieves Chrome's accessibility tree—most complete information but larger size.

### 3. Role Snapshot

```typescript
// Build role tree based on ARIA snapshot
export async function snapshotRoleViaPlaywright(opts) {
  const page = await getPageForTargetId(opts);
  const session = await page.context().newCDPSession(page);
  const res = await session.send("Accessibility.getFullAXTree");
  
  const built = buildRoleSnapshotFromAriaSnapshot(res.nodes, {
    interactive: opts.interactive,
    maxDepth: opts.maxDepth,
    compact: opts.compact,
  });
  
  storeRoleRefsForTarget({ page, refs: built.refs, mode: "role" });
  return { snapshot: built.snapshot, refs: built.refs, stats: built.stats };
}
```

Role Snapshot supports filtering options—can show only interactive elements, limit depth, compress structural nodes—suitable for Agents to quickly understand page actionable elements.

***

## 24.3.4 Playwright Tools Core

`pw-tools-core.ts` is a barrel file aggregating eight submodules:

```typescript
// src/browser/pw-tools-core.ts
export * from "./pw-tools-core.activity.js";
export * from "./pw-tools-core.downloads.js";
export * from "./pw-tools-core.interactions.js";
export * from "./pw-tools-core.responses.js";
export * from "./pw-tools-core.snapshot.js";
export * from "./pw-tools-core.state.js";
export * from "./pw-tools-core.storage.js";
export * from "./pw-tools-core.trace.js";
```

### interactions — Interactive Operations

Core interactive operations locate elements via **role references**:

```typescript
// src/browser/pw-tools-core.interactions.ts — click (simplified)
export async function clickViaPlaywright(opts: {
  cdpUrl: string;
  targetId?: string;
  ref: string;             // Role reference, e.g., "e3"
  doubleClick?: boolean;
  button?: "left" | "right" | "middle";
  modifiers?: Array<"Alt" | "Control" | "Meta" | "Shift">;
  timeoutMs?: number;
}) {
  const page = await getPageForTargetId(opts);
  ensurePageState(page);
  restoreRoleRefsForTarget({ cdpUrl: opts.cdpUrl, targetId: opts.targetId, page });
  
  const ref = requireRef(opts.ref);
  const locator = refLocator(page, ref);  // Get Playwright Locator via reference
  
  if (opts.doubleClick) {
    await locator.dblclick({ timeout, button: opts.button, modifiers: opts.modifiers });
  } else {
    await locator.click({ timeout, button: opts.button, modifiers: opts.modifiers });
  }
}
```

`refLocator(page, ref)` is the key bridge—it looks up reference `e3` in `PageState.roleRefs` to find `{ role: "button", name: "Cart (3)" }`, then constructs Playwright's `page.getByRole("button", { name: "Cart (3)" })` locator.

Complete set of interactive operations:

| Function                      | Purpose                       |
| ----------------------------- | ----------------------------- |
| `clickViaPlaywright`          | Click/double-click element    |
| `hoverViaPlaywright`          | Hover                         |
| `typeViaPlaywright`           | Type in input field           |
| `fillFormViaPlaywright`       | Batch fill form               |
| `selectOptionViaPlaywright`   | Select dropdown option        |
| `pressKeyViaPlaywright`       | Press key (e.g., Enter, Tab)  |
| `dragViaPlaywright`           | Drag                          |
| `scrollIntoViewViaPlaywright` | Scroll element into view      |
| `highlightViaPlaywright`      | Highlight element (debugging) |
| `setInputFilesViaPlaywright`  | File upload                   |
| `armFileUploadViaPlaywright`  | Prepare file selector         |
| `armDialogViaPlaywright`      | Prepare dialog handling       |

### downloads — Download Management

```typescript
export async function downloadViaPlaywright(opts) { /* Navigate to URL to trigger download */ }
export async function waitForDownloadViaPlaywright(opts) { /* Wait for download completion */ }
```

### state — Page State

```typescript
export async function navigateViaPlaywright(opts) { /* Navigate to URL */ }
export async function evaluateViaPlaywright(opts) { /* Execute JS */ }
export async function resizeViewportViaPlaywright(opts) { /* Resize viewport */ }
export async function setDeviceViaPlaywright(opts) { /* Emulate device */ }
export async function setGeolocationViaPlaywright(opts) { /* Set geolocation */ }
export async function emulateMediaViaPlaywright(opts) { /* Emulate media type */ }
```

### storage — Storage Management

```typescript
export async function cookiesGetViaPlaywright(opts) { /* Read cookies */ }
export async function cookiesSetViaPlaywright(opts) { /* Set cookies */ }
export async function cookiesClearViaPlaywright(opts) { /* Clear cookies */ }
export async function storageGetViaPlaywright(opts) { /* Read localStorage */ }
export async function storageSetViaPlaywright(opts) { /* Set localStorage */ }
export async function storageClearViaPlaywright(opts) { /* Clear localStorage */ }
```

### trace — Performance Tracing

```typescript
export async function traceStartViaPlaywright(opts) { /* Start recording Playwright Trace */ }
export async function traceStopViaPlaywright(opts) { /* Stop and save Trace file */ }
```

***

## 24.3.5 AI Assistance Module Aggregation

`pw-ai.ts` re-exports all Playwright operations as a unified API surface:

```typescript
// src/browser/pw-ai.ts — 60+ functions re-exported
export {
  // Session management
  getPageForTargetId, ensurePageState, closePlaywrightBrowserConnection,
  listPagesViaPlaywright, createPageViaPlaywright, refLocator,
  
  // Interactive operations
  clickViaPlaywright, hoverViaPlaywright, fillFormViaPlaywright,
  typeViaPlaywright, pressKeyViaPlaywright, dragViaPlaywright,
  
  // Snapshots
  snapshotAiViaPlaywright, snapshotAriaViaPlaywright, snapshotRoleViaPlaywright,
  takeScreenshotViaPlaywright, screenshotWithLabelsViaPlaywright,
  
  // State
  navigateViaPlaywright, evaluateViaPlaywright, resizeViewportViaPlaywright,
  
  // Storage
  cookiesGetViaPlaywright, storageGetViaPlaywright,
  
  // Network
  getConsoleMessagesViaPlaywright, getNetworkRequestsViaPlaywright,
  
  // ... and 60+ more functions
} from "./pw-tools-core.js";
```

***

## Summary of This Section

1. **Playwright connection reuse**—globally cache one persistent connection to Chrome, all operations share it
2. **Page state managed via WeakMap**—console messages, network requests, page errors each have capacity limits (500/500/200)
3. **Role snapshot is how Agents "see" web pages**—converts accessibility tree to indented text, assigns short reference IDs to each interactive element (like `e1`)
4. **Three snapshot modes**: AI Snapshot (Playwright built-in optimization), ARIA Snapshot (complete accessibility tree), Role Snapshot (filterable/compressible)
5. **All interactive operations locate via role references**—when Agents see `[e3]`, they use `ref: "e3"` to click, with `getByRole()` parsing underneath
6. **Tools core divided into eight major modules**: interactions, snapshots, downloads, responses, activity, state, storage, tracing
7. **`pw-ai.ts` aggregates 60+ Playwright operation functions**, providing a unified API surface for the browser server
