Skip to content
Back to search

cdp

SkillWorks with Claude CodeGitHub

Drive Chrome via the DevTools Protocol from JavaScript. Run JS snippets through the `browser-harness-js` CLI — it auto-spawns a long-lived bun HTTP server holding a fully-typed CDP `Session`, and every call (`browser-harness-js 'await session.Page.navigate(...)'`) executes against the same persistent connection. Session, active target, and globals survive across calls. Use when the user wants to automate, script, or inspect a Chrome browser via CDP — single tab or multi-tab, attach to existing Chrome or to a new one launched with --remote-debugging-port.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/browser-use/browser-harness-js with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/browser-use/browser-harness-js'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/browser-use--browser-harness-js/badge.svg)](/listings/browser-use--browser-harness-js)

HTML

<a href="/listings/browser-use--browser-harness-js"><img src="/api/listings/browser-use--browser-harness-js/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

npx skills add https://github.com/browser-use/browser-harness-js --skill cdp

Or paste this into your agent — it'll install the skill, put the CLI on your PATH, and run a first task:

Run `npx skills add https://github.com/browser-use/browser-harness-js --skill cdp`, then
symlink `browser-harness-js` into a directory on my PATH, then use the cdp skill to drive
my browser: look at all the tabs I have open, group them by topic, and screenshot the most
interesting one.

(The CLI auto-installs [`bun`](https://bun.sh) on first run if it's missing. Set `BROWSER_HARNESS_SKIP_BUN_INSTALL=1` to opt out.)

If Chrome asks you to tick a remote-debugging checkbox, do it — that's how the agent attaches:

See [interaction-skills/](interaction-skills/) for recipes on the mechanics that are not obvious from the CDP method list alone.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 250 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. ---
  2. name: cdp
  3. description: Drive Chrome via the DevTools Protocol from JavaScript. Run JS snippets through the `browser-harness-js` CLI — it auto-spawns a long-lived bun HTTP server holding a fully-typed CDP `Session`, and every call (`browser-harness-js 'await session.Page.navigate(...)'`) executes against the same persistent connection. Session, active target, and globals survive across calls. Use when the user wants to automate, script, or inspect a Chrome browser via CDP — single tab or multi-tab, attach to existing Chrome or to a new one launched with --remote-debugging-port.
  4. ---
  5. # CDP — `browser-harness-js` skill
  6. Custom codegen'd CDP SDK (every method from browser_protocol.json + js_protocol.json gets a typed wrapper) plus a tiny HTTP server that holds one persistent CDP `Session`. The `browser-harness-js` CLI auto-starts the server on first use and forwards JS snippets to it.
  7. The SDK lives in the skill's `sdk/` directory. In the rest of this doc, `<skill-dir>` refers to wherever `npx skills add` installed the skill (Claude Code: `~/.claude/skills/cdp`; Cursor: `~/.cursor/skills/cdp`; other agents vary). The CLI should be on PATH as `browser-harness-js`.
  8. ## Setup (once, first use)
  9. `npx skills add` drops the skill into your agent's skills directory but does NOT put the CLI on PATH. Before the first call, verify it's reachable and symlink it into any directory on your PATH if not:
  10. ```bash
  11. # macOS (Apple Silicon + Homebrew)
  12. command -v browser-harness-js >/dev/null || ln -sf <skill-dir>/sdk/browser-harness-js /opt/homebrew/bin/browser-harness-js
  13. # macOS (Intel) / most Linux — may need sudo
  14. command -v browser-harness-js >/dev/null || ln -sf <skill-dir>/sdk/browser-harness-js /usr/local/bin/browser-harness-js
  15. # Linux without sudo (ensure ~/.local/bin is on PATH)
  16. command -v browser-harness-js >/dev/null || { mkdir -p ~/.local/bin && ln -sf <skill-dir>/sdk/browser-harness-js ~/.local/bin/browser-harness-js; }
  17. ```
  18. The CLI auto-installs `bun` on first run if it's missing (the server is Bun-native). Set `BROWSER_HARNESS_SKIP_BUN_INSTALL=1` to opt out.
  19. ## How to use
  20. Just run `browser-harness-js '<JS>'`. The first call spawns the server in the background; subsequent calls hit the same process and so reuse the same `session`, the same WebSocket to Chrome, and any globals you set.
  21. ```bash
  22. browser-harness-js 'await session.connect()'
  23. browser-harness-js 'await session.Page.navigate({url:"https://example.com"})'
  24. browser-harness-js '(await session.Runtime.evaluate({expression:"document.title",returnByValue:true})).result.value'
  25. ```
  26. Output is the **raw result content** — no `{ok,result}` envelope.
  27. | Result type | stdout |
  28. |---|---|
  29. | string | bare text, no JSON quotes (e.g. `Example Domain`) |
  30. | number / boolean | `42`, `true` |
  31. | object / array (non-empty) | compact JSON (e.g. `{"frameId":"..."}`, `[1,2,3]`) |
  32. | `undefined` / `null` / `""` / `{}` / `[]` | empty (no output) |
  33. **Errors** go to **stderr**, exit code `1`. The CDP error message and JS stack are printed verbatim, e.g.:
  34. ```
  35. Error: CDP -32602: invalid params
  36. at _call (.../session.ts:117:33)
  37. ...
  38. ```
  39. Detect failure with `if browser-harness-js '...'; then ...; else handle_error; fi` or by checking `$?`.
  40. **Multi-line snippets via stdin (heredoc).** Important: a multi-statement snippet does NOT auto-return the last expression — write `return X` explicitly. Single-expression snippets passed as the first argument DO auto-return.
  41. ```bash
  42. browser-harness-js <<'EOF'
  43. const tabs = await listPageTargets();
  44. globalThis.tid = tabs[0].targetId;
  45. await session.use(globalThis.tid);
  46. return globalThis.tid;
  47. EOF
  48. ```
  49. ## CLI commands
  50. | Command | Behavior |
  51. |---|---|
  52. | `browser-harness-js '<js>'` | Auto-start server if needed, eval the JS, print result. |
  53. | `browser-harness-js <<EOF…EOF` | Same, code from stdin. |
  54. | `browser-harness-js --status` | Print health JSON (uptime, connected, sessionId) or exit 1 if down. |
  55. | `browser-harness-js --start` | Explicit start (no-op if already running). |
  56. | `browser-harness-js --stop` | Graceful shutdown. Drops session state. |
  57. | `browser-harness-js --restart` | Stop + start fresh. |
  58. | `browser-harness-js --logs` | `tail -f` the server log (`/tmp/browser-harness-js.log`). |
  59. Env vars: `CDP_REPL_PORT` (default `9876`), `CDP_REPL_LOG` (default `/tmp/browser-harness-js.log`).
  60. ## API surface inside snippets
  61. These globals are pre-loaded — no imports needed:
  62. - `session` — the persistent `Session`. Has every CDP domain mounted: `session.Page`, `session.DOM`, `session.Runtime`, `session.Network`, … 56 domains, 652 methods total.
  63. - `listPageTargets()` — list real page targets via CDP's `Target.getTargets` (works on Chrome 144+ too), with `chrome://` and `devtools://` URLs filtered out. No args — uses the connected session.
  64. - `detectBrowsers()` — scan OS-specific profile dirs for running Chromium-based browsers with remote debugging on. Returns `[{name, profileDir, port, wsPath, wsUrl, mtimeMs}]`, sorted by most recently launched.
  65. - `resolveWsUrl(opts)` — resolve a WS URL from `{wsUrl}` | `{port, host?}` | `{profileDir}`. For the no-args auto-detect flow, call `session.connect()` directly instead.
  66. - `CDP` — the generated namespaces (`CDP.Page`, `CDP.Runtime`, …) for type-name reference.
  67. ### Calling a CDP method
  68. Every method takes a single object argument matching the CDP wire params; it resolves to the typed return value (no `result` envelope, no `id` correlation — handled for you).
  69. ```js
  70. // no params
  71. await session.DOM.enable()
  72. // required params
  73. await session.Page.navigate({ url: 'https://example.com' })
  74. // all-optional params (object also optional)
  75. await session.Page.captureScreenshot()
  76. await session.Page.captureScreenshot({ format: 'png', quality: 80 })
  77. // returns are stripped to the typed shape
  78. const { root } = await session.DOM.getDocument()
  79. const { nodeId } = await session.DOM.querySelector({ nodeId: root.nodeId, selector: 'h1' })
  80. ```
  81. ### Connecting
  82. **Default: just call `session.connect()` with no args.** It auto-detects running Chromium-based browsers (Chrome, Chromium, Edge, Brave, Arc, Vivaldi, Opera, Comet, Canary) by scanning OS-specific profile dirs for a `DevToolsActivePort` file, ordered by most-recently-launched, and picks the first one whose WebSocket accepts. OS-agnostic — works on macOS, Linux, Windows.
  83. ```js
  84. await session.connect() // auto-detect
  85. ```
  86. Use `detectBrowsers()` first if you want to see what's available (or let the user pick) before connecting:
  87. ```js
  88. const found = await detectBrowsers()
  89. // [{ name: 'Google Chrome', profileDir, port, wsPath, wsUrl, mtimeMs }, ...]
  90. ```
  91. **Explicit forms** — use these only when auto-detect picks the wrong browser, or when you already know where to connect:
  92. | Form | When to use |
  93. |---|---|
  94. | `{ profileDir }` | Target a specific browser when several are running. Reads `<profileDir>/DevToolsActivePort` directly. |
  95. | `{ wsUrl }` | You already have `ws://…/devtools/browser/<uuid>` (e.g. piped from elsewhere). |
  96. ```js
  97. await session.connect({ profileDir: '/Users/<you>/Library/Application Support/Google/Chrome' })
  98. await session.connect({ wsUrl: 'ws://127.0.0.1:9222/devtools/browser/<uuid>' })
  99. ```
  100. Profile paths by OS — use these with `{ profileDir }`:
  101. - macOS: `~/Library/Application Support/<Browser>` (e.g. `Google/Chrome`, `Comet`, `BraveSoftware/Brave-Browser`, `Arc/User Data`)
  102. - Linux: `~/.config/<browser>` (e.g. `google-chrome`, `chromium`, `BraveSoftware/Brave-Browser`)
  103. - Windows: `%LOCALAPPDATA%\<Browser>\User Data` (e.g. `Google\Chrome`, `Microsoft\Edge`, `BraveSoftware\Brave-Browser`)
  104. Per-candidate WS-open timeout defaults to **5s** — live browsers answer with open/close within ~100ms, so 5s is already generous. The only case where 5s is too short is when Chrome is showing the **Allow** popup and waiting on the user to click. If you expect that, pass `timeoutMs: 30000`:
  105. ```js
  106. await session.connect({ profileDir: '/Users/<you>/Library/Application Support/Google/Chrome', timeoutMs: 30_000 })
  107. ```
  108. **If you see `No detected browser accepted a connection`** — the browsers have `DevToolsActivePort` files but none are currently serving WS. Most common cause: remote-debugging is enabled but the user hasn't clicked **Allow** on the prompt yet. Tell them to click Allow, then retry (or bump `timeoutMs`).
  109. ### Picking a target (tab)
  110. After `connect()`, call `session.use(targetId)` once; subsequent page-level calls (Page/DOM/Runtime/Network/etc.) auto-route to that target's sessionId. `Browser.*` and `Target.*` calls always hit the browser endpoint.
  111. ```js
  112. const tabs = await listPageTargets() // no args; uses the connected session
  113. const sid = await session.use(tabs[0].targetId)
  114. await session.Page.enable()
  115. await session.Page.navigate({ url: 'https://example.com' })
  116. ```
  117. `listPageTargets()` uses CDP's `Target.getTargets` (not `/json`), so it works on Chrome 144+ too. It already filters out `chrome://` and `devtools://` URLs. Equivalent raw call:
  118. ```js
  119. const { targetInfos } = await session.Target.getTargets({})
  120. const tabs = targetInfos.filter(t => t.type === 'page' && !t.url.startsWith('chrome://') && !t.url.startsWith('devtools://'))
  121. ```
  122. To switch tabs: `session.use(otherTargetId)`. To detach: `session.setActiveSession(undefined)`.
  123. ### Events
  124. ```js
  125. // Subscribe (returns an unsubscribe fn)
  126. const off = session.onEvent((method, params, sessionId) => { ... })
  127. // Or wait for a single matching event with optional predicate + timeout
  128. await session.Network.enable()
  129. const ev = await session.waitFor(
  130. 'Page.frameNavigated',
  131. (p) => p.frame.url.includes('example.com'),
  132. 10_000
  133. )
  134. ```
  135. ### Persisting state across calls
  136. Each snippet runs inside its own async wrapper, so its `let`/`const` declarations vanish when it returns. To carry data forward, attach to `globalThis`:
  137. ```bash
  138. browser-harness-js '(await listPageTargets()).forEach((t,i)=>globalThis["tab"+i]=t.targetId)'
  139. browser-harness-js 'await session.use(globalThis.tab0)'
  140. browser-harness-js 'await session.Page.navigate({url:"https://example.com"})'
  141. ```
  142. `session` itself, the active sessionId, and event subscribers are already preserved by the server — globals are only needed for ad-hoc data.
  143. ## Connecting to a running Chrome (chrome://inspect flow)
  144. When attaching to the user's already-running browser:
  145. 1. **Try `await session.connect()` first** (no args) — auto-detect handles every Chromium-based browser via `DevToolsActivePort`. If it returns, you're done.
  146. 2. **If auto-detect fails** with `No running browser with remote debugging detected`, the user needs to turn it on. Open the inspect page:
  147. ```bash
  148. # macOS — prefer AppleScript over `open -a` (reuses current profile, avoids the profile picker)
  149. osascript -e 'open location "chrome://inspect/#remote-debugging"'
  150. # Linux
  151. google-chrome 'chrome://inspect/#remote-debugging' # or: chromium, google-chrome-stable
  152. # Windows (PowerShell)
  153. Start-Process chrome 'chrome://inspect/#remote-debugging'
  154. ```
  155. Only macOS's AppleScript path avoids the profile picker; Linux/Windows may prompt the user to pick a profile first.
  156. 3. **Tick "Discover network targets"** in chrome://inspect, then click **Allow** when Chrome prompts.
  157. 4. **If auto-detect picks the wrong browser** (multiple running, you want a specific one): list them with `await detectBrowsers()`, then `await session.connect({ profileDir: <the one you want> })`.
  158. 5. **If `session.connect()` returns `No detected browser accepted a connection`**, the user has remote-debugging on but hasn't clicked **Allow** yet. Tell them to click it and retry, or pass `timeoutMs: 30000` to wait for the click.
  159. ## Working with targets (tabs)
  160. - **Filter Chrome internals.** `listPageTargets()` already drops `chrome://` and `devtools://` URLs. If you call `Target.getTargets()` directly, filter manually.
  161. - **CDP target order ≠ visible tab-strip order.** When the user says "the first tab I can see", use a screenshot or page title to identify it — `Target.activateTarget` only switches to a known targetId.
  162. ## Looking up a method
  163. The full typed surface is in `<skill-dir>/sdk/generated.ts` (~655 KB, only loaded if you read it). Each method has its CDP description as a JSDoc comment plus typed `*Params` / `*Return` interfaces in per-domain namespaces.
  164. ```bash
  165. grep -n "navigate" <skill-dir>/sdk/generated.ts | head
  166. ```
  167. ## Regenerating the SDK
  168. When the upstream protocol JSONs change, replace `sdk/browser_protocol.json` and/or `sdk/js_protocol.json` and re-run:
  169. ```bash
  170. cd <skill-dir>/sdk && bun gen.ts
  171. browser-harness-js --restart # pick up the new bindings
  172. ```
  173. ## Files
  174. All paths are relative to `<skill-dir>` (the install path — see top of this doc).
  175. - `/usr/local/bin/browser-harness-js` → `<skill-dir>/sdk/browser-harness-js` (the CLI)
  176. - `sdk/repl.ts` — HTTP server (`Bun.serve` on `127.0.0.1:9876`)
  177. - `sdk/session.ts` — `Session` class (transport, connect, target routing, events)
  178. - `sdk/generated.ts` — codegen output: every CDP method as a typed wrapper
  179. - `sdk/gen.ts` — codegen script
  180. - `sdk/{browser,js}_protocol.json` — upstream protocol (vendored)
README.md · README · 94 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. <img src="https://r2.browser-use.com/github/asbfgihsbfbaosfjla.png" alt="Browser Harness" width="100%" />
  2. > [!IMPORTANT]
  3. > **This repo is no longer the recommended path. Use [Browser Use](https://github.com/browser-use/browser-use).** Browser Use 1.0 is where this work continues: your coding agent drives Chrome over raw CDP with the browser-harness helpers, by piping Python to the `browser-use` CLI or through its MCP server.
  4. >
  5. > ```bash
  6. > uv tool install browser-use
  7. > browser-use <<'PY'
  8. > new_tab("https://example.com")
  9. > print(page_info())
  10. > PY
  11. > ```
  12. >
  13. > MCP server: `browser-use --cli-mcp`. This repo stays up as the JS/TS CDP bridge, for reference.
  14. # Browser Harness JS ♞
  15. The thinnest possible bridge from the LLM to Chrome. **No harness, no recipes, no rails** — just every CDP method as a typed JS call.
  16. One persistent WebSocket, 56 domains, 652 typed wrappers, zero wrapping of what Chrome already does.
  17. ```
  18. ● agent: wants to click a button
  19. │
  20. ● no click() helper, no upload_file(), no goto()
  21. │
  22. ● agent writes the CDP call itself await session.Input.dispatchMouseEvent({...})
  23. │ await session.DOM.setFileInputFiles({...})
  24. ✓ done — same pattern for all 652 methods
  25. ```
  26. **The protocol is the API.** If Chrome can do it, you can call it.
  27. ## Installation (legacy)
  28. For new setups use [Browser Use](https://github.com/browser-use/browser-use) (see the top of this page). To run this repo anyway:
  29. ```bash
  30. npx skills add https://github.com/browser-use/browser-harness-js --skill cdp
  31. ```
  32. Or paste this into your agent — it'll install the skill, put the CLI on your PATH, and run a first task:
  33. ```text
  34. Run `npx skills add https://github.com/browser-use/browser-harness-js --skill cdp`, then
  35. symlink `browser-harness-js` into a directory on my PATH, then use the cdp skill to drive
  36. my browser: look at all the tabs I have open, group them by topic, and screenshot the most
  37. interesting one.
  38. ```
  39. (The CLI auto-installs [`bun`](https://bun.sh) on first run if it's missing. Set `BROWSER_HARNESS_SKIP_BUN_INSTALL=1` to opt out.)
  40. If Chrome asks you to tick a remote-debugging checkbox, do it — that's how the agent attaches:
  41. <img src="docs/setup-remote-debugging.png" alt="Remote debugging setup" width="520" style="border-radius: 12px;" />
  42. See [interaction-skills/](interaction-skills/) for recipes on the mechanics that are not obvious from the CDP method list alone.
  43. ## Files
  44. - `SKILL.md` — day-to-day usage; how to connect, pick a tab, call methods, persist state
  45. - `sdk/browser-harness-js` — tiny CLI that auto-spawns the server and forwards snippets
  46. - `sdk/repl.ts` — Bun HTTP server holding one persistent `Session`
  47. - `sdk/session.ts` — the `Session` class: transport, connect, target routing, events
  48. - `sdk/gen.ts` — codegen: reads `browser_protocol.json` + `js_protocol.json` → typed wrappers
  49. - `sdk/generated.ts` — every CDP method as `session.<Domain>.<method>(params)` (generated)
  50. No helpers file. No `click()`, no `goto()`, no `upload_file()` — just the protocol, typed.
  51. ## Why no pre-baked helpers?
  52. Every helper is a lie about what CDP already gives you. `click(x, y)` hides `Input.dispatchMouseEvent` — which has 14 parameters the LLM might need (button, clickCount, modifiers, pointerType, force, tangentialPressure, …). A harness that exposes three of them quietly limits what the agent can do.
  53. - Types are the docs. `session.Page.navigate(` triggers autocomplete with the exact params — same JSDoc as the CDP reference.
  54. - No version drift. The SDK is regenerated from the upstream protocol JSON; new Chrome methods appear as soon as you swap the JSON.
  55. - No "helper doesn't handle my case" detours. If CDP can do it, the agent can call it — directly, typed, today.
  56. The only "helpers" you'll find are things CDP itself is missing:
  57. - `listPageTargets()` — filters `chrome://` / `devtools://` out of `Target.getTargets`
  58. - `resolveWsUrl({wsUrl|port|profileDir})` — reads `DevToolsActivePort` for Chrome 144+
  59. - `session.use(targetId)` / `session.waitFor(method, pred, timeout)` — the two routing primitives you genuinely need
  60. ## Contributing
  61. PRs welcome. The best way to help: **contribute a new interaction skill** under [interaction-skills/](interaction-skills/) when you figure out the CDP recipe for something non-obvious (a dropdown framework, a shadow-DOM trap, a network-wait pattern).
  62. - Keep recipes in **pure CDP** — `session.Domain.method(...)`, not wrapped helpers.
  63. - Lead with the shortest method call that works; add the workaround or trap afterwards.
  64. - Small and focused beats comprehensive. One mechanic per file.
  65. - Bug fixes, codegen improvements, and `session.ts` refinements are equally welcome.
  66. ---
  67. [Bitter lesson](https://browser-use.com/posts/bitter-lesson-agent-frameworks) · [Skills](https://browser-use.com/posts/web-agents-that-actually-learn)

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.