Skip to content

Instantly share code, notes, and snippets.

@aabccd021
Created September 5, 2025 12:19
Show Gist options
  • Select an option

  • Save aabccd021/911a26e80cd3981ac8b9eea93e5de30c to your computer and use it in GitHub Desktop.

Select an option

Save aabccd021/911a26e80cd3981ac8b9eea93e5de30c to your computer and use it in GitHub Desktop.
Simple Chrome Devtools Protocol Example
import * as fs from "node:fs";
import * as os from "node:os";
import * as child_process from "node:child_process";
function send(ws, pending, req) {
return new Promise((resolve) => {
const reqId = id++;
pending.set(reqId, resolve);
ws.send(JSON.stringify({ id: reqId, ...req }));
});
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
child_process.execSync('pkill -9 chrome || true', { stdio: 'ignore' });
await sleep(1000);
const chrome = child_process.spawn("google-chrome-stable", [
`--remote-debugging-port=9222`,
`--user-data-dir=${os.tmpdir()}`,
"--no-first-run",
"https://google.com"
])
await sleep(2000);
const resp = await fetch("http://127.0.0.1:9222/json");
const tabs = await resp.json();
const wsUrl = tabs[0].webSocketDebuggerUrl;
const ws = new WebSocket(wsUrl);
let id = 1;
const pending = new Map();
ws.addEventListener("message", (event) => {
const data = JSON.parse(event.data);
const resolve = pending.get(data.id)
resolve?.()
pending.delete(data.id);
});
ws.addEventListener("open", async () => {
await send(ws, pending, { method: "Page.enable" });
await send(ws, pending, { method: "Page.navigate", params: { url: "https://example.com" } });
await sleep(2000);
await send(ws, pending, { method: "Page.reload" });
await sleep(10_000);
ws.close();
chrome.kill();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment