SuperAPI AI Directory

browser-cdp

General & other

View repository

Updated 10-16 10:46

About this skill

Browser CDP Operation Tool

Connect to Chrome via CDP (Chrome DevTools Protocol), reuse the login state, and perform browser operations.

Prerequisites

  • macOS / Linux / Windows (experimental), Google Chrome installed and used before, source profile already exists
  • Node.js 20+
  • agent-browser installed:npm install -g agent-browser

When starting or rebuilding, if you need to end the Chrome process, first obtain consent according to the process below; unsaved tabs or drafts may be lost.


Startup Process (mandatory steps in skill-mode)

Step 1: Detect the current state (no side effects)

node {SKILL_DIR}/scripts/setup-cdp-chrome.js 9222 --detect-only

Output looks like:

CDP_STATUS=ready                        # 已就绪,可直接复用
CDP_URL=http://127.0.0.1:9222/json/version
BROWSER=Chrome/148.0.7778.168

Or:

CDP_STATUS=needs-setup
CHROME_RUNNING=yes                      # 用户有 Chrome 在跑,启动会杀掉
CHROME_PID_COUNT=3

Step 2: Branch based on the detection result

  • CDP_STATUS=ready and this time only need to connect → directly use agent-browser --cdp 9222 ...,Do not run setup。
  • Explicitly request --reset / --profile → even if ready, go through rebuild. Use --dry-run to view the processes that will be ended, and start with the originally intended options according to the consent process below.
  • CDP_STATUS=needs-setup and CHROME_RUNNING=no → safe start:
    node {SKILL_DIR}/scripts/setup-cdp-chrome.js 9222 --yes
    
  • CDP_STATUS=needs-setup and CHROME_RUNNING=yes → First confirm with the user: inform them that N Chrome processes will be ended and unsaved work may be lost; after consent, start with --yes , and if refused, abandon this automation.

In non-TTY calls, when Chrome is running and --yes is not passed, the script reports NEEDS_CONSENT: ... with exit code 3 and aborts. After obtaining consent, rerun; do not automatically add --yes。


Startup Script Options

Option Description
--detect-only Detect only, do not modify any state (used by skill)
--yes Consent already obtained, skip interactive prompt
--reset Clear before startup ~/chrome-debug-profile(use when login is invalid)
--profile <name> Specify source profile (default Default, e.g. "Profile 1"); passing it explicitly means rebuild
--dry-run Print the steps to be executed, do not execute

Exit codes:0 success / 1 general error / 2 user refused (TTY) / 3 consent required but missing --yes。


Common Operations

Open a page and wait for it to 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

Example reads the token item from localStorage or a JavaScript-readable Cookie; confirm the actual storage location per site.

agent-browser --cdp 9222 eval 'localStorage.getItem("token") || document.cookie'

Complex JS (containing quotes / $ / backticks)

Pass the script via base64 or standard input to avoid shell escaping errors:

# 1) base64 包裹
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 (snapshot to get element references)

agent-browser --cdp 9222 snapshot -i        # 仅交互元素
agent-browser --cdp 9222 click "<CSS or @e1>"
agent-browser --cdp 9222 type "<sel>" "<text>"

Stop / Cleanup

  • Just close the debug Chrome window. If the window is unresponsive, first follow --user-data-dir to verify the PID of the debug instance and then end only it:
    • macOS / Linux:pgrep -af chrome-debug-profile
    • Windows:wmic process where "name='chrome.exe'" get ProcessId,CommandLine | findstr chrome-debug-profile After verifying the PID, use kill -9 {PID} / taskkill /F /PID {PID}, and if it cannot be verified, stop.Manual cleanup must not batch-end processes by the Chrome executable name; the startup script still follows the consent process above.
  • Login state invalid:node {SKILL_DIR}/scripts/setup-cdp-chrome.js 9222 --reset --yes re-copy the source profile; if Chrome needs to be ended, still obtain consent first.

OpenCode Environment Notes

When executing time-consuming CDP commands in the OpenCode foreground, set timeouts for page loading and batch collection to avoid a single call occupying the session for a long time.

Timeout wrapper

Setting a timeout for PowerShell Job on Windows:

$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 操作超时(30s),请重试或手动打断" }
else { Receive-Job $job }
Remove-Job $job -Force

On macOS / Linux, use timeout when:

timeout 30 agent-browser --cdp 9222 eval "window.location.replace('https://www.qidian.com/rank/')" || echo "⏱ CDP 操作超时(30s),请重试或手动打断"

Known limitations

Scenario Risk Mitigation
Page load timeout The eval command waits forever and never returns Set a 30s timeout, and retry after timeout
Large-scale data scraping Cumulative waiting becomes too long when paging through multiple pages Set an independent timeout per page, and resume from the checkpoint after a failure
Chrome process hangs The CDP connection is disconnected but the process has not exited First verify the PID corresponding to the debug profile, and only terminate that debug instance before reconnecting; do not terminate regular Chrome as well
Network fluctuations Requests hang with no timeout Automatically retry once after timeout

If it remains stuck, in OpenCode press ESC to interrupt.


FAQ

Problem Solution
NEEDS_CONSENT + exit code 3 Ask the user whether to allow terminating the existing Chrome; after they agree, add --yes and rerun
CHROME_INSTALLED=no or the source profile does not exist Install and use Chrome once; if other profiles already exist, use --profile to specify
CDP port is not listening --detect-only Check again; if the port is occupied, switch to another port
The page redirects to the login page snapshot -i Find the login button and operate it
eval returns null Check the localStorage key name; for JS containing quotes, use eval -b or --stdin
Login state expired setup-cdp-chrome.js 9222 --reset --yes copy again
There are multiple Chrome profiles --profile "Profile 1" specify
Chrome does not start (30s timeout) Try --reset; check for port conflicts; check whether ~/chrome-debug-profile/ is corrupted