Skip to content
Projetos

Sobre

The AI-native browser automation library. Snapshot + ref targeting — born from OpenClaw, built for agents, by agents.

IA e aprendizado de máquina

Como estes números são medidos

Crescimento medido de estrelas

em 24 h
0
em 7 dias
0
em 15 dias
0
em 1 mês
+1

Variações líquidas em períodos sobrepostos, não totais diários. Medições ausentes ficam em branco. Estrelas indicam interesse, não qualidade.

README.md

Original

BrowserClaw

Live npm version License: MIT npm downloads GitHub stars

The browser tool, not the agent. You bring the brain.

The AI-native browser automation library — born from OpenClaw, built on Playwright, embeddable in any TS/Node agent loop. Snapshot + ref targeting: no CSS selectors, no XPath, no vision model — just numbered refs that map to interactive elements.

Most other tools in this space ship a complete AI agent: they take your task, own the LLM loop, decide what to click, and click it. Great — until you already have an agent. Then you've got two brains fighting over who's in charge.

browserclaw is just the eyes and hands. Call snapshot() and get an AI-readable text tree where every interactive element carries a numbered ref (e1, e2, …). The model reads text — the thing it's best at — and hands back a ref ID. browserclaw resolves that ref to one exact element through a Playwright locator and acts. Same page state → same ref → same result: deterministic targeting, no coordinate guessing, no LLM re-interpreting which element it meant. A ref stays with its element across snapshots, and once that element is gone the ref fails at once instead of clicking whatever took its place. The reasoning stays in your code.

import { BrowserClaw } from 'browserclaw';

const browser = await BrowserClaw.launch({ url: 'https://demo.playwright.dev/todomvc' });
try {
  const page = await browser.currentPage();
  await page.waitFor({ text: 'todos' });
  const { snapshot, refs } = await page.snapshot({ interactive: true });
  console.log(snapshot);
  const input = Object.entries(refs).find(
    ([, element]) => element.role === 'textbox' && element.name === 'What needs to be done?',
  );
  if (!input) throw new Error('Could not find the new to-do textbox');
  await page.type(input[0], 'Buy groceries', { submit: true });
} finally {
  await browser.stop();
}

The snapshot is the text your model reads. Each [ref=…] in it is a key in refs, such as e6: { role: 'textbox', name: 'What needs to be done?' }:

- link "real TodoMVC app." [ref=e3] [cursor=pointer]:
- textbox "What needs to be done?" [active] [ref=e6]
  - link "Remo H. Jansen" [ref=e10] [cursor=pointer]:
  - link "TodoMVC" [ref=e12] [cursor=pointer]:

Use it from your coding agent

Claude Code, Codex, Cursor and other coding agents can drive a browser with browserclaw from your project:

npm install browserclaw
npx skills add idan-rubin/browserclaw

Prefer plugins? In Claude Code, /plugin marketplace add idan-rubin/browserclaw, then /plugin install browserclaw@browserclaw. In Codex, codex plugin marketplace add idan-rubin/browserclaw, then codex plugin add browserclaw@browserclaw. Then ask your agent: Use browserclaw to open https://demo.playwright.dev/todomvc, add "Buy milk", and check that it appears.

The skill has the agent run npx browserclaw skill, which prints the guide for the version you installed, and npx browserclaw help page.click for any method. Unknown options fail with the right call instead of being ignored.

browserclaw starts its own browser with a separate profile, or connect()s to one you started with remote debugging. It is not a desktop browser that works inside your everyday signed-in tabs; for that, see ego lite in the comparison below.

Bring your own agent loop — or use ours

browserclaw never calls an LLM or decides anything; you do. The whole integration is snapshot in, ref out, act — here it is wired to a real model. Install @anthropic-ai/sdk and set ANTHROPIC_API_KEY and ANTHROPIC_MODEL to a model available to your account:

import { BrowserClaw } from 'browserclaw';
import Anthropic from '@anthropic-ai/sdk';

const llm = new Anthropic();
const model = process.env.ANTHROPIC_MODEL;
if (!model) throw new Error('Set ANTHROPIC_MODEL to a model available to your account');
const browser = await BrowserClaw.launch({ url: 'https://news.ycombinator.com' });
try {
  const page = await browser.currentPage();

  for (let step = 0; step < 20; step++) {
    const { snapshot } = await page.snapshot();
    const res = await llm.messages.create({
      model,
      max_tokens: 1024,
      system: 'You drive a browser. Reply with JSON: { "action": "click" | "type" | "done", "ref"?, "text"? }.',
      messages: [{ role: 'user', content: `Task: open the top story.\n\n${snapshot}` }],
    });
    const block = res.content[0];
    const action = JSON.parse(block.type === 'text' ? block.text : '{}');
    if (action.action === 'done') break;
    if (action.action === 'type') await page.type(action.ref, action.text);
    if (action.action === 'click') await page.click(action.ref);
  }
} finally {
  await browser.stop();
}

Swap Anthropic for any model — the snapshot is plain text in, a ref is plain text out. Layered, not bundled: the LLM, this library, and the agent are three independent pieces. Don't want to write the loop? Use browserclaw-agent — the open-source driver that adds obstacle recovery and learns a reusable skill per site. Bring your own brain, or use ours.

Why browserclaw?

browserclaw provides browser primitives you can call from an agent loop you already own:

  • Deterministic — refs resolve through Playwright locators and bound DOM identities, one ref → one element. No coordinate guessing, no LLM re-interpreting targets between calls.
  • Cheap & fast — a text snapshot is a fraction of the tokens of a screenshot, and there's no vision API round-trip in the targeting loop.
  • Reliable — built on Playwright's auto-wait and locator engine, not homegrown DOM poking.
  • Yours to compose — no framework opinions, no agent loop, no hosted platform. Drop it into whatever architecture you already have.

How browserclaw compares

Choose by the integration surface your application needs. Competitor details checked against their official documentation on October 10, 2026 (ego lite on November 24, 2026):

Tool Integration surface Action selection
browserclaw JS/TS library; caller owns the loop Snapshot refs → Playwright locators; no model calls inside the library
browser-use Python agent library; Python/TypeScript Cloud SDK for hosted tasks and browser infrastructure Agent-driven tasks, or caller-controlled managed browsers
Stagehand SDK with browser methods and AI primitives; local or Browserbase browsers Direct locators plus natural-language act, observe, and extract; repeated AI calls can be cached
Playwright MCP MCP tools; supports programmatic server creation Snapshot refs or selectors through Playwright tools
ego lite Desktop browser app for macOS and Windows; agent CLIs drive it through the ego-browser skill, inside your logged-in profile Agent-written JavaScript calling in-page tools (snapshot, click, fill); snapshot refs come from its customized Chromium engine

browserclaw exposes snapshots and actions directly in application code. It ships no agent loop or hosted browser service. browser-use, Stagehand, and Playwright MCP also support composing browser operations into your application; their APIs, hosting options, and model involvement differ.

ego lite solves a different problem. It is a browser you install so a coding agent on your own computer (Claude Code, Codex, Cursor) can work in the sites you are already signed in to, in its own workspace beside your tabs. If that is the job, use it. browserclaw is what you build with: an npm library that runs headless on a server, in CI, or in a container, against any Chromium-based browser, with your code deciding every action. By default it also blocks private-network addresses, including through redirects and in tabs a page opens (how it works).

Case studies

Two proof-of-concept products are built on browserclaw, through browserclaw-agent:

  • beelz.ai — bill pay. The agent is built to log in to a biller's own website, fill the payment form, and pay, with no per-provider integration.
  • tovli.ai — charitable giving. The agent is built to complete the donation form on each nonprofit's own website.

Try It Live — Or On Your Machine

browserclaw.org is an open-source playground — type a prompt and watch an AI agent drive a real browser with browserclaw, live. No setup, no API keys, just a text box and a browser stream. It runs on this library in production, and browserclaw stays current by syncing with the upstream OpenClaw browser SDK.

Want to run it yourself? The source is at github.com/idan-rubin/browserclaw-agent — spin it up with Docker or Node.js. Supports Groq, Gemini, OpenAI, and Anthropic out of the box.

Install

npm install browserclaw

Requires a Chromium-based browser installed on the system (Chrome, Brave, Edge, or Chromium). browserclaw auto-detects your installed browser — no need to install Playwright browsers separately.

How It Works

┌─────────────┐     snapshot()     ┌──────────────────────────────────────────┐
│  Web Page   │ ──────────────►    │  AI-readable text tree                   │
│             │                    │                                          │
│  [buttons]  │                    │  - heading "todos"                       │
│  [links]    │                    │  - textbox "What needs to be done?" [e1] │
│  [inputs]   │                    │  - link "Playwright" [e2]                │
└─────────────┘                    └──────────────┬───────────────────────────┘
                                                  │
                                          AI reads snapshot,
                                          decides: type in e1
                                                  │
┌─────────────┐   type('e1',...)   ┌──────────────▼──────────────────┐
│  Web Page   │ ◄──────────────    │  Ref "e1" resolves to a         │
│  (updated)  │                    │  Playwright locator — one ref,  │
│             │                    │  one exact element              │
└─────────────┘                    └─────────────────────────────────┘
  1. Snapshot a page → get an AI-readable text tree with numbered refs (e1, e2, e3...)
  2. AI reads the snapshot text and picks a ref to act on
  3. Actions target refs → browserclaw resolves each ref to a Playwright locator and executes the action

Refs stay put while the element lives. An element keeps its ref across snapshots, so a list that grows above it does not shift its number, and ids are never reused: an old ref can't land on a different element. When the element is gone, acting on its ref fails right away with a StaleRefError that says why (removed, document-replaced, frame-detached, expired), instead of waiting out a timeout. Refs inside iframes are plain eN too, and survive other frames navigating. The exception is a control Playwright cannot bind to an element (zero-size or pointer-events: none): its ref lasts only until the next snapshot.

API

Launch & Connect

// Launch a new Chrome instance (auto-detects Chrome/Brave/Edge/Chromium)
const browser = await BrowserClaw.launch({
  url: 'https://demo.playwright.dev/todomvc', // navigate initial tab (no extra tabs)
  headless: false, // default: false (visible window)
  executablePath: '...', // optional: specific browser path
  cdpPort: 9222, // default: first free of 9222-9226, 9229; a busy explicit port throws
  noSandbox: false, // default: false (set true for Docker/CI)
  ignoreHTTPSErrors: false, // default: false (set true for expired local dev certs)
  userDataDir: '...', // optional: custom user data directory
  profileName: 'browserclaw', // profile name in Chrome title bar
  profileColor: '#FF4500', // profile accent color (hex)
  chromeArgs: ['--start-maximized'], // additional Chrome flags
  isolated: true, // fresh per-run profile, auto-cleaned on stop()
  stealth: false, // default: false — inject JS patches (navigator.webdriver, plugins, WebGL vendor, …)
  ciDefaults: false, // default: false — adds CI-deterministic Chrome flags (may fingerprint as automation)
  recordVideo: { dir: './videos' }, // optional: record every page; videos flushed on page/context close
});

// Connect to an already-running Chrome instance and work in the tab that is in front
const browser = await BrowserClaw.connect('http://localhost:9222');
const page = await browser.currentPage();
await page.goto('https://demo.playwright.dev/todomvc'); // stays in that tab; browser.open(url) would add one

// Connect to an auth-protected CDP endpoint (e.g. an OpenClaw gateway)
const browser = await BrowserClaw.connect('http://host:9222', { authToken: '…', stealth: true });

// Auto-discovery: scans common CDP ports (9222-9226, 9229)
const browser = await BrowserClaw.connect();

connect() checks that Chrome is reachable, then the internal CDP connection retries 3 times with increasing timeouts (5 s, 7 s, 9 s) — safe for Docker/CI where Chrome starts slowly. If an attempt times out because a tab never answered during initialization, the retries stop and connect() throws UnresponsiveCdpTargetError naming that tab (err.targetIds): close the tab or restart the browser.

Always call stop() when finished. A handle created by launch() owns the Chrome process and terminates it on stop. A handle created by connect() releases its connection lease without terminating externally launched Chrome; the shared Playwright adapter closes when the last handle stops. Stopping one connected handle leaves other handles to the same endpoint usable. Stopping the launching handle still terminates its Chrome process, even if connected handles remain.

When headless Chromium is detected, browserclaw installs a guard that rejects modal WebAuthn passkey requests with NotAllowedError so clicks and keys remain usable. Conditional (autofill) requests retain their native behavior; use a headed browser for interactive passkey sign-in. A chrome-headless-shell executable can only be launched with headless: true.

On Linux, if TMPDIR exceeds 50 bytes, launch() gives Chrome /tmp for its temporary files so its socket path fits. The Chrome child also drops inherited jemalloc preload entries and MALLOC_CONF.

Anti-detection: launch() always passes Chrome the flag that disables the AutomationControlled Blink feature. connect() attaches to an already-running Chrome, so it cannot add launch flags retroactively. To inject JavaScript stealth patches for navigator.webdriver, plugins, WebGL vendor, and related browser signals, pass stealth: true to launch() or connect().

Anti-bot / challenge detection

Detect — and optionally wait out — Cloudflare and CAPTCHA interstitials, so your agent can react instead of acting on a challenge page.

const challenge = await page.detectChallenge();
// null, or { kind, message }. kind ∈ 'cloudflare-js' | 'cloudflare-block' | 'cloudflare-turnstile'
//                                  | 'hcaptcha' | 'recaptcha' | 'blocked' | 'rate-limited'

if (challenge?.kind === 'cloudflare-js') {
  const { resolved } = await page.waitForChallenge({ timeoutMs: 20000 }); // pollMs default 500
  if (!resolved) throw new Error('challenge did not clear');
}

waitForChallenge() polls until the page clears or the timeout elapses. JS challenges usually auto-resolve in a few seconds. The library's job is detection — CAPTCHAs (hCaptcha / reCAPTCHA / Turnstile) don't clear on their own. Pair detection with your own solver, a human in a visible window, or browserclaw-agent, whose built-in skills clear press-and-hold and Turnstile challenges via CDP.

Isolated profiles (per-run, per-process)

Pass isolated: true (or isolated: 'some-label') to launch in a dedicated per-run profile, an owner-only $TMPDIR/browserclaw-isolated-<label>-* directory:

  • A run-scoped random suffix is always appended — including when you pass a label string. Two concurrent launches with the same label (isolated: 'my-run') each get a unique directory and never collide on Chrome's SingletonLock. The label is for identification only; it does not produce a stable profile across runs.
  • stop() removes the isolated user-data directory on exit (best-effort; silent on failure). If the process crashes before stop(), leftover $TMPDIR/browserclaw-isolated-* directories remain and can be deleted safely when no Chrome process is using them.
  • When isolated is set, profileName and userDataDir options are ignored.
  • Any cookies, logins, extensions, or localStorage from prior runs are not available — by design.

For a stable, shared profile across runs (persistent login state, preserved history), omit isolated and use profileName / userDataDir instead. Browserclaw disables network prediction in its managed profiles. An explicit userDataDir retains its existing prediction preference, so Chrome may perform speculative networking outside page-request guards.

Stale-lock recovery (persistent profiles)

When a launch fails because Chrome reports the profile is in use by another process, browserclaw removes the Singleton* lock files and retries once — unless the lock is held by a live process on the same machine, in which case the launch fails so the running browser is left alone. A lock recorded under a different hostname is treated as stale: that's the normal state after a container restart with a persisted profile volume, where each run gets a fresh hostname and the old lock would otherwise block launches forever. The trade-off is deliberate and worth knowing: sharing one live profile directory across machines or containers (e.g. over a network filesystem) is unsupported — cross-host liveness can't be verified, so recovery will usurp the other session's lock. A warning is logged whenever locks are removed.

SSRF policy (navigating agent-supplied URLs)

Secure by default. browserclaw validates navigation URLs and DNS answers, blocking private and loopback addresses — 127.0.0.1, RFC 1918 ranges, link-local, the RFC 2544 range, IPv6 ULA, and cloud metadata endpoints like 169.254.169.254 unless an applicable policy exemption permits them. Explicit hostname denials take precedence over exemptions.

CDP discovery forwards the configured bearer token, URL credentials and query parameters only to the same authority. A gateway advertising a different WebSocket authority can supply that endpoint’s own credentials in its URL.

CDP HTTP and WebSocket connections use direct sockets with the validated DNS lookup for the actual dial. They do not use HTTP_PROXY, HTTPS_PROXY, or ALL_PROXY; remote CDP endpoints must be directly reachable. Chrome page-navigation proxy settings are separate. Chrome resolves page-navigation hostnames independently, so those navigation checks alone cannot eliminate DNS rebinding. Set ssrfPolicy.requireAllowlistedHostnames: true to reject unlisted DNS hostnames; names admitted through allowedHostnames or hostnameAllowlist must still be trusted. This gate does not apply when private-network access is enabled, and hostnameAllowlist alone never grants a private-network exemption.

The policy follows the tab, not just the URL you pass. Every redirect hop is checked before its request is sent. Once browserclaw has navigated or interacted with a tab (goto, reload, goBack, goForward, a click, a keypress), a document the page asks for on its own between your actions — a script redirect, a meta refresh, an iframe — is stopped when it points at a blocked address, leaving the current page in place. Tabs the page opens — window.open, target="_blank" links and forms, Ctrl/Cmd-, middle- and Shift-clicks — follow the same policy from their first request, redirects and iframes included: a tab that would open onto a blocked address is closed, and the action that opened it fails with InvalidBrowserNavigationUrlError (between actions, the tab is closed with a warning). If several pages request new tabs at the same time and Chromium omits their opener IDs, browserclaw closes tabs whose opener it cannot identify. To catch tabs opened by modifier clicks, browserclaw briefly holds every page load in the browser while it has a tab under the policy; in a browser you also use yourself through connect(), page loads wait while your Node process is paused (for example at a breakpoint) and continue when browserclaw disconnects. A tab you attached to and have only read from (snapshot, screenshot, text) is not intercepted until then, and neither are the tabs it opens; tabs opened by another CDP client or by a person using a headed browser are not intercepted either, and neither is a page that reaches through window.opener into a tab browserclaw is not intercepting. Each read validates the tab’s current URL. Frame-scoped role snapshots also validate the selected frame and its ancestors. Whole-page AI snapshots, screenshots and PDFs check the network addresses of embedded documents. Captures support inline frames, document blobs, Chromium’s failed-load frames, and extension frames such as the built-in PDF viewer. Subresources and CORS preflights are left to the browser.

To reach private or loopback hosts on purpose (local development, a dev tunnel, an internal dashboard), opt out explicitly:

const browser = await BrowserClaw.launch({
  ssrfPolicy: {
    dangerouslyAllowPrivateNetwork: true, // allow loopback, RFC1918, link-local, metadata endpoints
    allowRfc2544BenchmarkRange: true, // optional: also un-block 198.18.0.0/15 (proxy/fake-IP nets)
    allowIpv6UniqueLocalRange: true, // optional: also un-block fc00::/7 (trusted ULA proxy stacks)
  },
});

// Or keep the secure default and carve out only what you need:
const browser2 = await BrowserClaw.launch({
  ssrfPolicy: {
    allowedHostnames: ['internal.example.com'], // exempt one named host from the private-IP block
    hostnameAllowlist: ['*.example.com'], // restrict navigation to matching hostnames only
  },
});

Pages & Tabs

For a single-tab session, start with BrowserClaw.launch({ url }), then get that page with browser.currentPage(). open(url) creates another tab; it does not navigate the startup tab. If you already called launch() without a URL, use currentPage() followed by page.goto(url) to reuse the blank tab. In an attached browser, currentPage() prefers the focused tab. A blank or browser-internal tab yields to an accessible content tab. Check the handle's URL before calling page.goto(url) if the destination tab matters.

const page = await browser.currentPage(); // the tab in front
await page.goto('https://demo.playwright.dev/todomvc'); // navigate it; no new tab
const tabs = await browser.tabs(); // list all tabs
const handle = browser.page(tabs[0].targetId); // wrap existing tab
const appPage = await browser.waitForTab({ urlContains: 'app-web' });
await browser.focus(tabId); // bring tab to front
await browser.close(tabId); // close a tab
await browser.stop(); // stop browser + cleanup

page.id; // CDP target ID (use with focus/close/page)
await page.url(); // current page URL
await page.title(); // current page title
browser.url; // CDP endpoint URL

To intentionally add another tab:

const second = await browser.open('https://demo.playwright.dev/svgtodo');

Recovering tab handles

Tab handles can get out of sync if the app rewrites its URL aggressively or replaces the top-level target. Use the recovery primitives to re-bind a CrawlPage without having to restart the session:

// Attempts to refresh the cached targetId, optionally falling back to the
// best-effort resolver if the original target is gone.
await page.refreshTargetId();
await page.refreshTargetId({ fallback: 'active' });

// Rebind the handle using the best-effort resolver: prefers the old
// targetId, then the old URL, then a non-blank tab, then any tab.
await page.reacquire();

Recovery prefers the previous target ID, then the previous URL. Among the remaining candidates, content tabs take precedence over blank tabs. Chrome 150 and later report the selected tab in each window over CDP. When several windows qualify or the browser omits tab-selection metadata, BrowserClaw uses the endpoint’s recent tab order from /json/list if available, then the existing page order. For a specific tab, keep the handle from browser.open() or browser.waitForTab(), or select its ID from browser.tabs().

BrowserClaw exports structured errors so workflow code can tell apart the common failure modes:

import {
  BrowserTabNotFoundError, // targetId no longer resolves to an open tab
  BlockedBrowserTargetError, // target unavailable after SSRF policy blocked its navigation
  StaleRefError, // the ref's element is gone; err.reason says why
  AmbiguousTargetError, // clickByText/clickByRole/loc= matched several elements; err.candidates lists them
  SnapshotHydrationError, // snapshot returned without interactive refs
  NavigationRaceError, // the page kept navigating during an operation (snapshot() already retried once)
  UnresponsiveCdpTargetError, // a tab never answered while connecting; close it or restart the browser
  UnknownOptionError, // an option name the method does not know; nothing ran (err.options, err.expected)
  TargetNotFoundError, // a selector, text or role matched nothing and the page went idle
  FieldValueRejectedError, // a field did not keep the typed text (err.outcome: empty, unchanged, appended, truncated)
  EvaluateTimeoutError, // evaluate ran past timeoutMs; err.executionStopped, err.pageResponsive
  LoadStateTimeoutError, // waitFor({ loadState }) timed out; err.pendingRequests names what is still loading
  NavigationTimeoutError, // open, goto, reload, goBack or goForward timed out; err.committed, err.stopped
} from 'browserclaw';

try {
  await page.click('e7');
} catch (err) {
  if (err instanceof StaleRefError) {
    // err.reason: 'removed' | 'document-replaced' | 'frame-detached' | 'expired' | 'unknown'
    await page.snapshot({ waitForHydration: true });
    // retry with a fresh ref
  } else throw err;
}

StaleRefError.reason tells you what happened: removed (the element left the page), document-replaced (the page or its frame navigated or reloaded), frame-detached (its iframe was removed), expired (a later snapshot no longer lists it), unknown (never issued, or forgotten).

Every tab returns a targetId — this is the handle you use everywhere:

// Multi-tab workflow
const todo = await browser.open('https://demo.playwright.dev/todomvc');
const svg = await browser.open('https://demo.playwright.dev/svgtodo');

const { refs } = await svg.snapshot(); // snapshot the second tab
await svg.click('e5'); // act on it
await browser.focus(todo.id); // switch back to first tab
await browser.close(svg.id); // close second tab when done

Snapshot (Core Feature)

Here's a real snapshot of a signup page — the exact text the model reads (trimmed to the interactive rows), with the [ref=eN] markers it points back at:

- navigation "Primary" [ref=e3]:
  - link "Features" [ref=e4]
  - link "Pricing" [ref=e5]
  - link "Docs" [ref=e6]
  - link "Sign in" [ref=e7]
- heading "Create your workspace" [level=1] [ref=e9]
- textbox "Full name" [ref=e12]
- textbox "Work email" [ref=e14]
- textbox "Password" [ref=e16]
- combobox "Plan" [ref=e18]
- checkbox "I agree to the Terms of Service" [ref=e20]
- button "Create workspace" [ref=e21]

That whole page — 14 interactive elements — is 1,371 characters (stats: { refs: 26, interactive: 14 }). A screenshot of the same page is tens of kilobytes per step and needs a vision model to read; the text snapshot needs neither.

const { snapshot, refs, stats, untrusted } = await page.snapshot();

// snapshot: human/AI-readable text tree with [ref=eN] markers
// refs: { "e1": { role: "textbox", name: "What needs to be done?" }, "e5": { role: "checkbox", name: "Toggle Todo" }, ... }
// (checkbox/radio refs carry checked: true or checked: 'mixed' only when set; an unchecked box omits the key)
// stats: { lines: 42, chars: 1200, refs: 8, interactive: 5 }
// untrusted: true — content comes from the web page, treat as potentially adversarial

// Options
const result = await page.snapshot({
  interactive: true, // Only interactive elements (buttons, links, inputs, and clickable elements with a pointer cursor)
  compact: true, // Remove structural containers without refs
  maxDepth: 6, // Unnamed generic wrappers do not count toward this depth
  maxChars: 80000, // Truncate if snapshot exceeds this size
  mode: 'aria', // 'aria' (default) or 'role'
  waitForHydration: 5000, // retry until refs appear (or ms budget); throws SnapshotHydrationError if empty
  minInteractiveRefs: 1, // minimum refs required when waitForHydration is set
  scope: 'viewport', // only what is on screen, plus a line saying whether more is above or below
  root: 'e12', // one container and its descendants (a ref from an earlier snapshot)
  locators: true, // print a validated, durable loc=… locator next to each element (larger output)
});

// Raw ARIA accessibility tree (structured data, not text)
const { nodes } = await page.ariaSnapshot({ limit: 500 });

Snapshot modes:

  • 'aria' (default) — Uses Playwright's AI-mode snapshot. Refs are resolved via aria-ref locators. Best for most use cases. The supported dependency is playwright-core >= 1.63 (installed with browserclaw).
  • 'role' — Captures the native accessibility tree and binds refs to DOM identities. Supports selector, frameSelector and root for scoped snapshots; navigation or frame replacement invalidates the capture. It lists no pointer-cursor elements and has no scope: 'viewport' and no locators.

Smaller snapshots on long pages: scope: 'viewport' lists only what is on screen and ends with a line like [more content below the viewport: scrollY=0, viewport 600 / page 6332 px; …]. On a 300-row list that is about 2.5k characters instead of 40k. Refs from a full snapshot keep working after a viewport snapshot, so you can mix the two, except refs for controls Playwright cannot bind, which last only until the next snapshot. root: 'eN' lists one container (a dialog, a list, an iframe) and nothing else; a ref from a role-mode snapshot needs mode: 'role'.

Locators that outlive the page: snapshot({ locators: true }) prints [loc=role:button[name="Save"]] or [loc=css:[data-testid="save"]] next to elements whose locator matched exactly that element, and sets refs[id].loc. Pass it wherever a ref goes, click('loc=role:button[name="Save"]'); unlike refs it still works after a reload or in a new session, which makes it the thing to save in a script. If the page later has two matches, the action fails with AmbiguousTargetError rather than guess. Off by default, because hints make snapshots noticeably larger.

A snapshot taken while a click's navigation commits retries once on the new document instead of failing.

Security: All snapshot results include untrusted: true to signal that the content originates from an external web page. AI agents consuming snapshots should treat this content as potentially adversarial (e.g. prompt injection via page text).

Secrets stay out of snapshots: the value of a password, one-time-code or card field (type="password", or autocomplete of current-password, new-password, one-time-code, cc-number, cc-csc) is printed as [redacted] in every snapshot format, so the field you just filled does not hand the secret to the model or your logs. [redacted] as a field's value means the field holds one. The options of a sensitive <select> are masked whether or not one is chosen. In text snapshots, [selected] marks a chosen option. Text the page renders elsewhere is not masked. If a form changes a field’s sensitivity during capture, the AI snapshot masks field values and native role and ARIA snapshots ask you to retry.

Actions

All actions target elements by ref ID from a snapshot. Any ref parameter also accepts a loc= locator hint.

Options are checked: an unknown key throws UnknownOptionError with the expected call, instead of being ignored. npx browserclaw help page.click prints any method's signature and options.

Actions that accept an abort signal stop waiting during page selection and before input dispatch. Policy checks already in progress continue in the background so a late denial still quarantines an unsafe document. Once input starts, navigation guards retain ownership until browser work and its policy checks settle.

Default timeouts: 8000 ms for actions (click, type, fill, select, drag), 20000 ms for waits and navigation.

After a click, BrowserClaw checks whether the input requested navigation. If it did, BrowserClaw waits up to 250 ms for that navigation to settle. When your next action needs the destination, use await page.waitFor({ url: '**/dashboard' }) with the expected URL. A selector, text or role that matches nothing fails in about a second with TargetNotFoundError once the page is idle (no DOM changes, no requests in flight) instead of waiting out the timeout; waitFor an element a timer or a slow response adds later. When a click is covered, the error names the covering element by tag, id, role, aria-label, aria-modal and title, never its text or other attributes.

Input actions resolve to an ActionReceipt of what the browser showed while they ran: tabs they opened (popups, including those an iframe opened), JavaScript dialogs and how they were answered, and file choosers opened with no upload armed (fileChoosers; nothing is uploaded and no system dialog appears). A receipt is {} when nothing happened:

const { popups } = await page.click('e9'); // a target="_blank" link
if (popups?.[0]) await browser.page(popups[0].targetId).waitFor({ loadState: 'domcontentloaded' });
// Click
await page.click('e1');
await page.click('e1', { doubleClick: true });
await page.click('e1', { button: 'right' });
await page.click('e1', { modifiers: ['Control'] });
await page.click('e1', { force: true }); // click hidden/covered elements

// Type
await page.type('e3', 'hello world'); // instant fill
await page.type('e3', 'slow typing', { slowly: true }); // keystroke by keystroke
await page.type('e3', 'search', { submit: true }); // type + press Enter

// Other interactions
await page.hover('e2');
await page.select('e5', 'Option A', 'Option B');
await page.select('e5', ['Option A'], { timeoutMs: 3000 }); // with options
await page.drag('e1', 'e4');
await page.scrollIntoView('e7');

// Keyboard
await page.press('Enter');
await page.press('Control+a');
await page.press('Meta+Shift+p');
await page.insertText('pasted text'); // inserts into the focused element without individual key events

// Fill multiple form fields at once
await page.fill([
  { ref: 'e2', value: 'Jane Doe' },
  { ref: 'e4', value: '[email protected]' },
  { ref: 'e6', type: 'checkbox', value: true },
]);

type() and the text fields of fill() read the field back after filling. When the page rejects the text (the field stays empty, keeps its old value or appends), browserclaw retries once with a real click and key presses, then throws FieldValueRejectedError; a maxlength cut is reported at once. Messages give lengths, never the text.

fill() field types: 'text' (default) calls Playwright fill() with the string value. 'checkbox' and 'radio' call setChecked() with force: true (works on hidden inputs behind custom styling). Truthy values are true, 1, '1', 'true'. Type can be omitted and defaults to 'text'. Fields with an empty or whitespace-only ref are silently skipped. fill() resolves to an ActionReceipt. Each field is { ref, type?, value? }; { ref, text } throws UnknownOptionError.

fill() is the ergonomic form-filling case of the lower-level batch(), which runs a heterogeneous sequence of actions (click, mouseClick, type, insertText, press, hover, drag, select, fill, wait, …) in a single call:

const { results } = await page.batch([
  { kind: 'type', ref: 'e2', text: '[email protected]' },
  { kind: 'click', ref: 'e5' },
  { kind: 'wait', text: 'Welcome' },
]); // stops on first failure by default; pass { stopOnError: false } to continue after ordinary failures
// results: [{ ok: true }, { ok: true, receipt?: { popups, dialogs, fileChoosers } }, { ok: true } | { ok: false, error }]

A step carries receipt only when it is non-empty; an evaluate step carries its result, and a nested batch carries result: { results }.

Batches always stop when an action navigates or closes its page, even with stopOnError: false. Only dispatched actions appear in results; take a fresh snapshot before acting on the new document. Navigation-policy denials are thrown rather than returned as ordinary action failures.

No-snapshot actions

These methods find and click elements without needing a snapshot first — useful when you know the text or role but don't want the snapshot+ref round-trip. They search the main frame and never guess: an exact match wins over a partial one, and when several visible elements still match, the call throws AmbiguousTargetError listing them ([0] button "Remove", [1] link "Remove", …) so you can pass { index: N } or click a ref instead.

// Click by visible text or title attribute
await page.clickByText('Submit');
await page.clickByText('Save Changes', { exact: true });

// Click by ARIA role and accessible name
await page.clickByRole('button', 'Save');
await page.clickByRole('link', 'Settings');
await page.clickByRole('button', 'Create', { index: 1 }); // second visible match (0-based)
await page.clickByText('Remove', { index: 0 }); // first of several

// Click by CSS selector
await page.clickBySelector('#submit-btn');

// Click at page coordinates (for canvas elements, custom widgets)
await page.mouseClick(400, 300);

// Press and hold at coordinates (raw CDP events, bypasses automation detection)
await page.pressAndHold(400, 300, { holdMs: 5000, delay: 150 }); // delay ≤ 5000, holdMs ≤ 30000; a signal releases the button

// Low-level pointer and keys, for sliders, canvases and custom drags
await page.mouseMove(100, 200);
await page.mouseDown();
await page.mouseMove(300, 200, { steps: 10 });
await page.mouseUp();
await page.mouseWheel(0, 600, { x: 400, y: 300 }); // real wheel event at a point; resolves after the scroll applies
await page.keyDown('Shift');
await page.keyUp('Shift');

Highlight

await page.highlight('e1'); // Playwright built-in highlight

File Upload

Call ensureUploadStagingDirectory() right before each staging write and copy the file into the directory it returns. On Unix, the helper rechecks ownership of the private per-user staging root and recreates it if a temp cleaner removed it. On Windows, it creates the uploads directory if needed and relies on the configured temp directory's permissions. If your integration hard-coded the Unix staging path used before 0.21.3 (/tmp/browserclaw/uploads), switch to the helper and restage files from their original sources.

import { ensureUploadStagingDirectory } from 'browserclaw';
import { copyFile } from 'node:fs/promises';
import { join } from 'node:path';

// Stage the file inside the sandboxed uploads directory
const staged = join(ensureUploadStagingDirectory(), 'file.pdf');
await copyFile('/path/to/file.pdf', staged);

// Direct: set files on an <input type="file">
await page.uploadFile('e3', [staged]);

// Atomic: arm a chooser, click its trigger, and wait for the upload
await page.upload('e4', [staged]);

// Remote browser: send bytes instead of a browser-local filename
await page.uploadFile('e3', [staged], { browserFilesystemLocal: false });

// Arm pattern: for non-input file pickers
// Awaiting the call resolves once the listener is armed; awaiting `done`
// resolves after files have been set on the chooser.
const { done } = await page.armFileUpload([staged]);
await page.click('e3'); // triggers the file chooser
await done;

Upload methods accept timeoutMs and signal. Remote payloads must total less than 50 MiB; source modification times are not preserved by Playwright's browser transport. The default remains local-file paths, including when an SSRF policy is configured.

Cancelling atomic upload() waits for already-started browser work to settle. Two-phase armFileUpload() waiters reject promptly, but subsequent uploads still wait for the prior browser mutation to finish.

Dialog Handling

Handle JavaScript dialogs (alert, confirm, prompt). Arm the handler before the action that triggers the dialog.

await page.armDialog({ accept: true }); // arm BEFORE the trigger; resolves once the handler is armed
await page.click('e5'); // triggers confirm() — handled in the background

// With prompt text
await page.armDialog({ accept: true, promptText: 'my answer' }); // arm before the trigger
await page.click('e6'); // triggers prompt()

// Persistent handler: called for every dialog until cleared
await page.onDialog((event) => {
  console.log(`${event.type}: ${event.message}`);
  event.accept(); // or event.dismiss()
});
await page.onDialog(undefined); // clear the handler

By default, unexpected dialogs are auto-dismissed to prevent ProtocolError crashes.

Navigation & Waiting

await page.goto('https://demo.playwright.dev/todomvc');
await page.reload(); // reload the current page
await page.goBack(); // navigate back in history
await page.goForward(); // navigate forward in history
await page.waitFor({ loadState: 'networkidle' });
await page.waitFor({ text: 'Welcome' });
await page.waitFor({ textGone: 'Loading...' });
await page.waitFor({ url: '**/dashboard' }); // a string matches the whole URL; use ** wildcards
await page.waitFor({ url: /\/dashboard/ }); // or a RegExp
await page.waitFor({ url: (url) => url.searchParams.has('session') }); // or a predicate, run in Node
await page.waitFor({ selector: '.loaded' }); // wait for CSS selector
await page.waitFor({ selector: '.spinner', state: 'hidden' }); // 'attached' | 'detached' | 'visible' (default) | 'hidden'
await page.waitFor({ fn: '() => document.readyState === "complete"' }); // custom JS (string)
await page.waitFor({ fn: () => document.title === 'Done' }); // custom JS (function)
await page.waitFor({ fn: (name) => document.querySelector('button')?.textContent === name, arg: 'Save' }); // with arg
await page.waitFor({ timeMs: 1000 }); // sleep
await page.waitFor({ text: 'Ready', timeoutMs: 5000 }); // custom timeout
await page.waitFor({ text: 'Ready', signal: AbortSignal.timeout(5000) });

A loadState wait that times out throws LoadStateTimeoutError naming the requests still in flight (query strings left out). Navigation that times out throws NavigationTimeoutError, which says whether the new page committed; an uncommitted goto, reload, goBack or goForward is stopped, so the tab stays on the page it was on.

Capture

// Screenshots
const screenshot = await page.screenshot(); // viewport PNG → Buffer
const fullPage = await page.screenshot({ fullPage: true }); // full scrollable page
const element = await page.screenshot({ ref: 'e1' }); // specific element by ref
const bySelector = await page.screenshot({ element: '.hero' }); // by CSS selector
const jpeg = await page.screenshot({ type: 'jpeg' }); // JPEG format
const noTimeout = await page.screenshot({ timeoutMs: 0 }); // disable the default 20s screenshot timeout

// PDF
const pdf = await page.pdf(); // PDF export (headless only)

// Labeled screenshot — numbered badges on each ref for visual debugging
const { buffer, labels, skipped } = await page.screenshotWithLabels(['e1', 'e2', 'e3']);
// buffer: PNG with numbered overlays
// labels: [{ ref: 'e1', index: 1, box: { x, y, width, height } }, ...]
// skipped: refs that couldn't be found or had no bounding box

In headed Chrome, screenshots capture background tabs while the user's active tab keeps focus. In detected headless Chrome, screenshots activate the target tab to render it.

Screenshots and PDFs tolerate ads and other allowed child frames refreshing. If the main document navigates during capture, they discard the result and raise NavigationRaceError. You can retry on the new document. Both screenshot() and pdf() return a Buffer. Write to file with fs.writeFileSync('out.png', screenshot).

Trace Recording

Capture Playwright traces (screenshots, DOM snapshots, network) for debugging.

await page.traceStart({ screenshots: true, snapshots: true, sources: true }); // sources defaults to false
// ... perform actions ...
await page.traceStop('trace.zip');
// Open with: npx playwright show-trace trace.zip

Response Body

Intercept a network response and read its body.

const resp = await page.responseBody('/api/data');
console.log(resp.status, resp.body);
// { url, status, headers, body, truncated }

Options: timeoutMs (default 30 s, including body completion), maxChars (truncate body), signal (cancel).

Wait For Request

Wait for a network request matching a URL pattern and get full request + response details, including POST body.

const reqPromise = page.waitForRequest('/api/submit', { method: 'POST' });
await page.click('e5'); // submit a form
const req = await reqPromise;
console.log(req.method, req.postData); // 'POST', '{"name":"Jane"}'
console.log(req.status, req.ok); // 200, true
console.log(req.responseBody); // '{"id":123}'
// { url, method, postData?, status, ok, responseBody?, truncated? }

Use method to filter by HTTP method and maxChars to truncate the response body. The timeoutMs budget (default 30 s) includes reading the body.

Visible Page Text

const { text, truncated } = await page.text({ maxChars: 12_000 });
const article = await page.text({ selector: 'article' });

Without a selector, text() tries the first article, then the first main, using either only if visible and nonempty; otherwise it reads body. Output is capped at 40,000 characters and supports an abort signal. If text() detects that the main frame navigated during extraction, it throws NavigationRaceError. Retry once the intended document has loaded. Page text is untrusted external content, just like snapshots.

Activity Monitoring

Console messages, errors, and network requests are buffered automatically.

const logs = await page.consoleLogs(); // all messages
const errors = await page.consoleLogs({ level: 'error' }); // errors only
const recent = await page.consoleLogs({ clear: true }); // read and clear buffer
const pageErrors = await page.pageErrors(); // uncaught exceptions
const requests = await page.networkRequests({ filter: '/api' }); // matches URL or resource type
const fresh = await page.networkRequests({ clear: true }); // read and clear buffer

Storage

// Cookies
const cookies = await page.cookies();
await page.setCookie({ name: 'token', value: 'abc', url: 'https://demo.playwright.dev' });
const { added } = await page.setCookies(cookies); // imports in batches, counting accepted cookies
await page.clearCookies();

// localStorage / sessionStorage
const values = await page.storageGet('local');
const token = await page.storageGet('local', 'authToken');
await page.storageSet('local', 'key', 'value');
await page.storageClear('session');

Downloads

When BrowserClaw runs in WSL2 and connects directly to Windows Chrome over loopback, it uses wslpath to translate Playwright’s temporary download directory for Chrome. This includes Chrome’s user-approved /devtools/browser socket. Pass your usual WSL paths to download and waitForDownload. BrowserClaw keeps the original path if discovery or the WebSocket connection redirects, if the advertised socket differs in port or TLS from the configured endpoint, or if Chromium’s native metadata cannot identify Windows.

// Click a download link and save the file
const result = await page.download('e7', '/tmp/report.pdf');
console.log(result.suggestedFilename); // 'report.pdf'
// Returns: { url, suggestedFilename, path }

// Arm pattern: wait for next download (call before triggering)
const dlPromise = page.waitForDownload({ path: '/tmp/file.pdf' });
await page.click('e8'); // triggers download
const dl = await dlPromise;

Emulation

// Device emulation (viewport + user agent)
await page.setDevice('iPhone 13');

// Color scheme
await page.emulateMedia({ colorScheme: 'dark' });

// Geolocation
await page.setGeolocation({ latitude: 48.8566, longitude: 2.3522 }); // Paris
await page.setGeolocation({
  latitude: 48.8566,
  longitude: 2.3522,
  accuracy: 50,
  origin: 'https://demo.playwright.dev',
}); // grant to a specific origin
await page.setGeolocation({ clear: true }); // reset

// Locale & timezone
await page.setLocale('fr-FR');
await page.setTimezone('Europe/Paris');

// Network
await page.setOffline(true);
await page.setExtraHeaders({ 'X-Custom': 'value' });
await page.setHttpCredentials({ origin: 'https://example.com', username: 'admin', password: 'secret' });
await page.setHttpCredentials({ clear: true }); // remove

HTTP credentials apply to one origin (scheme, host and port). You can omit origin on an HTTP(S) page to use its current origin. Pass origin explicitly when setting credentials on a blank tab before navigation.

Evaluate

Run JavaScript directly in the browser page context.

const title = await page.evaluate('() => document.title');
const text = await page.evaluate('(el) => el.textContent', { ref: 'e1' });
const count = await page.evaluate('() => document.querySelectorAll("img").length');
const slow = await page.evaluate('() => document.readyState', { timeoutMs: 5000 }); // bounded (default 20s); pass an AbortSignal to cancel

timeoutMs is a hard limit, even for a synchronous loop: browserclaw stops the script and rejects with EvaluateTimeoutError, whose executionStopped and pageResponsive say what state the tab is in. Timers or promises the script started earlier can still run. Stopping a script also stops a long task of the page's own. While another evaluate on the tab, or on a tab sharing its process, still holds the page, the timed-out script is left queued (executionStopped: false) and stopped later if it still holds the page.

evaluateInAllFrames(fn, opts?)

Run JavaScript across the page's frames, including cross-origin iframes, subject to the configured SSRF policy. Results include successful evaluations; blocked frames and ordinary per-frame evaluation failures are skipped. timeoutMs sets one total evaluation budget across all frames (default 20 seconds). Exhausting it rejects the call rather than returning partial results.

const results = await page.evaluateInAllFrames(
  `() => {
  const el = document.querySelector('input[name="cardnumber"]');
  return el ? 'found' : null;
}`,
  { timeoutMs: 5000 },
);
// Returns: [{ frameUrl: '...', frameName: '...', result: 'found' }, ...]

Viewport

await page.resize(1280, 720);

Escape hatch: raw Playwright

When you need something browserclaw doesn't wrap, drop down to Playwright directly — same underlying page, full API (custom locators, route() interception, frame manipulation).

const pwPage = await page.playwrightPage(); // the raw Playwright Page
await pwPage.route('**/api/**', (r) => r.fulfill({ body: '{}' }));

const loc = await page.locator('.modal button.confirm'); // a Playwright Locator, no Page round-trip
await loc.click();

Note: mutations made through the raw Playwright page can conflict with browserclaw's internal ref tracking — re-snapshot after using it.

Session health: auth checks & telemetry

Built for cron / unattended runs: assert a session is logged in, and read structured timing + exit telemetry for diagnostics.

// All rules must pass. Rule kinds: url, cookie, selector, text, textGone, fn.
const auth = await page.isAuthenticated([{ url: '/dashboard' }, { textGone: 'Sign in' }]);
if (!auth.authenticated)
  console.log(
    'failed checks:',
    auth.checks.filter((c) => !c.passed),
  );

browser.recordAuthResult(auth.authenticated);
await browser.stop(auth.authenticated ? 'success' : 'auth_failed'); // exitReason recorded in telemetry

console.log(browser.telemetry());
// { launchMs, connectMs, navMs, authOk, exitReason, cleanupOk, timestamps: { startedAt, … } }

stop() accepts an ExitReason: 'success' | 'auth_failed' | 'nav_failed' | 'timeout' | 'crash' | 'disconnected' | 'manual' | 'error'.

Examples

See the examples/ directory for runnable demos:

  • basic.ts — Navigate, snapshot, and add a to-do by ref
  • form-fill.ts — Fill a multi-field form using refs
  • ai-agent.ts — AI agent loop pattern with Claude/GPT

Run from the source tree:

npx tsx examples/basic.ts

Requirements

  • Node.js >= 22
  • Chromium-based browser installed (Chrome, Brave, Edge, or Chromium)
  • playwright-core >= 1.63 (installed automatically as a dependency)

No need to install Playwright browsers — browserclaw uses your system's existing Chrome installation via CDP. If none is found, it falls back to a Chromium already in Playwright's browser cache.

Contributing

See CONTRIBUTING.md. Coding agents working on this repo: AGENTS.md.

Acknowledgments

browserclaw was born from the browser automation module in OpenClaw, built by Peter Steinberger and an amazing community of contributors. The snapshot + ref system, CDP connection management, and Playwright integration originate from that project.

License

MIT


Not affiliated with browserclaw.com in any way — no connection to that site; we recommend treating it with caution.

Explore projetos relacionados

Carregando…