Piloter Chrome avec le protocole CDP

VérifiéPrudence

Automatisez, scriptez et inspectez Chrome via le protocole CDP en exécutant des snippets JavaScript avec le CLI browser-harness-js, qui maintient une session persistante.

Spar Skills Guide Bot
DeveloppementIntermédiaire
04/09/2026
Claude CodeCursor
#browser-automation#chrome-devtools-protocol#javascript#persistent-session#cli

Recommandé pour

Synthèse automatique

Pilote Chrome via le DevTools Protocol en exécutant des extraits JavaScript avec le CLI browser-harness-js, qui conserve une session CDP persistante entre les appels.

Points forts

  • SDK CDP typé couvrant les méthodes des protocoles browser et JS, avec des wrappers générés.
  • Le serveur persistant réutilise la même session, le même target actif et les globales entre les appels.
  • Prend en charge plusieurs onglets et l'attachement à un Chrome existant ou lancé avec --remote-debugging-port.
  • Le CLI accepte des extraits en argument ou via stdin/heredoc et renvoie le résultat brut, ce qui simplifie l'enchaînement dans un shell.

Limites

  • La première utilisation demande de rendre le CLI accessible sur le PATH, souvent via un lien symbolique, et peut installer bun automatiquement.
  • L'exécution de JavaScript arbitraire avec les privilèges du navigateur et un serveur HTTP local persistant impose de faire confiance à l'outil et de prévoir son arrêt ou son nettoyage.
  • Le SKILL.md fourni s'arrête au milieu de la table des commandes CLI, donc la surface complète des commandes n'est pas documentée ici.
Quand l'utiliser

À utiliser lorsqu'il faut automatiser ou inspecter Chrome de façon scriptée et avec état via CDP, plutôt qu'avec une bibliothèque d'automatisation de haut niveau.

Quand l'éviter

À éviter pour des tests navigateur déclaratifs simples ou lorsque l'environnement ne permet pas de lancer Chrome avec le débogage distant.

Analyse de sécurité

Prudence
Score qualité84/100

This is a legitimate, purpose-built browser automation harness, and nothing here is obfuscated, destructive (no rm -rf, no curl|sh piping of remote scripts into a shell), or designed to exfiltrate secrets. However, it deliberately grants full CDP control over the user's primary Chrome profile, auto-installs a runtime, and runs a long-lived unauthenticated eval server on localhost — powerful capabilities that warrant 'caution' rather than 'safe'.

Points d'attention
  • •The skill's core function is executing arbitrary JavaScript against a live Chrome DevTools session, giving full read/write control over whatever the browser is logged into (cookies, tokens, authenticated pages). No malicious use is instructed, but the capability is effectively total control of the user's browsing session.
  • •First run auto-installs the Bun runtime (network fetch + execute) without an explicit prompt; BROWSER_HARNESS_SKIP_BUN_INSTALL=1 exists but is mentioned only in passing.
  • •A persistent, unauthenticated HTTP endpoint (Bun.serve on 127.0.0.1:9876) accepts and evals JS for the lifetime of the machine session; any local process could submit snippets to the attached browser. Default log path /tmp/browser-harness-js.log may be world-readable.
  • •Setup instructs symlinking the CLI into /usr/local/bin (potentially via sudo) and shell commands such as osascript / Start-Process to open chrome://inspect — legitimate but host-modifying steps an agent will perform unprompted.
  • •Attaching to an already-running browser relies on the user clicking Chrome's 'Allow' prompt; without it the harness can't connect, but once granted there is no scoping of what the snippet may do.
  • •Auto-installs `bun` on first run (remote installer executed without user confirmation) unless `BROWSER_HARNESS_SKIP_BUN_INSTALL=1` is set — an unsupervised download-and-execute step at first use.
  • •Setup instructions tell the agent to create symlinks into system PATH locations (`/usr/local/bin`, `/opt/homebrew/bin`), explicitly noting sudo may be needed — system-level modification performed by an automated agent.
  • •The skill starts an unauthenticated local HTTP server on `127.0.0.1:9876` that evaluates arbitrary JavaScript against a live CDP session; any local process (or a browser page via DNS-rebinding-style attacks on localhost) could drive the browser with the same privileges.
  • •`session.connect()` defaults to attaching to the user's already-running browser, granting full control over authenticated sessions (cookies, logged-in tabs, page contents) — high-impact capability if the agent is prompt-injected or misdirected by page content.
  • •Arbitrary code execution in pages via `session.Runtime.evaluate`, plus `osascript`/`open`/`Start-Process` invocations to launch browser UI.
  • •No destructive, exfiltration, or obfuscation patterns found; no secrets are sent out by the skill itself.
Comment cette analyse est faite

Exemples

Navigate and read title
Using the cdp skill, connect to Chrome with browser-harness-js, navigate to https://example.com, and return the document title.
Attach to existing Chrome
Attach to the Chrome instance on port 9222 with browser-harness-js, list the page targets, and switch the persistent session to the first tab.
Inspect current page
Run a browser-harness-js snippet that evaluates document.querySelectorAll('a').length on the current page and prints the link count.

name: cdp 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.

CDP — browser-harness-js skill

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.

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.

Setup (once, first use)

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:

# macOS (Apple Silicon + Homebrew)
command -v browser-harness-js >/dev/null || ln -sf <skill-dir>/sdk/browser-harness-js /opt/homebrew/bin/browser-harness-js

# macOS (Intel) / most Linux — may need sudo
command -v browser-harness-js >/dev/null || ln -sf <skill-dir>/sdk/browser-harness-js /usr/local/bin/browser-harness-js

# Linux without sudo (ensure ~/.local/bin is on PATH)
command -v browser-harness-js >/dev/null || { mkdir -p ~/.local/bin && ln -sf <skill-dir>/sdk/browser-harness-js ~/.local/bin/browser-harness-js; }

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.

How to use

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.

browser-harness-js 'await session.connect()'
browser-harness-js 'await session.Page.navigate({url:"https://example.com"})'
browser-harness-js '(await session.Runtime.evaluate({expression:"document.title",returnByValue:true})).result.value'

Output is the raw result content — no {ok,result} envelope.

| Result type | stdout | |---|---| | string | bare text, no JSON quotes (e.g. Example Domain) | | number / boolean | 42, true | | object / array (non-empty) | compact JSON (e.g. {"frameId":"..."}, [1,2,3]) | | undefined / null / "" / {} / [] | empty (no output) |

Errors go to stderr, exit code 1. The CDP error message and JS stack are printed verbatim, e.g.:

Error: CDP -32602: invalid params
    at _call (.../session.ts:117:33)
    ...

Detect failure with if browser-harness-js '...'; then ...; else handle_error; fi or by checking $?.

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.

browser-harness-js <<'EOF'
const tabs = await listPageTargets();
globalThis.tid = tabs[0].targetId;
await session.use(globalThis.tid);
return globalThis.tid;
EOF

CLI commands

| Command | Behavior | |---|---| | browser-harness-js '<js>' | Auto-start server if needed, eval the JS, print result. | | browser-harness-js <<EOF…EOF | Same, code from stdin. | | browser-harness-js --status | Print health JSON (uptime, connected, sessionId) or exit 1 if down. | | browser-harness-js --start | Explicit start (no-op if already running). | | browser-harness-js --stop | Graceful shutdown. Drops session state. | | browser-harness-js --restart | Stop + start fresh. | | browser-harness-js --logs | tail -f the server log (/tmp/browser-harness-js.log). |

Env vars: CDP_REPL_PORT (default 9876), CDP_REPL_LOG (default /tmp/browser-harness-js.log).

API surface inside snippets

These globals are pre-loaded — no imports needed:

  • session — the persistent Session. Has every CDP domain mounted: session.Page, session.DOM, session.Runtime, session.Network, … 56 domains, 652 methods total.
  • 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.
  • 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.
  • resolveWsUrl(opts) — resolve a WS URL from {wsUrl} | {port, host?} | {profileDir}. For the no-args auto-detect flow, call session.connect() directly instead.
  • CDP — the generated namespaces (CDP.Page, CDP.Runtime, …) for type-name reference.

Calling a CDP method

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).

// no params
await session.DOM.enable()

// required params
await session.Page.navigate({ url: 'https://example.com' })

// all-optional params (object also optional)
await session.Page.captureScreenshot()
await session.Page.captureScreenshot({ format: 'png', quality: 80 })

// returns are stripped to the typed shape
const { root } = await session.DOM.getDocument()
const { nodeId } = await session.DOM.querySelector({ nodeId: root.nodeId, selector: 'h1' })

Connecting

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.

await session.connect()   // auto-detect

Use detectBrowsers() first if you want to see what's available (or let the user pick) before connecting:

const found = await detectBrowsers()
// [{ name: 'Google Chrome', profileDir, port, wsPath, wsUrl, mtimeMs }, ...]

Explicit forms — use these only when auto-detect picks the wrong browser, or when you already know where to connect:

| Form | When to use | |---|---| | { profileDir } | Target a specific browser when several are running. Reads <profileDir>/DevToolsActivePort directly. | | { wsUrl } | You already have ws://…/devtools/browser/<uuid> (e.g. piped from elsewhere). |

await session.connect({ profileDir: '/Users/<you>/Library/Application Support/Google/Chrome' })
await session.connect({ wsUrl: 'ws://127.0.0.1:9222/devtools/browser/<uuid>' })

Profile paths by OS — use these with { profileDir }:

  • macOS: ~/Library/Application Support/<Browser> (e.g. Google/Chrome, Comet, BraveSoftware/Brave-Browser, Arc/User Data)
  • Linux: ~/.config/<browser> (e.g. google-chrome, chromium, BraveSoftware/Brave-Browser)
  • Windows: %LOCALAPPDATA%\<Browser>\User Data (e.g. Google\Chrome, Microsoft\Edge, BraveSoftware\Brave-Browser)

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:

await session.connect({ profileDir: '/Users/<you>/Library/Application Support/Google/Chrome', timeoutMs: 30_000 })

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).

Picking a target (tab)

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.

const tabs = await listPageTargets()                     // no args; uses the connected session
const sid  = await session.use(tabs[0].targetId)
await session.Page.enable()
await session.Page.navigate({ url: 'https://example.com' })

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:

const { targetInfos } = await session.Target.getTargets({})
const tabs = targetInfos.filter(t => t.type === 'page' && !t.url.startsWith('chrome://') && !t.url.startsWith('devtools://'))

To switch tabs: session.use(otherTargetId). To detach: session.setActiveSession(undefined).

Events

// Subscribe (returns an unsubscribe fn)
const off = session.onEvent((method, params, sessionId) => { ... })

// Or wait for a single matching event with optional predicate + timeout
await session.Network.enable()
const ev = await session.waitFor(
  'Page.frameNavigated',
  (p) => p.frame.url.includes('example.com'),
  10_000
)

Persisting state across calls

Each snippet runs inside its own async wrapper, so its let/const declarations vanish when it returns. To carry data forward, attach to globalThis:

browser-harness-js '(await listPageTargets()).forEach((t,i)=>globalThis["tab"+i]=t.targetId)'
browser-harness-js 'await session.use(globalThis.tab0)'
browser-harness-js 'await session.Page.navigate({url:"https://example.com"})'

session itself, the active sessionId, and event subscribers are already preserved by the server — globals are only needed for ad-hoc data.

Connecting to a running Chrome (chrome://inspect flow)

When attaching to the user's already-running browser:

  1. Try await session.connect() first (no args) — auto-detect handles every Chromium-based browser via DevToolsActivePort. If it returns, you're done.
  2. If auto-detect fails with No running browser with remote debugging detected, the user needs to turn it on. Open the inspect page:
    # macOS — prefer AppleScript over `open -a` (reuses current profile, avoids the profile picker)
    osascript -e 'open location "chrome://inspect/#remote-debugging"'
    
    # Linux
    google-chrome 'chrome://inspect/#remote-debugging'     # or: chromium, google-chrome-stable
    
    # Windows (PowerShell)
    Start-Process chrome 'chrome://inspect/#remote-debugging'
    
    Only macOS's AppleScript path avoids the profile picker; Linux/Windows may prompt the user to pick a profile first.
  3. Tick "Discover network targets" in chrome://inspect, then click Allow when Chrome prompts.
  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> }).
  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.

Working with targets (tabs)

  • Filter Chrome internals. listPageTargets() already drops chrome:// and devtools:// URLs. If you call Target.getTargets() directly, filter manually.
  • 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.

Looking up a method

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.

grep -n "navigate" <skill-dir>/sdk/generated.ts | head

Regenerating the SDK

When the upstream protocol JSONs change, replace sdk/browser_protocol.json and/or sdk/js_protocol.json and re-run:

cd <skill-dir>/sdk && bun gen.ts
browser-harness-js --restart   # pick up the new bindings

Files

All paths are relative to <skill-dir> (the install path — see top of this doc).

  • /usr/local/bin/browser-harness-js → <skill-dir>/sdk/browser-harness-js (the CLI)
  • sdk/repl.ts — HTTP server (Bun.serve on 127.0.0.1:9876)
  • sdk/session.ts — Session class (transport, connect, target routing, events)
  • sdk/generated.ts — codegen output: every CDP method as a typed wrapper
  • sdk/gen.ts — codegen script
  • sdk/{browser,js}_protocol.json — upstream protocol (vendored)

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/drive-chrome-via-the-devtools-protocol-mtmi9ajc/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/drive-chrome-via-the-devtools-protocol-mtmi9ajc' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/drive-chrome-via-the-devtools-protocol-mtmi9ajc/download' --output '.skill-downloads/drive-chrome-via-the-devtools-protocol-mtmi9ajc/SKILL.md.part' && mv '.skill-downloads/drive-chrome-via-the-devtools-protocol-mtmi9ajc/SKILL.md.part' '.skill-downloads/drive-chrome-via-the-devtools-protocol-mtmi9ajc/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/drive-chrome-via-the-devtools-protocol-mtmi9ajc/SKILL.md' && test -s '.skill-downloads/drive-chrome-via-the-devtools-protocol-mtmi9ajc/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/cdp' && cp -R '.skill-downloads/drive-chrome-via-the-devtools-protocol-mtmi9ajc' '.claude/skills/cdp'

Cursor
test -f '.skill-downloads/drive-chrome-via-the-devtools-protocol-mtmi9ajc/SKILL.md' && test -s '.skill-downloads/drive-chrome-via-the-devtools-protocol-mtmi9ajc/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/cdp' && cp -R '.skill-downloads/drive-chrome-via-the-devtools-protocol-mtmi9ajc' '.cursor/skills/cdp'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/drive-chrome-via-the-devtools-protocol-mtmi9ajc'

openskills read 'drive-chrome-via-the-devtools-protocol-mtmi9ajc'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/drive-chrome-via-the-devtools-protocol-mtmi9ajc/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires