
browser-cdp
PopularUse this skill when you need to control a Chrome browser via CDP (Chrome DevTools Protocol) to reuse existing login sessions. Covers: launching Chrome in debug mode, opening URLs, waiting for page load, evaluating JavaScript, taking snapshots, and extracting auth tokens. Trigger phrases: browser automation, CDP, agent-browser, browser operations, control browser, Chrome CDP, reuse login state, extract token from browser.
Related Skills
Use this skill when you need to control a Chrome browser via CDP (Chrome DevTools Protocol) to reuse existing login sessions. Covers: launching Chrome in debug mode, opening URLs, waiting for page load, evaluating JavaScript, taking snapshots, and extracting auth tokens. Trigger phrases: browser automation, CDP, agent-browser, browser operations, control browser, Chrome CDP, reuse login state, extract token from browser.
Browser CDP Automation Tool
Control Chrome via the CDP protocol to reuse existing login sessions and run browser automation workflows.
Prerequisites
- macOS / Linux / Windows (experimental), with Google Chrome installed
- Node.js 20+
agent-browserinstalled:npm install -g agent-browser
⚠️ Initial launch will kill the user's regular Chrome instances. You must ask for explicit user consent before launching (see "Launch Workflow" below); otherwise, the user may lose unsaved tabs or drafts.
Launch Workflow (Mandatory Steps for skill-mode)
Step 1: Detect current state (side-effect free)
node {SKILL_DIR}/scripts/setup-cdp-chrome.js 9222 --detect-only
Output format example:
CDP_STATUS=ready # Ready, can reuse directly
CDP_URL=http://127.0.0.1:9222/json/version
BROWSER=Chrome/148.0.7778.168
Or:
CDP_STATUS=needs-setup
CHROME_RUNNING=yes # User has running Chrome instances; launching will kill them
CHROME_PID_COUNT=3
Step 2: Branch based on detection result
CDP_STATUS=ready→ Useagent-browser --cdp 9222 ...directly; do not run setup.CDP_STATUS=needs-setupandCHROME_RUNNING=no→ Safe to launch:node {SKILL_DIR}/scripts/setup-cdp-chrome.js 9222 --yesCDP_STATUS=needs-setupandCHROME_RUNNING=yes→ First use the AskUserQuestion tool to confirm with the user: Inform them that N Chrome processes will be terminated and unsaved work might be lost. Only pass--yesto launch if the user agrees. If the user declines, abort the automation run.
Why you cannot directly pass --yes: In non-TTY environments (such as skill mode / Bash tool), if the script detects running Chrome processes without --yes, it exits with code 3 reporting NEEDS_CONSENT: ... and aborts, without silently killing processes. This is an intentional fallback mechanism—the skill workflow must still ask the user first rather than blindly passing --yes upon encountering code 3.
Launch Script Options
| Option | Description |
|---|---|
--detect-only |
Detect state only; does not modify anything (for skill usage) |
--yes |
Consent obtained; skip interactive prompt |
--reset |
Clear ~/chrome-debug-profile before launching (used when login session expires) |
--profile <name> |
Use a non-default Chrome profile (e.g., "Profile 1") |
--dry-run |
Print execution steps without running them |
Exit codes: 0 Success / 1 General error / 2 Declined by user (TTY) / 3 Consent required but --yes missing.
Common Operations
Open Page and Wait for Load
agent-browser --cdp 9222 open "<URL>"
agent-browser --cdp 9222 wait 3000
Extract Page Text
agent-browser --cdp 9222 eval 'document.body.innerText.substring(0, 8000)'
Extract Auth Token
agent-browser --cdp 9222 eval 'localStorage.getItem("token") || document.cookie'
Complex JS (Containing Quotes / $ / Backticks)
Shell escaping can be error-prone. Use one of the following two methods:
# 1) Base64 wrapper
agent-browser --cdp 9222 eval -b "$(echo -n "document.querySelectorAll('a').length" | base64)"
# 2) Heredoc + --stdin
cat <<'EOF' | agent-browser --cdp 9222 eval --stdin
const links = document.querySelectorAll('a');
links.length;
EOF
Page Interaction (Get Element Reference via Snapshot)
agent-browser --cdp 9222 snapshot -i # Interactive elements only
agent-browser --cdp 9222 click "<CSS or @e1>"
agent-browser --cdp 9222 type "<sel>" "<text>"
Stop / Cleanup
- Simply close the debug Chrome window. If the window is unresponsive, verify the PID associated with
--user-data-dirfirst and kill only that debug instance:- macOS / Linux:
pgrep -af chrome-debug-profile - Windows:
wmic process where "name='chrome.exe'" get ProcessId,CommandLine | findstr chrome-debug-profile
After obtaining the PID, runkill -9 {PID}/taskkill /F /PID {PID}. If ownership cannot be verified, stop immediately. Manual troubleshooting must not kill processes in bulk by executable name—that would terminate regular user Chrome instances.
Exception:setup-cdp-chrome.js --resetinternally performs a one-time process cleanup by executable name as part of the skill's explicit launch workflow requiring user consent via--yes. Do not copy this pattern during manual troubleshooting.
- macOS / Linux:
- Expired login session:
node {SKILL_DIR}/scripts/setup-cdp-chrome.js 9222 --reset --yes(Note:--yesstill requires asking the user first).
OpenCode Environment Notes
OpenCode lacks a background command execution tool. Long-running CDP operations (such as waiting for page loads or fetching bulk data) will block the session, causing the CLI to become unresponsive.
Timeout Wrapper
On Windows, wrap CDP commands using PowerShell Job timeouts:
$job = Start-Job { agent-browser --cdp 9222 eval "window.location.replace('https://www.qidian.com/rank/')" }
Wait-Job $job -Timeout 30 | Out-Null
if ($job.State -eq 'Running') { Stop-Job $job; Write-Output "⏱ CDP operation timed out (30s). Please retry or interrupt manually." }
else { Receive-Job $job }
Remove-Job $job -Force
On macOS / Linux, use the timeout command:
timeout 30 agent-browser --cdp 9222 eval "window.location.replace('https://www.qidian.com/rank/')" || echo "⏱ CDP operation timed out (30s). Please retry or interrupt manually."
Known Limitations
Even with timeout wrappers, issues may still occur in the following scenarios:
| Scenario | Risk | Mitigation |
|---|---|---|
| Page load timeout | eval command waits indefinitely |
Set a 30s timeout; retry after timeout |
| Large dataset scraping | Cumulative wait time across pagination is too long | Use independent timeouts per page; resume from breakpoint upon failure |
| Unresponsive Chrome process | CDP connection breaks while process remains | Verify the PID corresponding to the debug profile, terminate only that instance, and reconnect. Do not touch regular Chrome instances |
| Network fluctuations | Request hangs without timing out | Automatically retry once after timeout |
If an operation hangs persistently, press ESC in opencode to manually interrupt it.
Frequently Asked Questions
| Issue | Solution |
|---|---|
NEEDS_CONSENT + Exit code 3 |
Ask the user for permission to terminate Chrome using AskUserQuestion. Rerun with --yes upon consent |
| CDP port not listening | Run --detect-only to verify. If port is occupied, switch to another port |
| Page redirects to login screen | Use snapshot -i to find and click the login button |
eval returns null |
Verify the localStorage key name. For JS containing quotes, use eval -b or --stdin |
| Login state expired | Run setup-cdp-chrome.js 9222 --reset --yes to re-copy |
| Multiple Chrome profiles exist | Specify the profile using --profile "Profile 1" |
| Chrome fails to start (30s timeout) | Try --reset; check for port conflicts; verify if ~/chrome-debug-profile/ is corrupted |





