Browser Automation with agent-browser
Core Workflow
Every browser automation follows this pattern:
- Navigate:
agent-browser open <url>
- Snapshot:
agent-browser snapshot -i (get element refs like @e1, @e2)
- Interact: Use refs to click, fill, select
- Re-snapshot: After navigation or DOM changes, get fresh refs
bash
1agent-browser open https://example.com/form
2agent-browser snapshot -i
3# Output: @e1 [input type="email"], @e2 [input type="password"], @e3 [button] "Submit"
4
5agent-browser fill @e1 "user@example.com"
6agent-browser fill @e2 "password123"
7agent-browser click @e3
8agent-browser wait --load networkidle
9agent-browser snapshot -i # Check result
Command Chaining
Commands can be chained with && in a single shell invocation. The browser persists between commands via a background daemon, so chaining is safe and more efficient than separate calls.
bash
1# Chain open + wait + snapshot in one call
2agent-browser open https://example.com && agent-browser wait --load networkidle && agent-browser snapshot -i
3
4# Chain multiple interactions
5agent-browser fill @e1 "user@example.com" && agent-browser fill @e2 "password123" && agent-browser click @e3
6
7# Navigate and capture
8agent-browser open https://example.com && agent-browser wait --load networkidle && agent-browser screenshot page.png
When to chain: Use && when you don't need to read the output of an intermediate command before proceeding (e.g., open + wait + screenshot). Run commands separately when you need to parse the output first (e.g., snapshot to discover refs, then interact using those refs).
Essential Commands
bash
1# Navigation
2agent-browser open <url> # Navigate (aliases: goto, navigate)
3agent-browser close # Close browser
4
5# Snapshot
6agent-browser snapshot -i # Interactive elements with refs (recommended)
7agent-browser snapshot -i -C # Include cursor-interactive elements (divs with onclick, cursor:pointer)
8agent-browser snapshot -s "#selector" # Scope to CSS selector
9
10# Interaction (use @refs from snapshot)
11agent-browser click @e1 # Click element
12agent-browser click @e1 --new-tab # Click and open in new tab
13agent-browser fill @e2 "text" # Clear and type text
14agent-browser type @e2 "text" # Type without clearing
15agent-browser select @e1 "option" # Select dropdown option
16agent-browser check @e1 # Check checkbox
17agent-browser press Enter # Press key
18agent-browser keyboard type "text" # Type at current focus (no selector)
19agent-browser keyboard inserttext "text" # Insert without key events
20agent-browser scroll down 500 # Scroll page
21agent-browser scroll down 500 --selector "div.content" # Scroll within a specific container
22
23# Get information
24agent-browser get text @e1 # Get element text
25agent-browser get url # Get current URL
26agent-browser get title # Get page title
27
28# Wait
29agent-browser wait @e1 # Wait for element
30agent-browser wait --load networkidle # Wait for network idle
31agent-browser wait --url "**/page" # Wait for URL pattern
32agent-browser wait 2000 # Wait milliseconds
33
34# Downloads
35agent-browser download @e1 ./file.pdf # Click element to trigger download
36agent-browser wait --download ./output.zip # Wait for any download to complete
37agent-browser --download-path ./downloads open <url> # Set default download directory
38
39# Capture
40agent-browser screenshot # Screenshot to temp dir
41agent-browser screenshot --full # Full page screenshot
42agent-browser screenshot --annotate # Annotated screenshot with numbered element labels
43agent-browser pdf output.pdf # Save as PDF
44
45# Diff (compare page states)
46agent-browser diff snapshot # Compare current vs last snapshot
47agent-browser diff snapshot --baseline before.txt # Compare current vs saved file
48agent-browser diff screenshot --baseline before.png # Visual pixel diff
49agent-browser diff url <url1> <url2> # Compare two pages
50agent-browser diff url <url1> <url2> --wait-until networkidle # Custom wait strategy
51agent-browser diff url <url1> <url2> --selector "#main" # Scope to element
Common Patterns
Form Submission
bash
1agent-browser open https://example.com/signup
2agent-browser snapshot -i
3agent-browser fill @e1 "Jane Doe"
4agent-browser fill @e2 "jane@example.com"
5agent-browser select @e3 "California"
6agent-browser check @e4
7agent-browser click @e5
8agent-browser wait --load networkidle
Authentication with Auth Vault (Recommended)
bash
1# Save credentials once (encrypted with AGENT_BROWSER_ENCRYPTION_KEY)
2# Recommended: pipe password via stdin to avoid shell history exposure
3echo "pass" | agent-browser auth save github --url https://github.com/login --username user --password-stdin
4
5# Login using saved profile (LLM never sees password)
6agent-browser auth login github
7
8# List/show/delete profiles
9agent-browser auth list
10agent-browser auth show github
11agent-browser auth delete github
Authentication with State Persistence
bash
1# Login once and save state
2agent-browser open https://app.example.com/login
3agent-browser snapshot -i
4agent-browser fill @e1 "$USERNAME"
5agent-browser fill @e2 "$PASSWORD"
6agent-browser click @e3
7agent-browser wait --url "**/dashboard"
8agent-browser state save auth.json
9
10# Reuse in future sessions
11agent-browser state load auth.json
12agent-browser open https://app.example.com/dashboard
Session Persistence
bash
1# Auto-save/restore cookies and localStorage across browser restarts
2agent-browser --session-name myapp open https://app.example.com/login
3# ... login flow ...
4agent-browser close # State auto-saved to ~/.agent-browser/sessions/
5
6# Next time, state is auto-loaded
7agent-browser --session-name myapp open https://app.example.com/dashboard
8
9# Encrypt state at rest
10export AGENT_BROWSER_ENCRYPTION_KEY=$(openssl rand -hex 32)
11agent-browser --session-name secure open https://app.example.com
12
13# Manage saved states
14agent-browser state list
15agent-browser state show myapp-default.json
16agent-browser state clear myapp
17agent-browser state clean --older-than 7
Data Extraction
bash
1agent-browser open https://example.com/products
2agent-browser snapshot -i
3agent-browser get text @e5 # Get specific element text
4agent-browser get text body > page.txt # Get all page text
5
6# JSON output for parsing
7agent-browser snapshot -i --json
8agent-browser get text @e1 --json
Parallel Sessions
bash
1agent-browser --session site1 open https://site-a.com
2agent-browser --session site2 open https://site-b.com
3
4agent-browser --session site1 snapshot -i
5agent-browser --session site2 snapshot -i
6
7agent-browser session list
Connect to Existing Chrome
bash
1# Auto-discover running Chrome with remote debugging enabled
2agent-browser --auto-connect open https://example.com
3agent-browser --auto-connect snapshot
4
5# Or with explicit CDP port
6agent-browser --cdp 9222 snapshot
Color Scheme (Dark Mode)
bash
1# Persistent dark mode via flag (applies to all pages and new tabs)
2agent-browser --color-scheme dark open https://example.com
3
4# Or via environment variable
5AGENT_BROWSER_COLOR_SCHEME=dark agent-browser open https://example.com
6
7# Or set during session (persists for subsequent commands)
8agent-browser set media dark
Visual Browser (Debugging)
bash
1agent-browser --headed open https://example.com
2agent-browser highlight @e1 # Highlight element
3agent-browser record start demo.webm # Record session
4agent-browser profiler start # Start Chrome DevTools profiling
5agent-browser profiler stop trace.json # Stop and save profile (path optional)
Use AGENT_BROWSER_HEADED=1 to enable headed mode via environment variable. Browser extensions work in both headed and headless mode.
Local Files (PDFs, HTML)
bash
1# Open local files with file:// URLs
2agent-browser --allow-file-access open file:///path/to/document.pdf
3agent-browser --allow-file-access open file:///path/to/page.html
4agent-browser screenshot output.png
iOS Simulator (Mobile Safari)
bash
1# List available iOS simulators
2agent-browser device list
3
4# Launch Safari on a specific device
5agent-browser -p ios --device "iPhone 16 Pro" open https://example.com
6
7# Same workflow as desktop - snapshot, interact, re-snapshot
8agent-browser -p ios snapshot -i
9agent-browser -p ios tap @e1 # Tap (alias for click)
10agent-browser -p ios fill @e2 "text"
11agent-browser -p ios swipe up # Mobile-specific gesture
12
13# Take screenshot
14agent-browser -p ios screenshot mobile.png
15
16# Close session (shuts down simulator)
17agent-browser -p ios close
Requirements: macOS with Xcode, Appium (npm install -g appium && appium driver install xcuitest)
Real devices: Works with physical iOS devices if pre-configured. Use --device "<UDID>" where UDID is from xcrun xctrace list devices.
Security
All security features are opt-in. By default, agent-browser imposes no restrictions on navigation, actions, or output.
Content Boundaries (Recommended for AI Agents)
Enable --content-boundaries to wrap page-sourced output in markers that help LLMs distinguish tool output from untrusted page content:
bash
1export AGENT_BROWSER_CONTENT_BOUNDARIES=1
2agent-browser snapshot
3# Output:
4# --- AGENT_BROWSER_PAGE_CONTENT nonce=<hex> origin=https://example.com ---
5# [accessibility tree]
6# --- END_AGENT_BROWSER_PAGE_CONTENT nonce=<hex> ---
Domain Allowlist
Restrict navigation to trusted domains. Wildcards like *.example.com also match the bare domain example.com. Sub-resource requests, WebSocket, and EventSource connections to non-allowed domains are also blocked. Include CDN domains your target pages depend on:
bash
1export AGENT_BROWSER_ALLOWED_DOMAINS="example.com,*.example.com"
2agent-browser open https://example.com # OK
3agent-browser open https://malicious.com # Blocked
Action Policy
Use a policy file to gate destructive actions:
bash
1export AGENT_BROWSER_ACTION_POLICY=./policy.json
Example policy.json:
json
1{ "default": "deny", "allow": ["navigate", "snapshot", "click", "scroll", "wait", "get"] }
Auth vault operations (auth login, etc.) bypass action policy but domain allowlist still applies.
Output Limits
Prevent context flooding from large pages:
bash
1export AGENT_BROWSER_MAX_OUTPUT=50000
Diffing (Verifying Changes)
Use diff snapshot after performing an action to verify it had the intended effect. This compares the current accessibility tree against the last snapshot taken in the session.
bash
1# Typical workflow: snapshot -> action -> diff
2agent-browser snapshot -i # Take baseline snapshot
3agent-browser click @e2 # Perform action
4agent-browser diff snapshot # See what changed (auto-compares to last snapshot)
For visual regression testing or monitoring:
bash
1# Save a baseline screenshot, then compare later
2agent-browser screenshot baseline.png
3# ... time passes or changes are made ...
4agent-browser diff screenshot --baseline baseline.png
5
6# Compare staging vs production
7agent-browser diff url https://staging.example.com https://prod.example.com --screenshot
diff snapshot output uses + for additions and - for removals, similar to git diff. diff screenshot produces a diff image with changed pixels highlighted in red, plus a mismatch percentage.
Timeouts and Slow Pages
The default Playwright timeout is 25 seconds for local browsers. This can be overridden with the AGENT_BROWSER_DEFAULT_TIMEOUT environment variable (value in milliseconds). For slow websites or large pages, use explicit waits instead of relying on the default timeout:
bash
1# Wait for network activity to settle (best for slow pages)
2agent-browser wait --load networkidle
3
4# Wait for a specific element to appear
5agent-browser wait "#content"
6agent-browser wait @e1
7
8# Wait for a specific URL pattern (useful after redirects)
9agent-browser wait --url "**/dashboard"
10
11# Wait for a JavaScript condition
12agent-browser wait --fn "document.readyState === 'complete'"
13
14# Wait a fixed duration (milliseconds) as a last resort
15agent-browser wait 5000
When dealing with consistently slow websites, use wait --load networkidle after open to ensure the page is fully loaded before taking a snapshot. If a specific element is slow to render, wait for it directly with wait <selector> or wait @ref.
Session Management and Cleanup
When running multiple agents or automations concurrently, always use named sessions to avoid conflicts:
bash
1# Each agent gets its own isolated session
2agent-browser --session agent1 open site-a.com
3agent-browser --session agent2 open site-b.com
4
5# Check active sessions
6agent-browser session list
Always close your browser session when done to avoid leaked processes:
bash
1agent-browser close # Close default session
2agent-browser --session agent1 close # Close specific session
If a previous session was not closed properly, the daemon may still be running. Use agent-browser close to clean it up before starting new work.
Ref Lifecycle (Important)
Refs (@e1, @e2, etc.) are invalidated when the page changes. Always re-snapshot after:
- Clicking links or buttons that navigate
- Form submissions
- Dynamic content loading (dropdowns, modals)
bash
1agent-browser click @e5 # Navigates to new page
2agent-browser snapshot -i # MUST re-snapshot
3agent-browser click @e1 # Use new refs
Annotated Screenshots (Vision Mode)
Use --annotate to take a screenshot with numbered labels overlaid on interactive elements. Each label [N] maps to ref @eN. This also caches refs, so you can interact with elements immediately without a separate snapshot.
bash
1agent-browser screenshot --annotate
2# Output includes the image path and a legend:
3# [1] @e1 button "Submit"
4# [2] @e2 link "Home"
5# [3] @e3 textbox "Email"
6agent-browser click @e2 # Click using ref from annotated screenshot
Use annotated screenshots when:
- The page has unlabeled icon buttons or visual-only elements
- You need to verify visual layout or styling
- Canvas or chart elements are present (invisible to text snapshots)
- You need spatial reasoning about element positions
Semantic Locators (Alternative to Refs)
When refs are unavailable or unreliable, use semantic locators:
bash
1agent-browser find text "Sign In" click
2agent-browser find label "Email" fill "user@test.com"
3agent-browser find role button click --name "Submit"
4agent-browser find placeholder "Search" type "query"
5agent-browser find testid "submit-btn" click
JavaScript Evaluation (eval)
Use eval to run JavaScript in the browser context. Shell quoting can corrupt complex expressions -- use --stdin or -b to avoid issues.
bash
1# Simple expressions work with regular quoting
2agent-browser eval 'document.title'
3agent-browser eval 'document.querySelectorAll("img").length'
4
5# Complex JS: use --stdin with heredoc (RECOMMENDED)
6agent-browser eval --stdin <<'EVALEOF'
7JSON.stringify(
8 Array.from(document.querySelectorAll("img"))
9 .filter(i => !i.alt)
10 .map(i => ({ src: i.src.split("/").pop(), width: i.width }))
11)
12EVALEOF
13
14# Alternative: base64 encoding (avoids all shell escaping issues)
15agent-browser eval -b "$(echo -n 'Array.from(document.querySelectorAll("a")).map(a => a.href)' | base64)"
Why this matters: When the shell processes your command, inner double quotes, ! characters (history expansion), backticks, and $() can all corrupt the JavaScript before it reaches agent-browser. The --stdin and -b flags bypass shell interpretation entirely.
Rules of thumb:
- Single-line, no nested quotes -> regular
eval 'expression' with single quotes is fine
- Nested quotes, arrow functions, template literals, or multiline -> use
eval --stdin <<'EVALEOF'
- Programmatic/generated scripts -> use
eval -b with base64
Configuration File
Create agent-browser.json in the project root for persistent settings:
json
1{
2 "headed": true,
3 "proxy": "http://localhost:8080",
4 "profile": "./browser-data"
5}
Priority (lowest to highest): ~/.agent-browser/config.json < ./agent-browser.json < env vars < CLI flags. Use --config <path> or AGENT_BROWSER_CONFIG env var for a custom config file (exits with error if missing/invalid). All CLI options map to camelCase keys (e.g., --executable-path -> "executablePath"). Boolean flags accept true/false values (e.g., --headed false overrides config). Extensions from user and project configs are merged, not replaced.
Deep-Dive Documentation
Experimental: Native Mode
agent-browser has an experimental native Rust daemon that communicates with Chrome directly via CDP, bypassing Node.js and Playwright entirely. It is opt-in and not recommended for production use yet.
bash
1# Enable via flag
2agent-browser --native open example.com
3
4# Enable via environment variable (avoids passing --native every time)
5export AGENT_BROWSER_NATIVE=1
6agent-browser open example.com
The native daemon supports Chromium and Safari (via WebDriver). Firefox and WebKit are not yet supported. All core commands (navigate, snapshot, click, fill, screenshot, cookies, storage, tabs, eval, etc.) work identically in native mode. Use agent-browser close before switching between native and default mode within the same session.
Ready-to-Use Templates
bash
1./templates/form-automation.sh https://example.com/form
2./templates/authenticated-session.sh https://app.example.com/login
3./templates/capture-workflow.sh https://example.com ./output