Overview
Concrete function that creates a unified page snapshot using CDP (focus mode) or DOM traversal (background mode), with caching for reuse.
Description
The createSnapshot function is the unified entry point for page snapshot collection. It reads the automation mode and delegates to the appropriate backend: in focus mode it calls `snapshotManager.createSnapshot(tabId)` (CDP accessibility tree), in background mode it calls `requestDomSnapshot` (content script DOM traversal) and converts the result via `convertDomSnapshotToUnified`. The resulting `UnifiedSnapshot` contains a root `TextSnapshotNode`, an `idToNode` map for UID-based lookup, and the `tabId`. Snapshots are cached per tab (DOM cache for background mode, CDP cache in snapshotManager). The function clears the opposite cache to avoid confusion.
Usage
- Capture page state: `const snapshot = await createSnapshot(tabId)`
- Element lookup: combine with `getNodeByUid(tabId, uid)` after creating a snapshot.
- Formatting for LLM: pass the result to `formatSnapshot(snapshot)`.
Code Reference
Source Location
- Repository: AIPex
- File: packages/browser-runtime/src/automation/snapshot-provider.ts
- Lines: L175-212 (createSnapshot), L117-134 (convertDomSnapshotToUnified), L139-170 (requestDomSnapshot)
Signature
export async function createSnapshot(tabId: number): Promise<UnifiedSnapshot | null>
interface UnifiedSnapshot {
root: TextSnapshotNode;
idToNode: Map<string, TextSnapshotNode>;
tabId: number;
}
interface TextSnapshotNode {
id: string;
role: string;
name: string;
value?: string;
children: TextSnapshotNode[];
focused?: boolean;
disabled?: boolean;
expanded?: boolean;
checked?: boolean | "mixed";
pressed?: boolean | "mixed";
tagName?: string;
// ...
}
Import
import { createSnapshot } from "@aipexstudio/browser-runtime";
I/O Contract
Inputs
| Name |
Type |
Required |
Description
|
| tabId |
number |
Yes |
Target browser tab ID
|
Outputs
| Name |
Type |
Description
|
| returns |
null |
Snapshot with root node and idToNode map, or null on failure
|
Usage Examples
Capture and Format Snapshot
import { createSnapshot, formatSnapshot } from "@aipexstudio/browser-runtime";
const snapshot = await createSnapshot(tabId);
if (snapshot) {
const text = formatSnapshot(snapshot);
// Send formatted text to LLM as page context
console.log(text);
}
Background Mode (Auto-Selected)
// In background mode, createSnapshot internally:
// 1. Sends DOM_SNAPSHOT_MESSAGE to content script
// 2. Receives SerializedDomSnapshot
// 3. Converts to UnifiedSnapshot via convertDomSnapshotToUnified
// 4. Caches in domSnapshotCache
// 5. Clears CDP cache
// No fallback to CDP in background mode (strict silent)
Related Pages
Implements Principle
Uses Heuristics
Requires Environment
Page Connections
Double-click a node to navigate. Hold to expand connections.