If you ever used Puppeteer, Playwright or even Selenium WebDriver, you were talking to the browser through CDP without knowing it.
CDP stands for Chrome DevTools Protocol. It is a protocol that allows you to inspect, debug and control a Chromium based browser programmatically. It works over WebSocket and exposes almost everything the browser can do.
To test it yourself, first install the websocket-client library:
pip install websocket-client
Then close all Chrome instances and start Chrome with remote debugging enabled:
chrome.exe --remote-debugging-port=9222
Open another terminal and run this script:
import json
import requests
import websocket
# Get the WebSocket URL from Chrome
resp = requests.get("http://localhost:9222/json/version")
ws_url = resp.json()["webSocketDebuggerUrl"]
ws = websocket.create_connection(ws_url)
# Open a new tab and navigate to a page
cmd = {
"id": 1,
"method": "Target.createTarget",
"params": {"url": "https://example.com"}
}
ws.send(json.dumps(cmd))
result = json.loads(ws.recv())
print("Tab opened:", result["result"]["targetId"])
ws.close()
If you run this, Chrome will open a new tab pointing to example.com. The script prints the targetId of the new tab.
You can also take a screenshot of a page without any screenshot tool. After opening the tab, send this command:
cmd = {
"id": 2,
"method": "Page.captureScreenshot",
"params": {"format": "png"}
}
ws.send(json.dumps(cmd))
result = json.loads(ws.recv())
with open("screenshot.png", "wb") as f:
import base64
f.write(base64.b64decode(result["result"]["data"]))
print("Screenshot saved as screenshot.png")
Run the full script below. It will open a new tab, navigate to example.com, take a screenshot and save it to disk.
import json
import base64
import requests
import websocket
resp = requests.get("http://localhost:9222/json/version")
ws_url = resp.json()["webSocketDebuggerUrl"]
ws = websocket.create_connection(ws_url)
cmd_open = {
"id": 1,
"method": "Target.createTarget",
"params": {"url": "https://example.com"}
}
ws.send(json.dumps(cmd_open))
ws.recv()
cmd_ss = {
"id": 2,
"method": "Page.captureScreenshot",
"params": {"format": "png"}
}
ws.send(json.dumps(cmd_ss))
result = json.loads(ws.recv())
with open("screenshot.png", "wb") as f:
f.write(base64.b64decode(result["result"]["data"]))
print("Screenshot saved as screenshot.png")
ws.close()
CDP is the low level protocol that tools like Puppeteer wrap into a friendlier API. Understanding it helps when you need to do something those tools do not expose.
That's all for now.
Thanks for reading!
Top comments (0)