Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Browser Session Via Cdp?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/rafaelrr5-browser-session-via-cdp)
---
name: browser-session-via-cdp
description: "Drive a real logged-in Chrome/Edge over the DevTools Protocol when no API covers the job."
version: 1.0.0
author: Rafael Rocha Ribeiro (github.com/Rafaelrr5)
license: MIT
platforms: [linux, macos, windows]
metadata:
agent:
tags: [cdp, chromium, chrome, edge, browser, automation, session, login]
related_skills: [blocked-page-recovery, windows-desktop-automation]
---
# Drive a logged-in Chromium browser over CDP
Automate a real browser tab by speaking the Chrome DevTools Protocol (CDP) over
its HTTP + WebSocket endpoint: navigation, DOM reads, clicks, typed input, file
uploads. No extension, no scraping API.
## When to Use
- the site needs a login session the user holds in a real browser, and
- no public API covers the operation (an account settings page, a dashboard,
a web-only publishing flow).
Do not use it when a headless browser tool already reaches the page, or when the
operation has a clean API. Driving a real browser is the heavier, riskier path,
and heavy automation of a personal account can break the site's terms.
## The constraint to plan around
From Chrome 136, `--remote-debugging-port` and `--remote-debugging-pipe` are
ignored when Chrome runs on its default user data directory; they only work with
`--user-data-dir` pointing at a non-standard directory, which gets a different
encryption key ([Chrome for Developers, "Changes to remote debugging switches to
improve security"](https://developer.chrome.com/blog/remote-debugging-port)).
So you cannot attach a debug port to the user's everyday profile. Other
Chromium browsers may behave the same; confirm with `/json/version` rather than
assuming.
## Check first: is the user already on the page?
Look at the user's existing browser before launching anything or asking for a
login. If the site is already open and authenticated and you have a desktop
driver that can click the open window, use that. A dedicated debug profile
starts with an empty session (the site drops to its login or QR screen), it is
a second window the user may close mid-task (the port dies under you), and
opening windows on top of "it's already open" earns a correction.
If the user names a route (an MCP server, an existing endpoint) or forbids GUI
control, follow it. A separate process does not inherit the browser's session:
verify real authentication before claiming access. If cookie extraction is
blocked by security software, report the blocker; do not disable protection or
swap in another extractor to get around it.
Use the dedicated profile when nothing is open yet, or when you need DOM and JS
evaluation that an accessibility tree cannot give you.
## Procedure: dedicated profile + one manual login
1. **Close every process of that browser**, in a loop until none remain.
Background modes (Edge Startup Boost, "continue running in background")
relaunch processes seconds after a single kill. A survivor owns the
singleton lock, and your next launch hands its command line to it and exits,
dropping your flags.
2. **Launch with a dedicated data dir:**
```bash
chrome --remote-debugging-port=9222 \
--user-data-dir="<a folder of its own, e.g. ~/.cdp-profiles/site-name>" \
--no-first-run --no-default-browser-check
```
If the WebSocket handshake later returns `403 Forbidden` with a message
naming `--remote-allow-origins`, relaunch with that flag set to the origin
your client sends (`*` works but allows any page origin).
3. **Verify the port**: `curl -s http://localhost:9222/json/version` must return
JSON; `/json` lists the page targets with their `webSocketDebuggerUrl`.
4. **Navigate to the login URL and hand the window to the user for one manual
login.** Cookies persist in that profile, so later runs reuse them. Keep the
same `--user-data-dir` across runs and do not delete it.
A minimal client (Python, `websocket-client`):
```python
import json, urllib.request, websocket
tab = next(t for t in json.load(urllib.request.urlopen("http://localhost:9222/json"))
if t["type"] == "page")
ws = websocket.create_connection(tab["webSocketDebuggerUrl"])
_id = 0
def call(method, **params):
global _id; _id += 1
ws.send(json.dumps({"id": _id, "method": method, "params": params}))
while True:
msg = json.loads(ws.recv())
if msg.get("id") == _id:
return msg
call("Page.navigate", url="https://example.com/account")
print(call("Runtime.evaluate", expression="[location.href, document.title]",
returnByValue=True)["result"]["result"]["value"])
```
Write the driver as a `.py` file and run it. Inline `python -c` one-liners with
nested quotes break on the first edit, and a file keeps the helpers reusable
across steps.
## Verifying you are logged in
- Test success positively: the URL must be on the app (`host/dashboard`), not
merely "not `/login`". A fresh window exposes an `about:blank` target first;
a script that attaches at once and checks "no `/login`" reports success in
zero seconds while the real window sits on the login screen. Wait for a target
on the app's host.
- After each navigation read `location.href` and `document.title`. A redirect to
an auth wall means the session is missing; stop, or you end up "editing" the
login page.
- A hidden or occluded window can render blank panels. Call `Page.bringToFront`
before judging what rendered from a screenshot.
## Clicking and typing reliably
- **Coordinates:** `Input.dispatchMouseEvent` takes CSS pixels; screenshots are
device pixels. Divide by `devicePixelRatio` (or screenshot width / `innerWidth`).
Mixing them lands on the neighbouring control.
- **Get targets from the DOM:** `getBoundingClientRect()` and click the centre.
Skip zero-size matches; pages often keep a hidden duplicate of a button.
- **Browser UI and dialogs in shadow DOM** (settings pages, confirm bubbles) do
not show up in `querySelectorAll`. Read `Accessibility.getFullAXTree`, pick the
node by role + name (the last match when the page and the dialog share a
label), then `DOM.resolveNode` + `Runtime.callFunctionOn` with
`function(){this.click()}`.
- **File inputs:** `DOM.setFileInputFiles` on the `input[type=file]` node; order
of the list is kept.
- **Rich-text editors** ignore value assignment. Focus the editable element and
use `Input.insertText`, with real key events for line breaks.
- **Serialize dependent actions.** After a click, submit or navigation, read the
new state before the next action. Batched input lands on the previous screen.
- **Long async in-page work** (hundreds of in-page `fetch` calls): start it
without awaiting, write results to a `window.__results` object, and poll its
size. A single awaited evaluate hits client timeouts.
## Human handoff (captcha, 2FA)
When a human solves a challenge and hands the window back, it is on a clock.
Stay in that exact window: no reload, no new tab. Select an option, read back
that it is selected (`input.checked`), then submit; submitting the default sends
the wrong choice. Undo a wrong step with the page's own back control, since a
reload drops the post-challenge state. After submit, read `innerText` and look at
a screenshot: a modal or spinner can cover the page while the text still shows
the old form. If the challenge returns, stop and hand it back with the exact next
click. Never type passwords or codes yourself; that step belongs to the user or
a credential vault.
## Read-only audits
When the user says "read-only, change nothing": only navigation, tab switches,
pagination and unsaved report filters. Never press save, dismiss, create or edit
buttons, never click ads or calls to action. Close any panel opened by a
misclick without submitting and say so. Answer per section with verbatim text,
numbers in a table, and saved screenshot paths. Copy each screenshot to a work
folder right after capture; cache files get pruned.
## Pitfalls
- **Copying cookies from the real profile into the debug profile.** Session
cookies are encrypted with a key tied to the data directory; in another
directory they decrypt to garbage and the site shows its login wall. The one
manual login is the reliable path.
- **Pointing `--user-data-dir` at the default directory itself**, spelled out
in full: it is still the default and the port stays closed.
- **Pointing it at `<profile>/Default`** to reuse a session creates a nested
`Default/Default` tree with an empty session.
- **Wrong binary path.** `where`/`which` can come back empty; check the install
folder directly.
- **Headless detection.** A headless browser reports `HeadlessChrome` in its
user agent and `navigator.webdriver = true`; some bot walls block it outright,
and spoofing the user agent does not always help. Use the headed debug profile.
- **Locked desktop session.** GUI-level drivers fail at a lock screen even when
the window looks visible. Check the session is unlocked before blaming the page.
- **Reading messages marks them read.** Opening a messaging web client through
automation sends read receipts like a human would.
## Verification
- `/json/version` answers and the target URL is on the app's host.
- Every write is read back from the page (field value, saved banner, reloaded
state), not inferred from the click succeeding.
- Report what changed, what was only read, and any window you opened and closed.