Browser Automation with browser4-cli
Browser automation CLI for AI agents — Chrome/Chromium via CDP with accessibility-tree snapshots.
Decision layer only. Every topic links to a deep dive; load only what the task needs (§7 Reference Map).
From a Browser4 checkout, use ./b4w.sh (Bash/Linux/macOS) or ./b4w.ps1 (PowerShell) instead of an installed binary — they build the runtime bundle and start the backend from the checkout. Full notes: development-mode.md, AGENTS.md.
1. Core Loop
Keep these in mind — ordered by priority:
- 🔝 Minimize user disturbance (top rule) — before launching anything new, always check what already exists on this machine (
attach --list, list, status). If a browser with the right login state is already running, attach to it rather than open a fresh one. If a named session already drove the target site, goto on it instead of close + open. A new Browser4 browser is a new window or a new background process — both are disturbance. Details: §2 Browser Source & Connection, browser-modes.md.
- Headless default for AI agents — use
--headed only when the user asks for a visible window, a human must act, or anti-bot escalation (retry once). Details: browser-modes.md.
- Backend is long-lived — never stop it between commands — one backend process is reused for the whole task; "run a command, then shut it down" is not the intended flow. On-demand startup covers only the first command and a genuine death (host killed the process), so a restart per command is a fault to diagnose with
browser4-cli status, not expected behaviour.
- Dev mode — running from a checkout (
ROOT.md + pom.xml) pins one backend port per checkout; stale bundle → the command names the reason and rebuild hint. See development-mode.md.
0. DISCOVER browser4-cli discover # → one-shot inventory: CDP browsers + family state + managed sessions + P7 recommendation
# Or — run the three probes yourself when you need the raw data for something specific:
browser4-cli attach --list # → browsers on this machine with CDP ports + profile dir
browser4-cli list # → existing Browser4 sessions and their health
browser4-cli status # → default session: which browser, which page
PURPOSE: answer "can I attach/reuse instead of launching something new?" — zero disturbance
1. CHOOSE Two dimensions decide — resource (does it spawn something?) x authorization (whose browser?).
Route by whether the task needs the user's logins, NOT by which browser happens to be listed first:
│
├─ NO logins needed (public pages, docs, price checks, search results)
│ ├─ 🟢 discover shows DEDICATED automation browser (profile dir is its own, auth 🟢 ok) → attach --cdp <port>
│ ├─ 🟡 a healthy Browser4 session already drove this site → -s <name> goto <url> (goto, don't close+open)
│ ├─ 🟡 nothing reusable → open --headless <url> (new process, but zero behavioral footprint)
│ └─ ✗ never attach --extension here — taking over the user's daily browser buys nothing
│
└─ YES logins needed (dashboards, mail, any authenticated page)
Find where the login ALREADY lives before planning a fresh login:
├─ 🟢 a dedicated CDP browser already holds this site's login → attach --cdp <port>
├─ 🟡 a named managed session was logged in here before → -s <name> goto <url> (profile persists)
├─ 🟡 a state file holds the login → state load <file> (after open / goto)
├─ 🟡 the login lives only in the user's daily browser → attach --extension [channel]
└─ ✗ no login anywhere yet → any fresh profile is a login wall:
open --headed, let the human log in once, then persist it
(-s <name> keeps the profile; state save captures cookies for later)
2. SNAPSHOT browser4-cli snapshot -v 0 # capture accessibility tree (viewport 0 = visible screen)
3. INTERACT browser4-cli click <ref> # use refs from the snapshot
browser4-cli fill <ref> <value>
browser4-cli press Enter
4. RE-SNAPSHOT browser4-cli snapshot -v 0 --auto-diff # verify what changed (diff vs previous)
5. EXTRACT browser4-cli htmlsnapshot get ... # or eval, or X-SQL (see §4)
§1 CHOOSE is a two-dimension decision, not a preference order. Resource creation asks "does this path spawn a process/window?"; authorization asks "is the target the user's own daily browser?" The effective tier is the worse of the two, so no amount of resource savings upgrades a 🟡 authorization path to 🟢. This is why login and no-login tasks diverge: attach --extension is resource 🟢 but authorization 🟡 — correct only when the login lives nowhere else, wrong when a public page would do. --profile-mode SYSTEM_DEFAULT is deprecated (Chrome ≥143), so an open session can never borrow the everyday profile; logins reach a managed session only through a warmed named session or state save / state load. Full table: §2 Browser Source & Connection.
§0 DISCOVER is not an optional warm-up — it is how you honour the top rule. Every new browser task should start with these three lightweight commands — they launch no browser, create no session, and return in seconds. Skipping them has real costs: you may open a brand-new anonymous browser in front of a site where someone is already logged in (disturbance + login wall), or launch a fourth Browser4 session when three are already running (resource waste + later management pain). The only way to know whether an attachment or session already exists is to run DISCOVER first. Full decision flow at §2 Browser Source & Connection.
Copy-Paste Template
# Step 0: discover what already exists on this machine (lightweight, launches nothing)
# PURPOSE: find an attachment or reusable session before launching anything new — minimizes disturbance
browser4-cli discover # one-shot inventory + P7 recommendation — this is enough for most tasks
# Or run the three probes yourself when you need raw data for something specific:
browser4-cli attach --list # system browsers with CDP ports + profile dir (🟢/🟡 auth classification)
browser4-cli list # existing Browser4 sessions + connection type
browser4-cli status # default session details
# Step 1: pick the LOWEST-disturbance connection method based on what you found
# A) Attach to user's already-running browser — BEST option if login state is needed
browser4-cli attach --extension # zero setup, via Browser4 Extension (reuses user's daily Chrome/Edge profile)
browser4-cli attach --cdp 9222 # or direct CDP port (separate profile — no shared logins)
# B) Reuse an existing Browser4 session (already open, cookies/profile are there)
browser4-cli -s my-session goto "https://example.com/task"
# C) Fresh launch (last resort — adds a new process/window; only when A and B are unavailable)
browser4-cli open --headless "https://example.com" # headless by default; add --headed only when user asks or human must act
# Step 2-5: interaction loop (connection method differs, interaction commands are identical)
browser4-cli snapshot -v 0 --stdout # read the page; note refs
browser4-cli fill <ref> "<value>" # interact
browser4-cli press Enter
browser4-cli wait --load networkidle # proves network settled — nothing more
browser4-cli wait "<result-selector>" # poll the element carrying the result
browser4-cli snapshot -v 0 --auto-diff --stdout # verify changes vs pre-interaction page
browser4-cli htmlsnapshot get all text "<css>" # extract from the active page's snapshot
browser4-cli generate-locator <ref|css> # resilient CSS selector when a ref must outlive the snapshot
Add --stdout to any snapshot command to avoid writing files.
2. Key Concepts
Element Refs
After commands that modify browser state, browser4-cli saves an accessibility-tree snapshot:
- generic [ref=e7]:
- link "News" [ref=e191]: /url: https://example.com/news
- textbox "Search query" [ref=e35]
- button "Search" [ref=e25]
Each interactive element has a ref (e5, e12) — the element's Chrome DevTools Protocol backend node ID prefixed with e. Use refs to target elements in click, fill, type, get attr, etc.
/url fields may be relative — snapshot output includes the page URL at the top for resolution. Add -u/--urls to include link hrefs (omitted by default). htmlsnapshot get all attr "a[href]" href --absolute resolves relative hrefs against the page URL. Full detail: snapshot.md, htmlsnapshot.md.
Ref Lifecycle
Refs are ephemeral — treat them as single-use handles:
- Always re-snapshot after interactions:
click, fill, type, press, check, uncheck, select, hover, drag, dblclick.
- Always re-snapshot after page/context changes:
goto, reload, tab switches, or clicks that navigate/update the page. Rely on the automatic post-action snapshot for chaining form steps.
- Interactions auto-scroll the target into view; a later
snapshot -v 0 can start mid-page (hiddenTopHeight) — use eval "window.scrollTo(0,0)" or capture -v all when documenting the top.
Safe loop = interact → re-snapshot → use new refs. Pass --no-snapshot on an interaction when you plan to capture a fresh snapshot manually (saves a round-trip).
Display Mode (Headless vs Headed)
| Mode | Flag | Use case |
|---|
| Headless | --headless | Default for AI agents — scraping, automation, CI/CD |
| Headed | --headed | User asks for visible browser; human must act (login/CAPTCHA/QR); anti-bot escalation (retry once) |
Rule for AI agents: always use --headless by default. Use --headed for exactly three reasons: (1) the user explicitly asks for a visible window; (2) a human must act; (3) anti-bot escalation — close then open --headed with the same -s <name> so profile and cookies survive, retry once, and tell the user you switched. If the headed retry is blocked too, give up on fresh launches (this is not a reason to run browser4-cli stop) — the block is fingerprint/IP-level: prefer attach --cdp / attach --extension, raise --interact-level, or report the site as unreachable.
open sets display mode; goto inherits it. close first to change modes on an existing session.
GUI-less environments (CI, Docker) degrade --headed to headless — say the retry ran headless instead of claiming a visible window.
Browser Source & Connection
Two independent disturbance dimensions — effective tier = max(resource creation, authorization). Run §0 DISCOVER first to see what exists and what it is (user's daily browser vs dedicated automation browser).
| Source | Command | Resource Creation | Authorization | Effective | What it does |
|---|
| CDP attach (dedicated) | attach --cdp <port> on a browser with its own --user-data-dir | 🟢 Zero — no new process | 🟢 Authorized — was started for automation | 🟢 | Direct CDP to a browser the user knowingly started for automation. No shared logins from user's daily Chrome. |
| Reusable Browser4 session | -s <name> goto <url> | 🟡 Low — reuses existing process | 🟢 Authorized — Browser4-managed | 🟡 | An existing Browser4 session already has cookies/profile. goto on it directly; don't close + open. |
| Backend launch headless | open --headless | 🔴 Medium+ — new browser process | 🟢 Authorized — creating for automation | 🟡 | Invisible to the user; isolated profile. New process cost is acceptable because behavioral footprint is zero. |
| Extension attach | attach --extension [channel] | 🟢 Zero — no new process | 🟡 Risky — hijacks user's daily Chrome/Edge | 🟡 | Reuses user's default profile (all logins intact). Only pick this when the task needs the user's logged-in state. A task that does not need logins should not hijack the user's daily browser for it. |
| Backend launch headed | open --headed | 🔴 Medium+ — new process + visible window | 🟢 Authorized | 🔴 | Only when user explicitly asks for a visible window, or a human must act (login/CAPTCHA/QR). |
How DISCOVER answers the authorization question. browser4-cli discover is the one-shot entry point that prints all four sections — CDP browsers (with profile dir + auth 🟢/🟡 tier already computed), browser-family inventory, managed sessions, and a P7 two-dimension recommendation. The client-side sections never need a backend and return in seconds; the managed-sessions section hits the backend and gracefully skips with a one-line message when it is down. For granular probes you still have the three lower-level commands below — each is useful when you need just one slice of the inventory for something specific.
Mandatory before every browser task: the discovery checklist. All commands are read-only probes — they launch no browser, create no session, and return in seconds. They answer both "what exists" (resource dimension) and "what kind of resource is it" (authorization dimension):
| Command | What it tells you |
|---|
browser4-cli discover | One-shot entry point — run this first. Every CDP-ready browser (port, family, profile dir, auth 🟢/🟡 tier), every installed/running browser family with debug-port + extension status, every existing Browser4 session (connection method, health, last URL), and a P7 two-dimension recommendation that routes no-login vs login-needed tasks by effective tier. Client-side sections work with no backend. |
browser4-cli attach --list | Raw CDP browser scan only: port, family, open tab count, profile dir (reveals dedicated vs default). Client-side only, no backend. |
browser4-cli list | Existing Browser4 sessions: per-session name, connection method (Extension = user's daily vs CDP/Managed = dedicated), browser brand/version, health. |
browser4-cli status | Default (unnamed) session details: browser, connection method, current tab URL. |
After reading the output, pick the LOWEST effective tier that works for your task. The authorization dimension is what prevents you from picking attach --extension just because it shows up first — it only wins when the task needs the user's logged-in state.
Quick decision tree — pick the LOWEST effective tier first, and check what the target is before picking an attach path:
§0 DISCOVER is done. Now —
├─ 🟢 Effective: discover shows DEDICATED automation browsers
│ ├─ Port 9222 with profile=/path/to/automation-profile → attach --cdp 9222
│ └─ ego-lite is the target → attach --cdp ego-lite (CDP only, --extension not supported)
├─ 🟡 Effective (all three paths below are equally 🟡 effective — pick what fits the task):
│ ├─ list / status shows HEALTHY Browser4 sessions → -s <name> goto <url> (most of your tasks)
│ ├─ Task does NOT need user logins → open --headless <url> (new process, zero behavioral footprint)
│ └─ Task NEEDS user's logged-in state → attach --extension [channel] (only path to default profile)
├─ Bulk, throughput → swarm create → swarm query → swarm close
├─ Several parallel tasks (each needs isolated profile) → one -s <name> per task
└─ 🔴 None of the above + special requirement forces visible window → open --headed
├─ Human must act (login/CAPTCHA/QR) → open --headed
├─ Anti-detection needed → open --channel ego-lite | cloakbrowser
└─ One-shot clean scrape → open --profile-mode TEMPORARY (still 🟡 effective if headless)
Key rules (hard constraints you cannot break):
- Managed launches:
open (Chrome), open --channel ego-lite, open --channel brave, open --channel cloakbrowser. Any other channel name (msedge, chrome-canary, Electron, cloud) is attach-only — open rejects it with a hint to attach --cdp.
attach never launches a browser. If the target browser isn't running, attach fails loudly — it will not silently start a new one for you (which would lose login state).
- ego-lite and cloakbrowser own their anti-detection — Browser4 never injects stealth.js, but human-like input still applies. ego-lite is CDP only; no extension transport. cloakbrowser is a stealth Chromium you install yourself (found under
~/.cloakbrowser/chromium-* or -Dcloakbrowser.path).
close semantics differ by type: open sessions terminate the browser process; attach sessions only disconnect and close the tab they drove (the user's browser keeps running).
- Two hard constraints: SWARM always launches its own browsers (no attach); display mode (
--headless vs --headed) is fixed at session creation — you must close first to change it.
attach --extension is the only path to Chrome's default profile. Chrome refuses debug ports on its default profile, so attach --cdp always connects to an isolated profile with no shared logins.
- The authorization dimension never goes away. An attach on the user's daily browser remains 🟡 effective even if no other attach is available — you cannot pretend it is 🟢. The 🟢 path that would work on this task is
open --headless.
See browser-modes.md for the full three-axis matrix; attach.md for attach transport details and close/disconnect semantics.
Sessions
Named sessions (-s <name>) isolate browser state (cookies, localStorage, tabs) in a dedicated profile directory — reopening always restores the same profile. Use -s <name> to target a named session; goto auto-opens/reconnects.
Concurrent runs — always pass -s <name>: the unnamed DEFAULT session is a singleton shared by every invocation that omits -s (last writer wins), so parallel agents navigate each other's pages. Give each run its own -s job-42.
-s is a GLOBAL flag — position matters. Write it before the command: browser4-cli -s job-42 goto <url>. Written after the command it is rejected as an unexpected positional. The long form --session <name> behaves identically. Other session-pinning ways: BROWSER4_CLI_SESSION=job-42 (env var), browser4-cli config set session job-42 (persisted), browser4-cli session default <name> (promote an existing one).
Check what page an existing session is currently looking at:
browser4-cli -s my-session page info # → URL and title of that session's current tab
browser4-cli -s my-session tab list # → all tabs for that session (GUIDs, URLs, titles)
browser4-cli -s my-session snapshot -v 0 --stdout # → capture a snapshot directly on that session
None of these require the session to have been created by you just now. As long as list shows it as HEALTHY, you can work on it directly. status targets the unnamed session by default; add -s <name> status to check any named session.
stop shuts the backend and marks every session record stale — the records stay on disk, cookies and profile survive; next open/goto revives the same id. It is a deliberate teardown (workspace reset, plugin reload, wedged backend), not routine cleanup — leave the backend running between commands. close removes the record entirely and mints a new session id next time — run state save / state load around a close when browser state must survive.
Tab Management
Tab commands (tab list, tab new, tab select, tab close, window new) scope to a session. Re-snapshot after tab select. window new is the legacy spelling of tab new — both create an additional tab/target and auto-select it. Popups opened by the page (window.open, target="_blank") do not get announced — run tab list after triggering one, select it with tab select <index|guid>, then confirm with page info. Full detail: tab-management.md, tabs.md.
Frame Switching (iframes)
Element commands resolve CSS selectors against the main document by default. For iframe content: frames lists the tree; frame "<target>" switches (element ref, CSS selector, frame name/id, or URL fragment — nested frames switch repeatedly); frame main returns. Scope resets on navigation. Same-origin iframes fully supported; cross-origin fail with an actionable error. eval always runs in the main document. Detail: frames.md.
3. Command Map
| Command | Purpose | Full reference |
|---|
goto, open, close, close all, reload | Navigation & session management | browser-modes.md |
snapshot, snapshot grep | Capture accessibility tree (AXTree) with refs; --stdout prints directly; --auto-diff diffs vs previous | snapshot.md |
click, dblclick, drag, hover, mousemove, fill, type, press, select, check, generate locator | Page interaction | quick-patterns.md |
upload <ref> <file> | Upload local files to a page <input type="file"> | upload.md |
focus, key, keyboard | Explicit focus / keypresses | — |
is visible|enabled|checked <sel> | Element state assertions — prints verdict and exits 0 even when false; use --fail-on-false | quickstart.md |
dialog accept, dialog dismiss, dialog status | JS alert/confirm/prompt handling — triggering click parks server-side, so run dialog in a separate invocation (or click --auto-dismiss-dialogs) | — |
htmlsnapshot, get, get all, get attr, htmlsnapshot query, summary, inspect, readability, algorithms | Every htmlsnapshot command captures the active page first. Extract text/html/attr via CSS selectors (fresh snapshot of the active tab, so post-interaction state visible); query for correlated multi-field rows; summary for compressed WPSI YAML; --expires <dur> serves stored snapshot without touching tab | htmlsnapshot.md, x-sql.md |
get <mode> <selector> | Live-DOM single-element read (text, html, box, styles, property, attr) — no capture round-trip | — |
eval, eval --ref | Execute JS in the page. --await for Promises/fetch; --wait-selector for late content; --json for machine output; --ref takes an arrow function (element => element.textContent) — bare element.textContent returns null | eval.md |
scrollintoview, pushstate, highlight | Element scroll / history / visual highlight (eval-based shortcuts) | — |
vitals, web vitals | Core Web Vitals measurement (LCP, CLS, INP, FCP, TTFB) | — |
set geo|offline|headers|media|device | CDP emulation — active until changed or cleared; new tab starts un-emulated | emulation.md |
errors | Console errors only (alias of console --min-level error) | — |
extract, summarize, agent run | AI-powered extraction (needs LLM key). extract without --schema returns {title, content, links} — --schema produces named fields. agent run submits an async task → agent status <id> → agent result <id>; --wait / --follow / -i interactive session | agent.md, agent-access.md |
crawl, swarm, loop | Recursive crawling, parallel scraping, scheduled repeats | crawl.md, swarm.md, loop.md |
webminer install, webminer all, webminer views | Structure pages you already have (webminer all --max-files 900 raises the default 40-file cap; see §4d) | browser4-web-miner |
state save, state load, cookie-*, *-storage-* | Browser storage management | storage-state.md |
browser4-cli discover | One-shot browser discovery: CDP browsers + browser-family inventory + managed sessions + P7 two-dimension recommendation. Run this before every browser task to honor Minimize User Disturbance. | (built-in; see §0 and §2 "Discovery checklist") |
attach, attach --list | Connect to an existing browser via CDP or Browser4 Extension. attach --list is the raw CDP scan that discover calls internally. | attach.md |
webdb export, webdb normalize | Export cached pages, normalize URLs | webdb.md |
screenshot, scroll, wait, resize | Visual capture & viewport control | snapshot.md |
download, wait --download | Download management — wait --download only counts files created/changed after the call starts | snapshot.md |
network requests, network har start/stop, network route/routes/unroute | Network inspection, HAR recording, request mocking/abort | network.md |
profiler start, profiler stop | V8 CPU profiling via CDP | — |
scrape --formats <list>, scrape formats | One page capture → many outputs in one document; quote comma lists | scrape-formats.md |
batch | Run several commands in one invocation — steps run on the client, one backend call per step; exit code 5 = at least one step failed | quickstart.md |
tool call <mcp-name> [--json '{...}'] | Generic MCP passthrough for plugin-provided tools; names are snake_case; --fail-on-error makes PERMISSION_DENIED exit non-zero | — |
config, status, doctor, doctor log|metrics|status | Persistent CLI defaults + server health diagnostics | config.md |
skills, skill ... | Bundled skill files + backend skill management | skills.md |
plugin list|info|install|remove, plugin <domain> <method> | Plugin management & invocation | plugins.md |
experience save|query|list|deep learn | Progressive experience memory — sibling skill | browser4-experience |
star | Star the Browser4 repo; only when the user asks explicitly — never pass --gh on their behalf | — |
| Other | Remaining families: console, cdp, pdf, page info, diff snapshot, snapshot clean, profiles list, profile-import, chat, kill all, stop, uninstall, delete data. Discover with browser4-cli help <command> / browser4-cli --help category:<name> | — |
Refreshing This Skill
skills get browser4-cli prints this skill from the installed binary (use --full for every reference file). skills path, skills unpack [dest], install / upgrade also sync the bundled browser4-cli skill into ~/.agents/skills. Full detail: skills.md.
4. Decision Trees
What kind of work is this? Pick the branch first — it names the command family; full trees live in decision-trees.md.
What do you need to do?
|- act on a page (click, fill, press, upload) ..... snapshot -> act on refs -> re-snapshot
|- get snapshot metadata for the live page ....... htmlsnapshot (capture)
|- read content off the live page ................. htmlsnapshot get / get all / query
|- several outputs from one page at once ......... scrape --formats "markdown,links"
|- compute something in page JS ................... eval (--ref takes an arrow function)
|- understand a page, or find selectors ........... htmlsnapshot inspect | summary
|- fetch many known or linked pages ............... crawl (--seed-file, --depth N)
|- the same task across many URLs, in parallel .... swarm
|- repeat on a schedule ........................... loop
`- structure pages you already have ............... webminer all (raise --max-files from 40)
- Extraction method: interact →
snapshot + refs; read content → htmlsnapshot get/query/summary/inspect (each captures the active tab first, so post-interaction state is visible; --expires <dur> serves stored snapshot instead); live DOM → eval --json; natural language → extract.
- Bulk/scale: one list page →
query; known URLs → crawl --seed-file; follow links → crawl <url> --depth N; overlap → crawl --parallel 8; parallel → swarm; scheduled → loop. Interrupted crawl keeps its id → crawl list --status interrupted, then crawl resume <task-id> — already-fetched URLs are not re-requested by default.
- Query granularity:
get = first match; get all = all matches (unaligned arrays); query = correlated multi-field rows.
- WebMiner:
< 1,000 pages → webminer all (free, local, zero tokens); > 1,000 pages → WebMiner Commercial (Spark). webminer all silently truncates its corpus at --max-files 40 — raise it explicitly. The interactive HTML report goes under the OS temp dir, not --output.
- X-SQL quickstart:
SELECT DOM_FIRST_TEXT(DOM,'h2') AS title ... FROM DOM_LOAD_AND_SELECT(@url, '.product-card') — single quotes for CSS, @url unquoted; run via --sql @file.sql. A JOIN of two DOM_LOAD_AND_SELECT sources executes (each reloads the page, so joins are costly); CTEs and FROM-clause subqueries are not supported. Numeric-returning functions serialize as JSON strings unless you CAST(... AS DOUBLE).
5. Critical Warnings
A trap index — broad warnings that apply across the whole skill or most of it. File-local warnings live with their commands.
| Trap | What happens | Do this |
|---|
| 🔴 Resource dim: launching when something already exists (top trap) | Three Browser4 sessions or a dedicated CDP browser are already running, but you open again — disturbance, login wall (isolated profile = no existing cookies), resource waste | Run §0 DISCOVER (attach --list, list, status) before every new browser task, then pick the LOWEST effective tier path from the decision tree |
| 🔴 Auth dim: hijacking user's daily browser (attach --extension when logins not needed) | attach --extension on the user's daily Chrome/Edge opens a relay tab, controls their browser, can observe their tabs and pages — this is authorization 🟡 risk, not 🟢, even though no new process was created | attach --extension only when the task explicitly needs the user's logged-in default profile. For public-page tasks (no login needed), prefer open --headless (🔴 resource but 🟢 authorization = effective 🟡) |
| 🔴 attach --cdp ≠ reusing user's daily Chrome logins | Chrome refuses debug ports on its default profile, so attach --cdp always connects to an isolated --user-data-dir with no shared cookies — the agent lands on a login wall | Need the user's logged-in state? Use attach --extension [channel] — it is the only path to Chrome's default profile logins |
| Reusing a ref | Refs expire on every DOM-changing command (click, fill, goto, reload, tab switch) | Re-snapshot before reusing a ref; --no-snapshot skips the automatic one |
| Brittle CSS selectors | A selector tied to today's markup breaks when the site changes its HTML | Discover with htmlsnapshot inspect / summary; scenario docs are patterns, not recipes |
is visible/enabled/checked | Prints the verdict and exits 0 even when false | Add --fail-on-false to make false/null exit 1 |
wait <sel> / --text / --url / --fn | Exits non-zero when the condition never becomes true | Poll the element that carries the result |
wait --load networkidle | Proves the network went quiet, not that the page is ready — JS-rendered result pages can still be empty | Poll the result element first |
eval "async …" without --await | An unresolved Promise is reported as a failure, not as data | Add --await to every async / fetch expression |
eval --ref with a bare expression | Returns null instead of the value | Always an arrow function: element => element.textContent |
| Nested quotes | Inline JS/SQL with nested quotes breaks on PowerShell/bash | Pass --file, @file, --stdin or --base64; in PowerShell quote "@query.sql" — @ is the splatting operator |
--headless / --headed after the session is created | No effect — the session was created with one mode, changing it later is ignored with a warning | close first, then open --headless / open --headed |
Concurrent runs without -s | Parallel agents share the DEFAULT session (last writer wins) and navigate each other's pages | Give each run its own -s job-42 |
-s written after the command | Rejected as an unexpected positional | Write -s <name> before the command |
| Pagination floods | snapshot --stdout / snapshot get html / snapshot grep can dump 63KB+ trees and 256KB+ snapshot files | Bound the capture (-v 0, --depth, --selector) or use snapshot grep |
| Sandboxed host with unwritable log dir | open / goto hang until startup timeout with Access denied | Point BROWSER4_RUNTIME_DIR, BROWSER4_SERVER_LOG_DIR, BROWSER4_CLI_STATE_DIR at writable directories; doctor log reads startup logs |
close + open when a reusable session would have worked | You lose that session's cookies, localStorage, tab history — and later on the same site you have to log in again from scratch | Check list / -s <name> page info first to confirm the session is healthy, then goto directly on it; only close + open when you explicitly want a clean profile |
| Localized marketplace | The site localized for this profile — Chinese titles, HKD prices — not a missing flag | Drive the site's own language/currency picker, then verify one product; the profile carries the choice into crawl --session |
| Git Bash / MSYS path conversion | Arguments starting with / are rewritten into Windows paths before PowerShell starts — ./b4w.ps1 refuses them | Invoke ./b4w.sh, or prefix MSYS2_ARG_CONV_EXCL='*' ./b4w.ps1; prefer the slash-free spelling where a substring suffices |
6. Quick Patterns
Proven copy-paste recipes — top 3 paths; the full walkthroughs live in quick-patterns.md and quickstart.md.
- Interactive Form Fill — open → snapshot → fill refs → submit →
wait --load networkidle → poll the result element → snapshot -v 0 --auto-diff --stdout to verify.
- Find Elements by Text —
snapshot grep [-i] [-A 3 -B 1] "pattern"; a -i search for "language|currency|English" finds localization controls.
- Bulk Extraction with X-SQL — correlated fields via
htmlsnapshot query --sql @query.sql with SELECT DOM_FIRST_TEXT(DOM,'h2') AS title, DOM_FIRST_FLOAT(DOM,'.price') AS price FROM DOM_LOAD_AND_SELECT(@url, '.product-card'); run across pages with crawl --sql @query.sql --parallel 8.
Resilient selectors: div:expr(width > 400 && height > 400) filters by computed geometry instead of class names — usable in any CSS selector and in htmlsnapshot get / X-SQL selectors. Detail: power-dom.md; css-selector-bridge.md bridges refs → selectors.
7. Reference Map
Organized by task — follow the link that matches what you're trying to do; this map replaces long inline descriptions.
Core / distilled quick reference: quickstart.md — compressed resident version embedded in the CLI engine prompt; system prompt refreshes this file, full detail stays in SKILL.md.
Interact with pages (accessibility tree & element refs): snapshot.md — snapshot, snapshot grep, -v, --auto-diff, -i interactive-only mode (drops draggable/hover-only refs); tabs.md — tab GUID forms, --json envelope, last-tab rule; upload.md — upload local files to <input type="file">; frames.md — iframes: switching, scope resets on navigation.
Extract data from pages: htmlsnapshot.md — get, get all, query, summary, inspect, readability, algorithms, --expires; eval.md — eval, eval --ref, input options, --await, arrow-function rule; x-sql.md — X-SQL function reference (DOM, STR, ARRAY namespaces); decision-trees.md — extraction method, bulk/scale, WebMiner, X-SQL quickstart; scrape-formats.md — one capture → many formats in one document; quick-patterns.md — proven interact/verify/extract recipes; scenario walkthroughs: htmlsnapshot-scenarios.md (specialized: advanced, amazon, audit, extraction).
Run at scale: bulk-collection.md — collecting N items without losing data, persist rows as you go, pin locale/currency; crawl.md — recursive crawling, seed-file bulk fetch, X-SQL extraction, resume; swarm.md — parallel scraping across multiple browser contexts; loop.md — repeated task execution with persistence/resume.
Manage browser state: storage-state.md — cookies, localStorage, state save/load; browser-state-import.md — copy system browser state into Browser4-managed sessions; webdb.md — export cached pages, normalize URLs; attach.md — CDP / Extension attach transport, endpoint resolution, close vs disconnect semantics; tab-management.md — multi-tab workflows, GUID targeting, error recovery.
Choose how the browser runs: browser-modes.md — session × display × browser source matrix, headless→headed escalation, profile mode, ego-lite, Chrome ≥143 restrictions; emulation.md — set geo|offline|headers|media|device, undo recipes.
Manage skills & configuration: skills.md — bundled skill files, backend skill management, sync to ~/.agents/skills; config.md — config command family: CLI defaults and server-side overrides; plugins.md — plugin JAR install (the one case that legitimately needs a backend restart), policy refusal.
AI-powered extraction: agent.md — extract, summarize, agent run|status|result, lifecycle; agent-access.md — task access presets (full/write/read-build/read), PERMISSION_DENIED codes, unattended default; agent-workspace.md — per-task workspace, path boundaries, deliverable formats.
Resilient selectors: power-dom.md — PowerCSS :expr() visual-feature selectors; css-selector-bridge.md — bridging refs to CSS selectors.
Fetching / load behavior: load-options-guide.md — cache control, quality requirements, portal crawling; load-options-decision.md — choosing LoadOptions.
Troubleshoot: shell-quoting.md — avoid shell-quoting breakage for JS/X-SQL on Windows / Git Bash; development-mode.md — one backend per checkout, dev ports 8282+, per-checkout state namespace.
8. Installation
npm install -g browser4-cli && browser4-cli install # Node.js available
irm https://browser4.oss-cn-beijing.aliyuncs.com/scripts/install-browser4-cli.ps1 | iex # Windows
curl -fsSL https://browser4.oss-cn-beijing.aliyuncs.com/scripts/install-browser4-cli.sh | bash # Linux/macOS
Run browser4-cli open and Web UI will be available on http://localhost:18182/ for human.